context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using System.Reflection;
using Sandbox.ModAPI;
using VRage.Game;
using VRage.Game.Components;
using VRage.Game.ModAPI;
using VRage.ModAPI;
using SEPC.Collections;
using SEPC.Components.Stores;
using SEPC.Logging;
namespace SEPC.Components
{
/// <summary>
/// Holds a ComponentStore and propagates events, updates, and entity changes to it.
/// Provides thread-safe component registration and event raising.
/// Receives events from MySession.
/// </summary>
public class ComponentSession
{
static ComponentCollectionStore ComponentStore;
static LockedDeque<Action> ExternalRegistrations;
static RunStatus Status;
#region Registration and event raising
/// <param name="unregisterOnClosing">Leave as null if you plan on manually unregistering</param>
public static void RegisterUpdateHandler(uint frequency, Action toInvoke, IMyEntity unregisterOnClosing = null)
{
var assembly = Assembly.GetCallingAssembly();
ExternalRegistrations?.AddTail(() => {
ComponentStore.AddUpdateHandler(frequency, toInvoke, assembly);
if (unregisterOnClosing != null)
unregisterOnClosing.OnClosing += (entity) => ComponentStore.RemoveUpdateHandler(frequency, toInvoke);
});
}
public static void UnregisterUpdateHandler(uint frequency, Action toInvoke)
{
ExternalRegistrations?.AddTail(() => {
ComponentStore.RemoveUpdateHandler(frequency, toInvoke);
});
}
public static void RegisterComponentGroup(int group)
{
var collection = ComponentRegistrar.GetComponents(Assembly.GetCallingAssembly(), group);
ExternalRegistrations?.AddTail(() => {
ComponentStore.TryAddCollection(collection);
});
}
public static void RaiseSessionEvent(string eventName)
{
ExternalRegistrations?.AddTail(() => {
ComponentStore.RaiseSessionEvent(eventName); ;
});
}
/// <summary>
/// NOT thread-safe, but allows us to immediately raise an event instead of deferring it to the next frame.
/// This is useful for events that would be propagated too late if delayed til the next frame, like UpdatingStopped (next frame comes after UpdatingResumed).
/// </summary>
/// <param name="eventName"></param>
public static void RaiseSessionEventImmediately(string eventName)
{
ComponentStore.RaiseSessionEvent(eventName);
}
public static void RaiseEntityEvent(string eventName, IMyEntity entity)
{
ExternalRegistrations?.AddTail(() => {
ComponentStore.RaiseEntityEvent(eventName, entity); ;
});
}
#endregion
#region Lifecycle
/// <summary>
/// Resets the status for a new session.
/// Called by SEPC.App.MySession only.
/// </summary>
public static void Open()
{
Logger.DebugLog("Components.Session.SessionOpened()");
Status = RunStatus.NotInitialized;
}
/// <summary>
/// Initializes once MySession is ready, runs external actions, and propagates updates to the store.
/// Called by SEPC.App.MySession only.
/// </summary>
public static void Update()
{
try
{
if (Status == RunStatus.Terminated)
return;
if (Status == RunStatus.NotInitialized)
{
TryInitialize();
return;
}
if (ExternalRegistrations.Count != 0)
ExternalRegistrations.PopHeadInvokeAll();
ComponentStore.Update();
}
catch (Exception error)
{
Logger.Log("Error: " + error, Severity.Level.FATAL);
Status = RunStatus.Terminated;
}
}
/// <summary>
/// Releases all resources and marks as terminated.
/// Called by SEPC.App.MySession only.
/// </summary>
public static void Close()
{
Logger.DebugLog("Terminating");
if (ComponentStore != null)
ComponentStore.RaiseSessionEvent(ComponentEventNames.SessionClose);
MyAPIGateway.Entities.OnEntityAdd -= EntityAdded;
// clear fields in case SE doesn't clean up properly
ComponentStore = null;
ExternalRegistrations = null;
Status = RunStatus.Terminated;
}
private static void TryInitialize()
{
// return unless session ready
if (MyAPIGateway.CubeBuilder == null || MyAPIGateway.Entities == null || MyAPIGateway.Multiplayer == null || MyAPIGateway.Parallel == null
|| MyAPIGateway.Players == null || MyAPIGateway.Session == null || MyAPIGateway.TerminalActionsHelper == null || MyAPIGateway.Utilities == null ||
(!MyAPIGateway.Multiplayer.IsServer && MyAPIGateway.Session.Player == null))
return;
var runningOn = !MyAPIGateway.Multiplayer.MultiplayerActive ? RunLocation.Both : (MyAPIGateway.Multiplayer.IsServer ? RunLocation.Server : RunLocation.Client);
Logger.DebugLog($"Initializing. RunningOn: {runningOn}, SessionName: {MyAPIGateway.Session.Name}, SessionPath: {MyAPIGateway.Session.CurrentPath}");
ComponentStore = new ComponentCollectionStore(runningOn);
ExternalRegistrations = new LockedDeque<Action>();
MyAPIGateway.Entities.OnEntityAdd += EntityAdded;
var entities = new HashSet<IMyEntity>();
MyAPIGateway.Entities.GetEntities(entities);
foreach (IMyEntity entity in entities)
EntityAdded(entity);
foreach (var collection in ComponentRegistrar.GetInitComponents())
ComponentStore.TryAddCollection(collection);
Status = RunStatus.Initialized;
}
#endregion
#region Entity Add/Remove Handlers
private static void EntityAdded(IMyEntity entity)
{
ComponentStore.AddEntity(entity);
entity.OnClosing += EntityRemoved;
// CubeBlocks aren't included in Entities.OnEntityAdd
IMyCubeGrid asGrid = entity as IMyCubeGrid;
if (asGrid != null && asGrid.Save)
{
var blocksInGrid = new List<IMySlimBlock>();
asGrid.GetBlocks(blocksInGrid, slim => slim.FatBlock != null);
foreach (IMySlimBlock slim in blocksInGrid)
BlockAdded(slim);
asGrid.OnBlockAdded += BlockAdded;
}
}
private static void BlockAdded(IMySlimBlock entity)
{
IMyCubeBlock asBlock = entity.FatBlock;
if (asBlock != null)
EntityAdded(asBlock);
}
private static void EntityRemoved(IMyEntity entity)
{
// Attached to entities themselves, so can be called after terminated
if (ComponentStore != null)
ComponentStore.RemoveEntity(entity);
entity.OnClosing -= EntityRemoved;
// CubeBlocks aren't included in Entities.OnEntityAdd
IMyCubeGrid asGrid = entity as IMyCubeGrid;
if (asGrid != null)
asGrid.OnBlockAdded -= BlockAdded;
}
#endregion
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_OXCROPS
{
using System;
using System.Text;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// This class is designed to verify the response buffer formats of Fast Transfer ROPs.
/// </summary>
[TestClass]
public class S10_FastTransferROPs : TestSuiteBase
{
#region Class Initialization and Cleanup
/// <summary>
/// Class initialize.
/// </summary>
/// <param name="testContext">The session context handle</param>
[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
}
/// <summary>
/// Class cleanup.
/// </summary>
[ClassCleanup]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
#endregion
#region Test Cases
/// <summary>
/// This method tests the ROP buffers of RopFastTransferSourceCopyMessages.
/// </summary>
[TestCategory("MSOXCROPS"), TestMethod()]
public void MSOXCROPS_S10_TC01_TestRopFastTransferSourceCopyMessages()
{
this.CheckTransportIsSupported();
this.cropsAdapter.RpcConnect(
Common.GetConfigurationPropertyValue("SutComputerName", this.Site),
ConnectionType.PrivateMailboxServer,
Common.GetConfigurationPropertyValue("UserEssdn", this.Site),
Common.GetConfigurationPropertyValue("Domain", this.Site),
Common.GetConfigurationPropertyValue("AdminUserName", this.Site),
Common.GetConfigurationPropertyValue("PassWord", this.Site));
// Step 1: Send the RopCreateMessage request to create a message
#region RopCreateMessage success response
// Log on to the private mailbox.
RopLogonResponse logonResponse = Logon(LogonType.Mailbox, this.userDN, out inputObjHandle);
// Create a message
RopCreateMessageRequest createMessageRequest = new RopCreateMessageRequest();
RopCreateMessageResponse createMessageResponse;
createMessageRequest.RopId = (byte)RopId.RopCreateMessage;
createMessageRequest.LogonId = TestSuiteBase.LogonId;
createMessageRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
createMessageRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1;
// Set CodePageId to 0x0FFF, which specified the code page of Logon object will be used.
createMessageRequest.CodePageId = TestSuiteBase.CodePageId;
// Create a message in INBOX
createMessageRequest.FolderId = logonResponse.FolderIds[4];
// Set AssociatedFlag to 0x00(FALSE), which specifies the message is not a folder associated information (FAI) message.
createMessageRequest.AssociatedFlag = Convert.ToByte(TestSuiteBase.Zero);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 1: Begin to send the RopCreateMessage request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
createMessageRequest,
this.inputObjHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
createMessageResponse = (RopCreateMessageResponse)response;
Site.Assert.AreEqual<uint>(
TestSuiteBase.SuccessReturnValue,
createMessageResponse.ReturnValue,
"if ROP succeeds, the ReturnValue of its response is 0(success)");
uint targetMessageHandle = responseSOHs[0][createMessageResponse.OutputHandleIndex];
#endregion
// Step 2: Send the RopSaveChangesMessage request to save changes
#region RopSaveChangesMessage success response
// Save message
RopSaveChangesMessageRequest saveChangesMessageRequest;
RopSaveChangesMessageResponse saveChangesMessageResponse;
saveChangesMessageRequest.RopId = (byte)RopId.RopSaveChangesMessage;
saveChangesMessageRequest.LogonId = TestSuiteBase.LogonId;
saveChangesMessageRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
saveChangesMessageRequest.ResponseHandleIndex = TestSuiteBase.ResponseHandleIndex1;
saveChangesMessageRequest.SaveFlags = (byte)SaveFlags.ForceSave;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 2: Begin to send the RopSaveChangesMessage request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
saveChangesMessageRequest,
targetMessageHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
saveChangesMessageResponse = (RopSaveChangesMessageResponse)response;
Site.Assert.AreEqual<uint>(
TestSuiteBase.SuccessReturnValue,
saveChangesMessageResponse.ReturnValue,
"If ROP succeeds, the ReturnValue of its response is 0 (success).");
ulong messageId = saveChangesMessageResponse.MessageId;
#endregion
// Step 3: Send the RopOpenFolder request to open folder containing created message
#region RopOpenFoldersuccess response
// Open the folder(Inbox) containing the created message
RopOpenFolderRequest openFolderRequest;
RopOpenFolderResponse openFolderResponse;
openFolderRequest.RopId = (byte)RopId.RopOpenFolder;
openFolderRequest.LogonId = TestSuiteBase.LogonId;
openFolderRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
openFolderRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1;
// Inbox will be opened
openFolderRequest.FolderId = logonResponse.FolderIds[4];
openFolderRequest.OpenModeFlags = (byte)FolderOpenModeFlags.None;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 3: Begin to send the RopOpenFolder request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
openFolderRequest,
this.inputObjHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
openFolderResponse = (RopOpenFolderResponse)response;
Site.Assert.AreEqual<uint>(
TestSuiteBase.SuccessReturnValue,
openFolderResponse.ReturnValue,
"If ROP succeeds, the ReturnValue of its response is 0 (success).");
uint folderHandle = responseSOHs[0][openFolderResponse.OutputHandleIndex];
ulong[] messageIds = new ulong[1];
messageIds[0] = messageId;
#endregion
// Step 4: Send the RopFastTransferSourceCopyMessages request to verify success response
#region RopFastTransferSourceCopyMessages success response
RopFastTransferSourceCopyMessagesRequest fastTransferSourceCopyMessagesRequest;
RopFastTransferSourceCopyMessagesResponse fastTransferSourceCopyMessagesResponse;
fastTransferSourceCopyMessagesRequest.RopId = (byte)RopId.RopFastTransferSourceCopyMessages;
fastTransferSourceCopyMessagesRequest.LogonId = TestSuiteBase.LogonId;
fastTransferSourceCopyMessagesRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
fastTransferSourceCopyMessagesRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1;
fastTransferSourceCopyMessagesRequest.MessageIdCount = (ushort)messageIds.Length;
fastTransferSourceCopyMessagesRequest.MessageIds = messageIds;
fastTransferSourceCopyMessagesRequest.CopyFlags = (byte)RopFastTransferSourceCopyMessagesCopyFlags.BestBody;
fastTransferSourceCopyMessagesRequest.SendOptions = (byte)SendOptions.ForceUnicode;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 4: Begin to send the RopFastTransferSourceCopyMessages request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
fastTransferSourceCopyMessagesRequest,
folderHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
fastTransferSourceCopyMessagesResponse = (RopFastTransferSourceCopyMessagesResponse)response;
Site.Assert.AreEqual<uint>(
TestSuiteBase.SuccessReturnValue,
fastTransferSourceCopyMessagesResponse.ReturnValue,
"If ROP succeeds, the ReturnValue of its response is 0 (success).");
#endregion
}
/// <summary>
/// This method tests the ROP buffers of RopFastTransferSourceGetBuffer.
/// </summary>
[TestCategory("MSOXCROPS"), TestMethod()]
public void MSOXCROPS_S10_TC02_TestRopFastTransferSourceGetBuffer()
{
this.CheckTransportIsSupported();
this.cropsAdapter.RpcConnect(
Common.GetConfigurationPropertyValue("SutComputerName", this.Site),
ConnectionType.PrivateMailboxServer,
Common.GetConfigurationPropertyValue("UserEssdn", this.Site),
Common.GetConfigurationPropertyValue("Domain", this.Site),
Common.GetConfigurationPropertyValue("AdminUserName", this.Site),
Common.GetConfigurationPropertyValue("PassWord", this.Site));
// Step 1: Send the RopCreateMessage request to create a message
#region RopCreateMessage success response
// Log on to the private mailbox.
RopLogonResponse logonResponse = Logon(LogonType.Mailbox, this.userDN, out inputObjHandle);
// Create a message
RopCreateMessageRequest createMessageRequest = new RopCreateMessageRequest();
RopCreateMessageResponse createMessageResponse;
createMessageRequest.RopId = (byte)RopId.RopCreateMessage;
createMessageRequest.LogonId = TestSuiteBase.LogonId;
createMessageRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
createMessageRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1;
// Set CodePageId to 0x0FFF, which specified the code page of Logon object will be used.
createMessageRequest.CodePageId = TestSuiteBase.CodePageId;
// Create a message in INBOX
createMessageRequest.FolderId = logonResponse.FolderIds[4];
// Set AssociatedFlag to 0x00(FALSE), which specifies the message is not a folder associated information (FAI) message.
createMessageRequest.AssociatedFlag = Convert.ToByte(TestSuiteBase.Zero);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 1: Begin to send the RopCreateMessage request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
createMessageRequest,
this.inputObjHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
createMessageResponse = (RopCreateMessageResponse)response;
Site.Assert.AreEqual<uint>(
TestSuiteBase.SuccessReturnValue,
createMessageResponse.ReturnValue,
"if ROP succeeds, the ReturnValue of its response is 0(success)");
uint targetMessageHandle = responseSOHs[0][createMessageResponse.OutputHandleIndex];
#endregion
// Step 2: Send the RopSaveChangesMessage request to save changes
#region RopSaveChangesMessage success response
// Save message
RopSaveChangesMessageRequest saveChangesMessageRequest;
RopSaveChangesMessageResponse saveChangesMessageResponse;
saveChangesMessageRequest.RopId = (byte)RopId.RopSaveChangesMessage;
saveChangesMessageRequest.LogonId = TestSuiteBase.LogonId;
saveChangesMessageRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
saveChangesMessageRequest.ResponseHandleIndex = TestSuiteBase.ResponseHandleIndex1;
saveChangesMessageRequest.SaveFlags = (byte)SaveFlags.ForceSave;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 2: Begin to send the RopSaveChangesMessage request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
saveChangesMessageRequest,
targetMessageHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
saveChangesMessageResponse = (RopSaveChangesMessageResponse)response;
Site.Assert.AreEqual<uint>(
TestSuiteBase.SuccessReturnValue,
saveChangesMessageResponse.ReturnValue,
"If ROP succeeds, the ReturnValue of its response is 0 (success).");
ulong messageId = saveChangesMessageResponse.MessageId;
#endregion
// Step 3: Send the RopOpenFolder request to open folder containing created message
#region RopOpenFoldersuccess response
// Open the folder(Inbox) containing the created message
RopOpenFolderRequest openFolderRequest;
RopOpenFolderResponse openFolderResponse;
openFolderRequest.RopId = (byte)RopId.RopOpenFolder;
openFolderRequest.LogonId = TestSuiteBase.LogonId;
openFolderRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
openFolderRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1;
// Inbox will be opened
openFolderRequest.FolderId = logonResponse.FolderIds[4];
openFolderRequest.OpenModeFlags = (byte)FolderOpenModeFlags.None;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 3: Begin to send the RopOpenFolder request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
openFolderRequest,
this.inputObjHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
openFolderResponse = (RopOpenFolderResponse)response;
Site.Assert.AreEqual<uint>(
TestSuiteBase.SuccessReturnValue,
openFolderResponse.ReturnValue,
"If ROP succeeds, the ReturnValue of its response is 0 (success).");
uint folderHandle = responseSOHs[0][openFolderResponse.OutputHandleIndex];
ulong[] messageIds = new ulong[1];
messageIds[0] = messageId;
#endregion
// Step 4: Send the RopFastTransferSourceCopyMessages request to verify success response
#region RopFastTransferSourceCopyMessages success response
RopFastTransferSourceCopyMessagesRequest fastTransferSourceCopyMessagesRequest;
RopFastTransferSourceCopyMessagesResponse fastTransferSourceCopyMessagesResponse;
fastTransferSourceCopyMessagesRequest.RopId = (byte)RopId.RopFastTransferSourceCopyMessages;
fastTransferSourceCopyMessagesRequest.LogonId = TestSuiteBase.LogonId;
fastTransferSourceCopyMessagesRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
fastTransferSourceCopyMessagesRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1;
fastTransferSourceCopyMessagesRequest.MessageIdCount = (ushort)messageIds.Length;
fastTransferSourceCopyMessagesRequest.MessageIds = messageIds;
fastTransferSourceCopyMessagesRequest.CopyFlags = (byte)RopFastTransferSourceCopyMessagesCopyFlags.BestBody;
fastTransferSourceCopyMessagesRequest.SendOptions = (byte)SendOptions.ForceUnicode;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 4: Begin to send the RopFastTransferSourceCopyMessages request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
fastTransferSourceCopyMessagesRequest,
folderHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
fastTransferSourceCopyMessagesResponse = (RopFastTransferSourceCopyMessagesResponse)response;
Site.Assert.AreEqual<uint>(
TestSuiteBase.SuccessReturnValue,
fastTransferSourceCopyMessagesResponse.ReturnValue,
"If ROP succeeds, the ReturnValue of its response is 0 (success).");
uint downloadContextHandle = responseSOHs[0][fastTransferSourceCopyMessagesResponse.OutputHandleIndex];
#endregion
// Step 5: Send the RopFastTransferSourceGetBuffer request to verify success response
#region RopFastTransferSourceGetBuffer success response
RopFastTransferSourceGetBufferRequest fastTransferSourceGetBufferRequest;
RopFastTransferSourceGetBufferResponse fastTransferSourceGetBufferResponse;
fastTransferSourceGetBufferRequest.RopId = (byte)RopId.RopFastTransferSourceGetBuffer;
fastTransferSourceGetBufferRequest.LogonId = TestSuiteBase.LogonId;
fastTransferSourceGetBufferRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
// The server determines the buffer size based on the residual size of the RPC buffer
fastTransferSourceGetBufferRequest.BufferSize = (ushort)MS_OXCROPSAdapter.BufferSize;
// This value specifies the maximum size limit when the server determines the buffer size.
// as specified in [MS-OXCROPS].
fastTransferSourceGetBufferRequest.MaximumBufferSize = TestSuiteBase.MaximumBufferSize;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 5: Begin to send the RopFastTransferSourceGetBuffer request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
fastTransferSourceGetBufferRequest,
downloadContextHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
fastTransferSourceGetBufferResponse = (RopFastTransferSourceGetBufferResponse)response;
Site.Assert.AreEqual<uint>(
TestSuiteBase.SuccessReturnValue,
fastTransferSourceGetBufferResponse.ReturnValue,
"If ROP succeeds, the ReturnValue of its response is 0 (success).");
#endregion
}
/// <summary>
/// This method tests the ROP buffers of RopFastTransferDestinationConfigure and RopFastTransferDestinationPutBuffer.
/// </summary>
[TestCategory("MSOXCROPS"), TestMethod()]
public void MSOXCROPS_S10_TC03_TestRopFastTransferDestinationPutBuffer()
{
this.CheckTransportIsSupported();
this.cropsAdapter.RpcConnect(
Common.GetConfigurationPropertyValue("SutComputerName", this.Site),
ConnectionType.PrivateMailboxServer,
Common.GetConfigurationPropertyValue("UserEssdn", this.Site),
Common.GetConfigurationPropertyValue("Domain", this.Site),
Common.GetConfigurationPropertyValue("AdminUserName", this.Site),
Common.GetConfigurationPropertyValue("PassWord", this.Site));
// Step 1: Send the RopOpenFolder request to OpenFolder
#region RopOpenFolder success response
// Log on to the private mailbox.
RopLogonResponse logonResponse = Logon(LogonType.Mailbox, this.userDN, out inputObjHandle);
// Open a folder first, then create a subfolder under the opened folder
RopOpenFolderRequest openFolderRequest;
RopOpenFolderResponse openFolderResponse;
openFolderRequest.RopId = (byte)RopId.RopOpenFolder;
openFolderRequest.LogonId = TestSuiteBase.LogonId;
openFolderRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
openFolderRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1;
openFolderRequest.FolderId = logonResponse.FolderIds[4];
openFolderRequest.OpenModeFlags = (byte)FolderOpenModeFlags.None;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 1: Begin to send the RopOpenFolder request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
openFolderRequest,
this.inputObjHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
openFolderResponse = (RopOpenFolderResponse)response;
Site.Assert.AreEqual<uint>(
TestSuiteBase.SuccessReturnValue,
openFolderResponse.ReturnValue,
"If ROP succeeds, the ReturnValue of its response is 0 (success)");
// This handle will be used as input handle in RopCreateFolder
uint openedFolderHandle = responseSOHs[0][openFolderResponse.OutputHandleIndex];
#endregion
// Step 2: Send the RopCreateFolder request to create a subfolder under the opened folder
#region RopCreateFolder success response
// Create a subfolder in opened folder
RopCreateFolderRequest createFolderRequest;
RopCreateFolderResponse createFolderResponse;
createFolderRequest.RopId = (byte)RopId.RopCreateFolder;
createFolderRequest.LogonId = TestSuiteBase.LogonId;
createFolderRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
createFolderRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1;
createFolderRequest.FolderType = (byte)FolderType.Genericfolder;
// Set UseUnicodeStrings to 0x0(FALSE), which specifies the DisplayName and Comment are not specified in Unicode.
createFolderRequest.UseUnicodeStrings = Convert.ToByte(TestSuiteBase.Zero);
// Set OpenExisting to 0xFF, which means the folder being created will be opened when it is already existed.
createFolderRequest.OpenExisting = TestSuiteBase.NonZero;
createFolderRequest.Reserved = TestSuiteBase.Reserved;
createFolderRequest.DisplayName = Encoding.ASCII.GetBytes(TestSuiteBase.DisplayNameAndCommentForNonSearchFolder + "\0");
createFolderRequest.Comment = Encoding.ASCII.GetBytes(TestSuiteBase.DisplayNameAndCommentForNonSearchFolder + "\0");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 2: Begin to send the RopCreateFolder request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
createFolderRequest,
openedFolderHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
createFolderResponse = (RopCreateFolderResponse)response;
Site.Assert.AreEqual<uint>(
TestSuiteBase.SuccessReturnValue,
createFolderResponse.ReturnValue,
"If ROP succeeds, the ReturnValue of its response is 0 (success)");
uint targetFolderHandle = responseSOHs[0][createFolderResponse.OutputHandleIndex];
#endregion
// Step 3: Send the RopFastTransferDestinationConfigure request to verify success response
#region RopFastTransferDestinationConfigure success response
RopFastTransferDestinationConfigureRequest fastTransferDestinationConfigureRequest;
RopFastTransferDestinationConfigureResponse fastTransferDestinationConfigureResponse;
fastTransferDestinationConfigureRequest.RopId = (byte)RopId.RopFastTransferDestinationConfigure;
fastTransferDestinationConfigureRequest.LogonId = TestSuiteBase.LogonId;
fastTransferDestinationConfigureRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
fastTransferDestinationConfigureRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1;
fastTransferDestinationConfigureRequest.SourceOperation = (byte)SourceOperation.CopyTo;
// The client identifies the FastTransfer operation being configured as a logical part of a larger object move operation
fastTransferDestinationConfigureRequest.CopyFlags = (byte)RopFastTransferDestinationConfigureCopyFlags.Move;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 3: Begin to send the RopFastTransferDestinationConfigure request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
fastTransferDestinationConfigureRequest,
targetFolderHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
fastTransferDestinationConfigureResponse = (RopFastTransferDestinationConfigureResponse)response;
Site.Assert.AreEqual<uint>(
TestSuiteBase.SuccessReturnValue,
fastTransferDestinationConfigureResponse.ReturnValue,
"If ROP succeeds, the ReturnValue of its response is 0 (success)");
uint fastTranferUploadContextHandle = responseSOHs[0][fastTransferDestinationConfigureResponse.OutputHandleIndex];
#endregion
// Step 4: Send the RopFastTransferDestinationPutBuffer request to verify success response
#region RopFastTransferDestinationPutBuffer success response
RopFastTransferDestinationPutBufferRequest fastTransferDestinationPutBufferRequest;
// Set to a marker value (StartTopFld) refer to the table in MS-OXCFXICS.
byte[] transferData = { 0x03, 0x00, 0x09, 0x40 };
fastTransferDestinationPutBufferRequest.RopId = (byte)RopId.RopFastTransferDestinationPutBuffer;
fastTransferDestinationPutBufferRequest.LogonId = TestSuiteBase.LogonId;
fastTransferDestinationPutBufferRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
fastTransferDestinationPutBufferRequest.TransferDataSize = (ushort)transferData.Length;
fastTransferDestinationPutBufferRequest.TransferData = transferData;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 4: Begin to send the RopFastTransferDestinationPutBuffer request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
fastTransferDestinationPutBufferRequest,
fastTranferUploadContextHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
#endregion
}
/// <summary>
/// This method tests the ROP buffers of RopFastTransferSourceCopyFolder.
/// </summary>
[TestCategory("MSOXCROPS"), TestMethod()]
public void MSOXCROPS_S10_TC04_TestRopFastTransferSourceCopyFolder()
{
this.CheckTransportIsSupported();
this.cropsAdapter.RpcConnect(
Common.GetConfigurationPropertyValue("SutComputerName", this.Site),
ConnectionType.PrivateMailboxServer,
Common.GetConfigurationPropertyValue("UserEssdn", this.Site),
Common.GetConfigurationPropertyValue("Domain", this.Site),
Common.GetConfigurationPropertyValue("AdminUserName", this.Site),
Common.GetConfigurationPropertyValue("PassWord", this.Site));
// Step 1: Send the RopOpenFolder request to open folder
#region RopFastTransferDestinationPutBuffer success response
// Log on to the private mailbox.
RopLogonResponse logonResponse = Logon(LogonType.Mailbox, this.userDN, out inputObjHandle);
// Open a folder first, then create a subfolder under the opened folder
RopOpenFolderRequest openFolderRequest;
RopOpenFolderResponse openFolderResponse;
openFolderRequest.RopId = (byte)RopId.RopOpenFolder;
openFolderRequest.LogonId = TestSuiteBase.LogonId;
openFolderRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
openFolderRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1;
// Open root folder
openFolderRequest.FolderId = logonResponse.FolderIds[4];
openFolderRequest.OpenModeFlags = (byte)FolderOpenModeFlags.None;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 1: Begin to send the RopOpenFolder request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
openFolderRequest,
this.inputObjHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
openFolderResponse = (RopOpenFolderResponse)response;
Site.Assert.AreEqual<uint>(
TestSuiteBase.SuccessReturnValue,
openFolderResponse.ReturnValue,
"If ROP succeeds, the ReturnValue of its response is 0 (success)");
// This handle will be used as input handle in RopCreateFolder
uint openedFolderHandle = responseSOHs[0][openFolderResponse.OutputHandleIndex];
#endregion
// Step 2: Send the RopCreateFolder request to create subfolder under opened folder
#region RopCreateFolder success response
RopCreateFolderRequest createFolderRequest;
RopCreateFolderResponse createFolderResponse;
createFolderRequest.RopId = (byte)RopId.RopCreateFolder;
createFolderRequest.LogonId = TestSuiteBase.LogonId;
createFolderRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
createFolderRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1;
createFolderRequest.FolderType = (byte)FolderType.Genericfolder;
// Set UseUnicodeStrings to 0x0, which specifies the DisplayName and Comment are not specified in Unicode.
createFolderRequest.UseUnicodeStrings = Convert.ToByte(TestSuiteBase.Zero);
// Set OpenExisting to 0xFF, which means the folder being created will be opened when it is already existed.
createFolderRequest.OpenExisting = TestSuiteBase.NonZero;
createFolderRequest.Reserved = TestSuiteBase.Reserved;
createFolderRequest.DisplayName = Encoding.ASCII.GetBytes(TestSuiteBase.DisplayNameAndCommentForNonSearchFolder + "\0");
createFolderRequest.Comment = Encoding.ASCII.GetBytes(TestSuiteBase.DisplayNameAndCommentForNonSearchFolder + "\0");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 2: Begin to send the RopCreateFolder request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
createFolderRequest,
openedFolderHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
createFolderResponse = (RopCreateFolderResponse)response;
Site.Assert.AreEqual<uint>(
TestSuiteBase.SuccessReturnValue,
createFolderResponse.ReturnValue,
"If ROP succeeds, the ReturnValue of its response is 0 (success)");
uint targetFolderHandle = responseSOHs[0][createFolderResponse.OutputHandleIndex];
#endregion
// Step 3: Send the RopFastTransferSourceCopyFolder request to create subfolder under opened folder
#region RopFastTransferSourceCopyFolder success response
RopFastTransferSourceCopyFolderRequest fastTransferSourceCopyFolderRequest;
RopFastTransferSourceCopyFolderResponse fastTransferSourceCopyFolderResponse;
fastTransferSourceCopyFolderRequest.RopId = (byte)RopId.RopFastTransferSourceCopyFolder;
fastTransferSourceCopyFolderRequest.LogonId = TestSuiteBase.LogonId;
fastTransferSourceCopyFolderRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
fastTransferSourceCopyFolderRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1;
fastTransferSourceCopyFolderRequest.CopyFlags = (byte)RopFastTransferSourceCopyFolderCopyFlags.CopySubfolders;
fastTransferSourceCopyFolderRequest.SendOptions = (byte)SendOptions.ForceUnicode;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 3: Begin to send the RopFastTransferSourceCopyFolder request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
fastTransferSourceCopyFolderRequest,
targetFolderHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
fastTransferSourceCopyFolderResponse = (RopFastTransferSourceCopyFolderResponse)response;
Site.Assert.AreEqual<uint>(
TestSuiteBase.SuccessReturnValue,
fastTransferSourceCopyFolderResponse.ReturnValue,
"If ROP succeeds, the ReturnValue of its response is 0 (success)");
#endregion
}
/// <summary>
/// This method tests the ROP buffers of RopTellVersion.
/// </summary>
[TestCategory("MSOXCROPS"), TestMethod()]
public void MSOXCROPS_S10_TC05_TestRopTellVersion()
{
this.CheckTransportIsSupported();
this.cropsAdapter.RpcConnect(
Common.GetConfigurationPropertyValue("SutComputerName", this.Site),
ConnectionType.PrivateMailboxServer,
Common.GetConfigurationPropertyValue("UserEssdn", this.Site),
Common.GetConfigurationPropertyValue("Domain", this.Site),
Common.GetConfigurationPropertyValue("AdminUserName", this.Site),
Common.GetConfigurationPropertyValue("PassWord", this.Site));
// Log on to the private mailbox.
this.Logon(LogonType.Mailbox, this.userDN, out this.inputObjHandle);
RopTellVersionRequest tellVersionRequest;
ushort[] version = new ushort[3];
tellVersionRequest.RopId = (byte)RopId.RopTellVersion;
tellVersionRequest.LogonId = TestSuiteBase.LogonId;
tellVersionRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
tellVersionRequest.Version = version;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Begin to send the RopTellVersion request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
tellVersionRequest,
this.inputObjHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
}
/// <summary>
/// This method tests the ROP buffers of RopFastTransferSourceCopyTo.
/// </summary>
[TestCategory("MSOXCROPS"), TestMethod()]
public void MSOXCROPS_S10_TC06_TestRopFastTransferSourceCopyTo()
{
this.CheckTransportIsSupported();
this.cropsAdapter.RpcConnect(
Common.GetConfigurationPropertyValue("SutComputerName", this.Site),
ConnectionType.PrivateMailboxServer,
Common.GetConfigurationPropertyValue("UserEssdn", this.Site),
Common.GetConfigurationPropertyValue("Domain", this.Site),
Common.GetConfigurationPropertyValue("AdminUserName", this.Site),
Common.GetConfigurationPropertyValue("PassWord", this.Site));
// Step 1: Send the RopCreateMessage request to create a message
#region RopCreateMessage success response
// Log on to the private mailbox.
RopLogonResponse logonResponse = Logon(LogonType.Mailbox, this.userDN, out inputObjHandle);
// Create a message
RopCreateMessageRequest createMessageRequest = new RopCreateMessageRequest();
RopCreateMessageResponse createMessageResponse;
createMessageRequest.RopId = (byte)RopId.RopCreateMessage;
createMessageRequest.LogonId = TestSuiteBase.LogonId;
createMessageRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
createMessageRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1;
// Set CodePageId to 0x0FFF, which specified the code page of Logon object will be used.
createMessageRequest.CodePageId = TestSuiteBase.CodePageId;
// Create a message in INBOX
createMessageRequest.FolderId = logonResponse.FolderIds[4];
// Set AssociatedFlag to 0x00(FALSE), which specifies the message is not a folder associated information (FAI) message.
createMessageRequest.AssociatedFlag = Convert.ToByte(TestSuiteBase.Zero);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 1: Begin to send the RopCreateMessage request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
createMessageRequest,
this.inputObjHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
createMessageResponse = (RopCreateMessageResponse)response;
Site.Assert.AreEqual<uint>(
TestSuiteBase.SuccessReturnValue,
createMessageResponse.ReturnValue,
"if ROP succeeds, the ReturnValue of its response is 0(success)");
uint targetMessageHandle = responseSOHs[0][createMessageResponse.OutputHandleIndex];
#endregion
// Step 2: Send the RopSaveChangesMessage request to save changes
#region RopSaveChangesMessage success response
// Save message
RopSaveChangesMessageRequest saveChangesMessageRequest;
RopSaveChangesMessageResponse saveChangesMessageResponse;
saveChangesMessageRequest.RopId = (byte)RopId.RopSaveChangesMessage;
saveChangesMessageRequest.LogonId = TestSuiteBase.LogonId;
saveChangesMessageRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
saveChangesMessageRequest.ResponseHandleIndex = TestSuiteBase.ResponseHandleIndex1;
saveChangesMessageRequest.SaveFlags = (byte)SaveFlags.ForceSave;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 2: Begin to send the RopSaveChangesMessage request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
saveChangesMessageRequest,
targetMessageHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
saveChangesMessageResponse = (RopSaveChangesMessageResponse)response;
Site.Assert.AreEqual<uint>(
TestSuiteBase.SuccessReturnValue,
saveChangesMessageResponse.ReturnValue,
"If ROP succeeds, the ReturnValue of its response is 0 (success).");
#endregion
// Step 3: Send the RopFastTransferSourceCopyTo request to verify success response
#region RopFastTransferSourceCopyTo response
RopFastTransferSourceCopyToRequest fastTransferSourceCopyToRequest;
RopFastTransferSourceCopyToResponse fastTransferSourceCopyToResponse;
PropertyTag[] messagePropertyTags = this.CreateMessageSamplePropertyTags();
fastTransferSourceCopyToRequest.RopId = (byte)RopId.RopFastTransferSourceCopyTo;
fastTransferSourceCopyToRequest.LogonId = TestSuiteBase.LogonId;
fastTransferSourceCopyToRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
fastTransferSourceCopyToRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1;
// This value specifies the level at which the copy is occurring, which is specified in [MS-OXCROPS]
// Non-Zero: exclude all descendant sub-objects from being copied
fastTransferSourceCopyToRequest.Level = TestSuiteBase.LevelOfZero;
fastTransferSourceCopyToRequest.CopyFlags = (uint)RopFastTransferSourceCopyToCopyFlags.BestBody;
fastTransferSourceCopyToRequest.SendOptions = (byte)SendOptions.Unicode;
fastTransferSourceCopyToRequest.PropertyTagCount = (ushort)messagePropertyTags.Length;
fastTransferSourceCopyToRequest.PropertyTags = messagePropertyTags;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 3: Begin to send the RopFastTransferSourceCopyTo request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
fastTransferSourceCopyToRequest,
targetMessageHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
fastTransferSourceCopyToResponse = (RopFastTransferSourceCopyToResponse)response;
Site.Assert.AreEqual<uint>(
TestSuiteBase.SuccessReturnValue,
fastTransferSourceCopyToResponse.ReturnValue,
"If ROP succeeds, the ReturnValue of its response is 0 (success).");
#endregion
}
/// <summary>
/// This method tests the ROP buffers of RopFastTransferSourceCopyProperties.
/// </summary>
[TestCategory("MSOXCROPS"), TestMethod()]
public void MSOXCROPS_S10_TC07_TestRopFastTransferSourceCopyProperties()
{
this.CheckTransportIsSupported();
this.cropsAdapter.RpcConnect(
Common.GetConfigurationPropertyValue("SutComputerName", this.Site),
ConnectionType.PrivateMailboxServer,
Common.GetConfigurationPropertyValue("UserEssdn", this.Site),
Common.GetConfigurationPropertyValue("Domain", this.Site),
Common.GetConfigurationPropertyValue("AdminUserName", this.Site),
Common.GetConfigurationPropertyValue("PassWord", this.Site));
// Step 1: Send the RopCreateMessage request to create a message
#region RopCreateMessage success response
// Log on to the private mailbox.
RopLogonResponse logonResponse = Logon(LogonType.Mailbox, this.userDN, out inputObjHandle);
// Create a message
RopCreateMessageRequest createMessageRequest = new RopCreateMessageRequest();
RopCreateMessageResponse createMessageResponse;
createMessageRequest.RopId = (byte)RopId.RopCreateMessage;
createMessageRequest.LogonId = TestSuiteBase.LogonId;
createMessageRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
createMessageRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1;
// Set CodePageId to 0x0FFF, which specified the code page of Logon object will be used.
createMessageRequest.CodePageId = TestSuiteBase.CodePageId;
// Create a message in INBOX
createMessageRequest.FolderId = logonResponse.FolderIds[4];
// Set AssociatedFlag to 0x00(FALSE), which specifies the message is not a folder associated information (FAI) message.
createMessageRequest.AssociatedFlag = Convert.ToByte(TestSuiteBase.Zero);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 1: Begin to send the RopCreateMessage request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
createMessageRequest,
this.inputObjHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
createMessageResponse = (RopCreateMessageResponse)response;
Site.Assert.AreEqual<uint>(
TestSuiteBase.SuccessReturnValue,
createMessageResponse.ReturnValue,
"if ROP succeeds, the ReturnValue of its response is 0(success)");
uint targetMessageHandle = responseSOHs[0][createMessageResponse.OutputHandleIndex];
#endregion
// Step 2: Send the RopSaveChangesMessage request to save changes
#region RopSaveChangesMessage success response
// Save message
RopSaveChangesMessageRequest saveChangesMessageRequest;
RopSaveChangesMessageResponse saveChangesMessageResponse;
saveChangesMessageRequest.RopId = (byte)RopId.RopSaveChangesMessage;
saveChangesMessageRequest.LogonId = TestSuiteBase.LogonId;
saveChangesMessageRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
saveChangesMessageRequest.ResponseHandleIndex = TestSuiteBase.ResponseHandleIndex1;
saveChangesMessageRequest.SaveFlags = (byte)SaveFlags.ForceSave;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 2: Begin to send the RopSaveChangesMessage request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
saveChangesMessageRequest,
targetMessageHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
saveChangesMessageResponse = (RopSaveChangesMessageResponse)response;
Site.Assert.AreEqual<uint>(
TestSuiteBase.SuccessReturnValue,
saveChangesMessageResponse.ReturnValue,
"If ROP succeeds, the ReturnValue of its response is 0 (success).");
#endregion
// Step 3: Send the RopFastTransferSourceCopyTo request to verify success response
#region RopFastTransferSourceCopyTo response
RopFastTransferSourceCopyPropertiesRequest fastTransferSourceCopyPropertiesRequest;
PropertyTag[] messagePropertyTags = this.CreateMessageSamplePropertyTags();
fastTransferSourceCopyPropertiesRequest.RopId = (byte)RopId.RopFastTransferSourceCopyProperties;
fastTransferSourceCopyPropertiesRequest.LogonId = TestSuiteBase.LogonId;
fastTransferSourceCopyPropertiesRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
fastTransferSourceCopyPropertiesRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1;
// This value specifies the level at which the copy is occurring, which is specified in [MS-OXCROPS].
fastTransferSourceCopyPropertiesRequest.Level = TestSuiteBase.LevelOfNonZero;
// Move: the client identifies the FastTransfer operation being configured as a logical part of a larger object move operation.
fastTransferSourceCopyPropertiesRequest.CopyFlags = (byte)RopFastTransferSourceCopyPropertiesCopyFlags.Move;
fastTransferSourceCopyPropertiesRequest.SendOptions = (byte)SendOptions.Unicode;
fastTransferSourceCopyPropertiesRequest.PropertyTagCount = (ushort)messagePropertyTags.Length;
fastTransferSourceCopyPropertiesRequest.PropertyTags = messagePropertyTags;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 3: Begin to send the RopFastTransferSourceCopyProperties request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
fastTransferSourceCopyPropertiesRequest,
targetMessageHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
#endregion
}
/// <summary>
/// This method tests the ROP buffers of RopFastTransferDestinationPutBufferExtended.
/// </summary>
[TestCategory("MSOXCROPS"), TestMethod()]
public void MSOXCROPS_S10_TC08_TestRopFastTransferDestinationPutBufferExtended()
{
this.CheckTransportIsSupported();
this.cropsAdapter.RpcConnect(
Common.GetConfigurationPropertyValue("SutComputerName", this.Site),
ConnectionType.PrivateMailboxServer,
Common.GetConfigurationPropertyValue("UserEssdn", this.Site),
Common.GetConfigurationPropertyValue("Domain", this.Site),
Common.GetConfigurationPropertyValue("AdminUserName", this.Site),
Common.GetConfigurationPropertyValue("PassWord", this.Site));
// Step 1: Send the RopOpenFolder request to OpenFolder
#region RopOpenFolder success response
// Log on to the private mailbox.
RopLogonResponse logonResponse = Logon(LogonType.Mailbox, this.userDN, out inputObjHandle);
// Open a folder first, then create a subfolder under the opened folder
RopOpenFolderRequest openFolderRequest;
RopOpenFolderResponse openFolderResponse;
openFolderRequest.RopId = (byte)RopId.RopOpenFolder;
openFolderRequest.LogonId = TestSuiteBase.LogonId;
openFolderRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
openFolderRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1;
openFolderRequest.FolderId = logonResponse.FolderIds[4];
openFolderRequest.OpenModeFlags = (byte)FolderOpenModeFlags.None;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 1: Begin to send the RopOpenFolder request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
openFolderRequest,
this.inputObjHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
openFolderResponse = (RopOpenFolderResponse)response;
Site.Assert.AreEqual<uint>(
TestSuiteBase.SuccessReturnValue,
openFolderResponse.ReturnValue,
"If ROP succeeds, the ReturnValue of its response is 0 (success)");
// This handle will be used as input handle in RopCreateFolder
uint openedFolderHandle = responseSOHs[0][openFolderResponse.OutputHandleIndex];
#endregion
// Step 2: Send the RopCreateFolder request to create a subfolder under the opened folder
#region RopCreateFolder success response
// Create a subfolder in opened folder
RopCreateFolderRequest createFolderRequest;
RopCreateFolderResponse createFolderResponse;
createFolderRequest.RopId = (byte)RopId.RopCreateFolder;
createFolderRequest.LogonId = TestSuiteBase.LogonId;
createFolderRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
createFolderRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1;
createFolderRequest.FolderType = (byte)FolderType.Genericfolder;
// Set UseUnicodeStrings to 0x0(FALSE), which specifies the DisplayName and Comment are not specified in Unicode.
createFolderRequest.UseUnicodeStrings = Convert.ToByte(TestSuiteBase.Zero);
// Set OpenExisting to 0xFF, which means the folder being created will be opened when it is already existed.
createFolderRequest.OpenExisting = TestSuiteBase.NonZero;
createFolderRequest.Reserved = TestSuiteBase.Reserved;
createFolderRequest.DisplayName = Encoding.ASCII.GetBytes(TestSuiteBase.DisplayNameAndCommentForNonSearchFolder + "\0");
createFolderRequest.Comment = Encoding.ASCII.GetBytes(TestSuiteBase.DisplayNameAndCommentForNonSearchFolder + "\0");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 2: Begin to send the RopCreateFolder request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
createFolderRequest,
openedFolderHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
createFolderResponse = (RopCreateFolderResponse)response;
Site.Assert.AreEqual<uint>(
TestSuiteBase.SuccessReturnValue,
createFolderResponse.ReturnValue,
"If ROP succeeds, the ReturnValue of its response is 0 (success)");
uint targetFolderHandle = responseSOHs[0][createFolderResponse.OutputHandleIndex];
#endregion
// Step 3: Send the RopFastTransferDestinationConfigure request to verify success response
#region RopFastTransferDestinationConfigure success response
RopFastTransferDestinationConfigureRequest fastTransferDestinationConfigureRequest;
RopFastTransferDestinationConfigureResponse fastTransferDestinationConfigureResponse;
fastTransferDestinationConfigureRequest.RopId = (byte)RopId.RopFastTransferDestinationConfigure;
fastTransferDestinationConfigureRequest.LogonId = TestSuiteBase.LogonId;
fastTransferDestinationConfigureRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
fastTransferDestinationConfigureRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1;
fastTransferDestinationConfigureRequest.SourceOperation = (byte)SourceOperation.CopyTo;
// The client identifies the FastTransfer operation being configured as a logical part of a larger object move operation
fastTransferDestinationConfigureRequest.CopyFlags = (byte)RopFastTransferDestinationConfigureCopyFlags.Move;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 3: Begin to send the RopFastTransferDestinationConfigure request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
fastTransferDestinationConfigureRequest,
targetFolderHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
fastTransferDestinationConfigureResponse = (RopFastTransferDestinationConfigureResponse)response;
Site.Assert.AreEqual<uint>(
TestSuiteBase.SuccessReturnValue,
fastTransferDestinationConfigureResponse.ReturnValue,
"If ROP succeeds, the ReturnValue of its response is 0 (success)");
uint fastTranferUploadContextHandle = responseSOHs[0][fastTransferDestinationConfigureResponse.OutputHandleIndex];
#endregion
// Step 4: Send the RopFastTransferDestinationPutBufferExtended request to verify success response
#region RopFastTransferDestinationPutBufferExtended success response
RopFastTransferDestinationPutBufferExtendedRequest fastTransferDestinationPutBufferExtendedRequest;
// Set to a marker value (StartTopFld) refer to the table in MS-OXCFXICS.
byte[] transferData = { 0x03, 0x00, 0x09, 0x40 };
fastTransferDestinationPutBufferExtendedRequest.RopId = (byte)RopId.RopFastTransferDestinationPutBufferExtended;
fastTransferDestinationPutBufferExtendedRequest.LogonId = TestSuiteBase.LogonId;
fastTransferDestinationPutBufferExtendedRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
fastTransferDestinationPutBufferExtendedRequest.TransferDataSize = (ushort)transferData.Length;
fastTransferDestinationPutBufferExtendedRequest.TransferData = transferData;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 4: Begin to send the RopFastTransferDestinationPutBufferExtended request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
fastTransferDestinationPutBufferExtendedRequest,
fastTranferUploadContextHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
#endregion
}
#endregion
#region Common method
/// <summary>
/// PropertyTag for the message.
/// </summary>
/// <returns>Array of PropertyTag</returns>
private PropertyTag[] CreateMessageSamplePropertyTags()
{
PropertyTag[] propertyTags = new PropertyTag[1];
PropertyTag tag = new PropertyTag
{
PropertyId = this.propertyDictionary[PropertyNames.PidTagLastModificationTime].PropertyId,
PropertyType = this.propertyDictionary[PropertyNames.PidTagLastModificationTime].PropertyType
};
// PidTagLastModificationTime
// PtypTime
propertyTags[0] = tag;
return propertyTags;
}
#endregion
}
}
| |
// 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.Storage
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Operations operations.
/// </summary>
internal partial class Operations : IServiceOperations<StorageManagementClient>, IOperations
{
/// <summary>
/// Initializes a new instance of the Operations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal Operations(StorageManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the StorageManagementClient
/// </summary>
public StorageManagementClient Client { get; private set; }
/// <summary>
/// Lists all of the available Storage Rest API operations.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<Operation>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Storage/operations").ToString();
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<Operation>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Operation>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Provides a way for an app to not start an operation unless
** there's a reasonable chance there's enough memory
** available for the operation to succeed.
**
**
===========================================================*/
using System;
using System.IO;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.Contracts;
/*
This class allows an application to fail before starting certain
activities. The idea is to fail early instead of failing in the middle
of some long-running operation to increase the survivability of the
application and ensure you don't have to write tricky code to handle an
OOM anywhere in your app's code (which implies state corruption, meaning you
should unload the appdomain, if you have a transacted environment to ensure
rollback of individual transactions). This is an incomplete tool to attempt
hoisting all your OOM failures from anywhere in your worker methods to one
particular point where it is easier to handle an OOM failure, and you can
optionally choose to not start a workitem if it will likely fail. This does
not help the performance of your code directly (other than helping to avoid
AD unloads). The point is to avoid starting work if it is likely to fail.
The Enterprise Services team has used these memory gates effectively in the
unmanaged world for a decade.
In Whidbey, we will simply check to see if there is enough memory available
in the OS's page file & attempt to ensure there might be enough space free
within the process's address space (checking for address space fragmentation
as well). We will not commit or reserve any memory. To avoid race conditions with
other threads using MemoryFailPoints, we'll also keep track of a
process-wide amount of memory "reserved" via all currently-active
MemoryFailPoints. This has two problems:
1) This can account for memory twice. If a thread creates a
MemoryFailPoint for 100 MB then allocates 99 MB, we'll see 99 MB
less free memory and 100 MB less reserved memory. Yet, subtracting
off the 100 MB is necessary because the thread may not have started
allocating memory yet. Disposing of this class immediately after
front-loaded allocations have completed is a great idea.
2) This is still vulnerable to race conditions with other threads that don't use
MemoryFailPoints.
So this class is far from perfect. But it may be good enough to
meaningfully reduce the frequency of OutOfMemoryExceptions in managed apps.
In Orcas or later, we might allocate some memory from the OS and add it
to a allocation context for this thread. Obviously, at that point we need
some way of conveying when we release this block of memory. So, we
implemented IDisposable on this type in Whidbey and expect all users to call
this from within a using block to provide lexical scope for their memory
usage. The call to Dispose (implicit with the using block) will give us an
opportunity to release this memory, perhaps. We anticipate this will give
us the possibility of a more effective design in a future version.
In Orcas, we may also need to differentiate between allocations that would
go into the normal managed heap vs. the large object heap, or we should
consider checking for enough free space in both locations (with any
appropriate adjustments to ensure the memory is contiguous).
*/
namespace System.Runtime
{
public sealed class MemoryFailPoint : CriticalFinalizerObject, IDisposable
{
// Find the top section of user mode memory. Avoid the last 64K.
// Windows reserves that block for the kernel, apparently, and doesn't
// let us ask about that memory. But since we ask for memory in 1 MB
// chunks, we don't have to special case this. Also, we need to
// deal with 32 bit machines in 3 GB mode.
// Using Win32's GetSystemInfo should handle all this for us.
private static readonly ulong s_topOfMemory;
// Walking the address space is somewhat expensive, taking around half
// a millisecond. Doing that per transaction limits us to a max of
// ~2000 transactions/second. Instead, let's do this address space
// walk once every 10 seconds, or when we will likely fail. This
// amortization scheme can reduce the cost of a memory gate by about
// a factor of 100.
private static long s_hiddenLastKnownFreeAddressSpace = 0;
private static long s_hiddenLastTimeCheckingAddressSpace = 0;
private const int CheckThreshold = 10 * 1000; // 10 seconds
private static long LastKnownFreeAddressSpace
{
get { return Volatile.Read(ref s_hiddenLastKnownFreeAddressSpace); }
set { Volatile.Write(ref s_hiddenLastKnownFreeAddressSpace, value); }
}
private static long AddToLastKnownFreeAddressSpace(long addend)
{
return Interlocked.Add(ref s_hiddenLastKnownFreeAddressSpace, addend);
}
private static long LastTimeCheckingAddressSpace
{
get { return Volatile.Read(ref s_hiddenLastTimeCheckingAddressSpace); }
set { Volatile.Write(ref s_hiddenLastTimeCheckingAddressSpace, value); }
}
// When allocating memory segment by segment, we've hit some cases
// where there are only 22 MB of memory available on the machine,
// we need 1 16 MB segment, and the OS does not succeed in giving us
// that memory. Reasons for this could include:
// 1) The GC does allocate memory when doing a collection.
// 2) Another process on the machine could grab that memory.
// 3) Some other part of the runtime might grab this memory.
// If we build in a little padding, we can help protect
// ourselves against some of these cases, and we want to err on the
// conservative side with this class.
private const int LowMemoryFudgeFactor = 16 << 20;
// Round requested size to a 16MB multiple to have a better granularity
// when checking for available memory.
private const int MemoryCheckGranularity = 16;
// Note: This may become dynamically tunable in the future.
// Also note that we can have different segment sizes for the normal vs.
// large object heap. We currently use the max of the two.
private static readonly ulong s_GCSegmentSize = RuntimeImports.RhGetGCSegmentSize();
// For multi-threaded workers, we want to ensure that if two workers
// use a MemoryFailPoint at the same time, and they both succeed, that
// they don't trample over each other's memory. Keep a process-wide
// count of "reserved" memory, and decrement this in Dispose and
// in the critical finalizer. See
// SharedStatics.MemoryFailPointReservedMemory
private ulong _reservedMemory; // The size of this request (from user)
private bool _mustSubtractReservation; // Did we add data to SharedStatics?
static MemoryFailPoint()
{
Interop.Kernel32.SYSTEM_INFO info = new Interop.Kernel32.SYSTEM_INFO();
Interop.Kernel32.GetSystemInfo(ref info);
s_topOfMemory = (ulong)info.lpMaximumApplicationAddress;
}
// We can remove this link demand in a future version - we will
// have scenarios for this in partial trust in the future, but
// we're doing this just to restrict this in case the code below
// is somehow incorrect.
public MemoryFailPoint(int sizeInMegabytes)
{
if (sizeInMegabytes <= 0)
throw new ArgumentOutOfRangeException(nameof(sizeInMegabytes), SR.ArgumentOutOfRange_NeedNonNegNum);
ulong size = ((ulong)sizeInMegabytes) << 20;
_reservedMemory = size;
// Check to see that we both have enough memory on the system
// and that we have enough room within the user section of the
// process's address space. Also, we need to use the GC segment
// size, not the amount of memory the user wants to allocate.
// Consider correcting this to reflect free memory within the GC
// heap, and to check both the normal & large object heaps.
ulong segmentSize = (ulong)(Math.Ceiling((double)size / s_GCSegmentSize) * s_GCSegmentSize);
if (segmentSize >= s_topOfMemory)
throw new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_TooBig);
ulong requestedSizeRounded = (ulong)(Math.Ceiling((double)sizeInMegabytes / MemoryCheckGranularity) * MemoryCheckGranularity);
//re-convert into bytes
requestedSizeRounded <<= 20;
ulong availPageFile = 0; // available VM (physical + page file)
ulong totalAddressSpaceFree = 0; // non-contiguous free address space
// Check for available memory, with 2 attempts at getting more
// memory.
// Stage 0: If we don't have enough, trigger a GC.
// Stage 1: If we don't have enough, try growing the swap file.
// Stage 2: Update memory state, then fail or leave loop.
//
// (In the future, we could consider adding another stage after
// Stage 0 to run finalizers. However, before doing that make sure
// that we could abort this constructor when we call
// GC.WaitForPendingFinalizers, noting that this method uses a CER
// so it can't be aborted, and we have a critical finalizer. It
// would probably work, but do some thinking first.)
for (int stage = 0; stage < 3; stage++)
{
CheckForAvailableMemory(out availPageFile, out totalAddressSpaceFree);
// If we have enough room, then skip some stages.
// Note that multiple threads can still lead to a race condition for our free chunk
// of address space, which can't be easily solved.
ulong reserved = MemoryFailPointReservedMemory;
ulong segPlusReserved = segmentSize + reserved;
bool overflow = segPlusReserved < segmentSize || segPlusReserved < reserved;
bool needPageFile = availPageFile < (requestedSizeRounded + reserved + LowMemoryFudgeFactor) || overflow;
bool needAddressSpace = totalAddressSpaceFree < segPlusReserved || overflow;
// Ensure our cached amount of free address space is not stale.
long now = Environment.TickCount; // Handle wraparound.
if ((now > LastTimeCheckingAddressSpace + CheckThreshold || now < LastTimeCheckingAddressSpace) ||
LastKnownFreeAddressSpace < (long)segmentSize)
{
CheckForFreeAddressSpace(segmentSize, false);
}
bool needContiguousVASpace = (ulong)LastKnownFreeAddressSpace < segmentSize;
if (!needPageFile && !needAddressSpace && !needContiguousVASpace)
break;
switch (stage)
{
case 0:
// The GC will release empty segments to the OS. This will
// relieve us from having to guess whether there's
// enough memory in either GC heap, and whether
// internal fragmentation will prevent those
// allocations from succeeding.
GC.Collect();
continue;
case 1:
// Do this step if and only if the page file is too small.
if (!needPageFile)
continue;
// Attempt to grow the OS's page file. Note that we ignore
// any allocation routines from the host intentionally.
RuntimeHelpers.PrepareConstrainedRegions();
try
{
}
finally
{
// This shouldn't overflow due to the if clauses above.
UIntPtr numBytes = new UIntPtr(segmentSize);
unsafe
{
#if ENABLE_WINRT
void* pMemory = Interop.mincore.VirtualAllocFromApp(null, numBytes, Interop.Kernel32.MEM_COMMIT, Interop.Kernel32.PAGE_READWRITE);
#else
void* pMemory = Interop.Kernel32.VirtualAlloc(null, numBytes, Interop.Kernel32.MEM_COMMIT, Interop.Kernel32.PAGE_READWRITE);
#endif
if (pMemory != null)
{
bool r = Interop.Kernel32.VirtualFree(pMemory, UIntPtr.Zero, Interop.Kernel32.MEM_RELEASE);
if (!r)
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
}
}
}
continue;
case 2:
// The call to CheckForAvailableMemory above updated our
// state.
if (needPageFile || needAddressSpace)
{
InsufficientMemoryException e = new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint);
#if DEBUG
e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize,
needPageFile, needAddressSpace, needContiguousVASpace,
availPageFile >> 20, totalAddressSpaceFree >> 20,
LastKnownFreeAddressSpace >> 20, reserved);
#endif
throw e;
}
if (needContiguousVASpace)
{
InsufficientMemoryException e = new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_VAFrag);
#if DEBUG
e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize,
needPageFile, needAddressSpace, needContiguousVASpace,
availPageFile >> 20, totalAddressSpaceFree >> 20,
LastKnownFreeAddressSpace >> 20, reserved);
#endif
throw e;
}
break;
default:
Debug.Assert(false, "Fell through switch statement!");
break;
}
}
// Success - we have enough room the last time we checked.
// Now update our shared state in a somewhat atomic fashion
// and handle a simple race condition with other MemoryFailPoint instances.
AddToLastKnownFreeAddressSpace(-((long)size));
if (LastKnownFreeAddressSpace < 0)
CheckForFreeAddressSpace(segmentSize, true);
RuntimeHelpers.PrepareConstrainedRegions();
try
{
}
finally
{
AddMemoryFailPointReservation((long)size);
_mustSubtractReservation = true;
}
}
private static void CheckForAvailableMemory(out ulong availPageFile, out ulong totalAddressSpaceFree)
{
bool r;
Interop.Kernel32.MEMORYSTATUSEX memory = new Interop.Kernel32.MEMORYSTATUSEX();
r = Interop.Kernel32.GlobalMemoryStatusEx(ref memory);
if (!r)
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
availPageFile = memory.availPageFile;
totalAddressSpaceFree = memory.availVirtual;
}
// Based on the shouldThrow parameter, this will throw an exception, or
// returns whether there is enough space. In all cases, we update
// our last known free address space, hopefully avoiding needing to
// probe again.
private static unsafe bool CheckForFreeAddressSpace(ulong size, bool shouldThrow)
{
// Start walking the address space at 0. VirtualAlloc may wrap
// around the address space. We don't need to find the exact
// pages that VirtualAlloc would return - we just need to
// know whether VirtualAlloc could succeed.
ulong freeSpaceAfterGCHeap = MemFreeAfterAddress(null, size);
// We may set these without taking a lock - I don't believe
// this will hurt, as long as we never increment this number in
// the Dispose method. If we do an extra bit of checking every
// once in a while, but we avoid taking a lock, we may win.
LastKnownFreeAddressSpace = (long)freeSpaceAfterGCHeap;
LastTimeCheckingAddressSpace = Environment.TickCount;
if (freeSpaceAfterGCHeap < size && shouldThrow)
throw new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_VAFrag);
return freeSpaceAfterGCHeap >= size;
}
// Returns the amount of consecutive free memory available in a block
// of pages. If we didn't have enough address space, we still return
// a positive value < size, to help potentially avoid the overhead of
// this check if we use a MemoryFailPoint with a smaller size next.
private static unsafe ulong MemFreeAfterAddress(void* address, ulong size)
{
if (size >= s_topOfMemory)
return 0;
ulong largestFreeRegion = 0;
Interop.Kernel32.MEMORY_BASIC_INFORMATION memInfo = new Interop.Kernel32.MEMORY_BASIC_INFORMATION();
UIntPtr sizeOfMemInfo = (UIntPtr)sizeof(Interop.Kernel32.MEMORY_BASIC_INFORMATION);
while (((ulong)address) + size < s_topOfMemory)
{
UIntPtr r = Interop.Kernel32.VirtualQuery(address, ref memInfo, sizeOfMemInfo);
if (r == UIntPtr.Zero)
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
ulong regionSize = memInfo.RegionSize.ToUInt64();
if (memInfo.State == Interop.Kernel32.MEM_FREE)
{
if (regionSize >= size)
return regionSize;
else
largestFreeRegion = Math.Max(largestFreeRegion, regionSize);
}
address = (void*)((ulong)address + regionSize);
}
return largestFreeRegion;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void GetMemorySettings(out ulong maxGCSegmentSize, out ulong topOfMemory);
~MemoryFailPoint()
{
Dispose(false);
}
// Applications must call Dispose, which conceptually "releases" the
// memory that was "reserved" by the MemoryFailPoint. This affects a
// global count of reserved memory in this version (helping to throttle
// future MemoryFailPoints) in this version. We may in the
// future create an allocation context and release it in the Dispose
// method. While the finalizer will eventually free this block of
// memory, apps will help their performance greatly by calling Dispose.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
// This is just bookkeeping to ensure multiple threads can really
// get enough memory, and this does not actually reserve memory
// within the GC heap.
if (_mustSubtractReservation)
{
RuntimeHelpers.PrepareConstrainedRegions();
try
{
}
finally
{
AddMemoryFailPointReservation(-((long)_reservedMemory));
_mustSubtractReservation = false;
}
}
/*
// Prototype performance
// Let's pretend that we returned at least some free memory to
// the GC heap. We don't know this is true - the objects could
// have a longer lifetime, and the memory could be elsewhere in the
// GC heap. Additionally, we subtracted off the segment size, not
// this size. That's ok - we don't mind if this slowly degrades
// and requires us to refresh the value a little bit sooner.
// But releasing the memory here should help us avoid probing for
// free address space excessively with large workItem sizes.
Interlocked.Add(ref LastKnownFreeAddressSpace, _reservedMemory);
*/
}
// This is the total amount of memory currently "reserved" via
// all MemoryFailPoints allocated within the process.
// Stored as a long because we need to use Interlocked.Add.
private static long s_memFailPointReservedMemory;
internal static long AddMemoryFailPointReservation(long size)
{
// Size can legitimately be negative - see Dispose.
return Interlocked.Add(ref s_memFailPointReservedMemory, (long)size);
}
internal static ulong MemoryFailPointReservedMemory
{
get
{
Debug.Assert(Volatile.Read(ref s_memFailPointReservedMemory) >= 0, "Process-wide MemoryFailPoint reserved memory was negative!");
return (ulong)Volatile.Read(ref s_memFailPointReservedMemory);
}
}
#if DEBUG
internal sealed class MemoryFailPointState
{
private ulong _segmentSize;
private int _allocationSizeInMB;
private bool _needPageFile;
private bool _needAddressSpace;
private bool _needContiguousVASpace;
private ulong _availPageFile;
private ulong _totalFreeAddressSpace;
private long _lastKnownFreeAddressSpace;
private ulong _reservedMem;
private String _stackTrace; // Where did we fail, for additional debugging.
internal MemoryFailPointState(int allocationSizeInMB, ulong segmentSize, bool needPageFile, bool needAddressSpace, bool needContiguousVASpace, ulong availPageFile, ulong totalFreeAddressSpace, long lastKnownFreeAddressSpace, ulong reservedMem)
{
_allocationSizeInMB = allocationSizeInMB;
_segmentSize = segmentSize;
_needPageFile = needPageFile;
_needAddressSpace = needAddressSpace;
_needContiguousVASpace = needContiguousVASpace;
_availPageFile = availPageFile;
_totalFreeAddressSpace = totalFreeAddressSpace;
_lastKnownFreeAddressSpace = lastKnownFreeAddressSpace;
_reservedMem = reservedMem;
try
{
_stackTrace = Environment.StackTrace;
}
catch (System.Security.SecurityException)
{
_stackTrace = "no permission";
}
catch (OutOfMemoryException)
{
_stackTrace = "out of memory";
}
}
public override String ToString()
{
return String.Format(System.Globalization.CultureInfo.InvariantCulture, "MemoryFailPoint detected insufficient memory to guarantee an operation could complete. Checked for {0} MB, for allocation size of {1} MB. Need page file? {2} Need Address Space? {3} Need Contiguous address space? {4} Avail page file: {5} MB Total free VA space: {6} MB Contiguous free address space (found): {7} MB Space reserved by process's MemoryFailPoints: {8} MB",
_segmentSize >> 20, _allocationSizeInMB, _needPageFile,
_needAddressSpace, _needContiguousVASpace,
_availPageFile >> 20, _totalFreeAddressSpace >> 20,
_lastKnownFreeAddressSpace >> 20, _reservedMem);
}
}
#endif
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// 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 Alachisoft.NCache.Common.DataStructures.Clustered;
using System.Collections.Generic;
using System.Collections;
namespace Alachisoft.NCache.Common.DataStructures
{
public class OptimizedQueue<TKey,TQueueITem> where TQueueITem :ISizable
{
private HashVector _queue = new HashVector(1000);
private HashVector _keyToIndexMap = new HashVector(1000);
private HashVector _indexToKeyMap = new HashVector(1000);
private int _tail = -1;
private int _head = -1;
private bool _tailMaxReached = false;
private object _sync_mutex = new object();
private long _size;
private long _count;
public long Size
{
get { lock (_sync_mutex) { return _size; } }
}
public long Count
{
get { lock (_sync_mutex) { return _count; } }
}
public OptimizedQueue():this(10,null)
{
}
public OptimizedQueue(int size) : this(size, null)
{
}
public OptimizedQueue(int size,IEqualityComparer keyComparer)
{
_queue = new HashVector(size);
_keyToIndexMap = new HashVector(size, keyComparer);
_indexToKeyMap = new HashVector(size);
}
/// <summary>
/// Optimized Enqueue opeartion, adds the opeartion at _tail index and removes
/// any previous operations on that key from the queue
/// </summary>
/// <param name="item"></param>
public bool Enqueue(string key, TQueueITem item)
{
bool isNewItem = true;
try
{
lock (_sync_mutex)
{
if (_keyToIndexMap.ContainsKey(key)) //Optimized Queue, so checking in the map if the current cache key is already mapped to some index of Queue or not
{
//just update the old operation without chaning it's order in the queue.
int index1 = (int)_keyToIndexMap[key];
TQueueITem oldOperation = (TQueueITem)_queue[index1];
_queue[index1] = item;
isNewItem = false;
_size -= oldOperation.Size; //subtract old operation size
_size += item.Size;
return isNewItem;
}
if (_tail == int.MaxValue) //checks if the _tail value has reached the maxvalue of the long data type, so reinitialize it
{
_tail = -1;
_tailMaxReached = true;
}
int index = ++_tail;
_size += item.Size;
_queue.Add(index, item); //Add new opeartion at the tail of the queue
_keyToIndexMap[key] = index; // update (cache key, queue index) map
_indexToKeyMap[index] = key;
if (isNewItem) _count++;
}
}
catch (Exception exp)
{
throw exp;
}
finally
{
}
return isNewItem;
}
public TQueueITem Dequeue()
{
TQueueITem operation = default(TQueueITem);
try
{
lock (_sync_mutex)
{
int index = 0;
do //fetch the next valid operation from the queue
{
if (_head < _tail || _tailMaxReached) //or contition checks if the _tail has reached max long value and _head has not yet reached there , so in this case _head<_tail will fail bcz _tail has been reinitialized
{
if (_head == int.MaxValue) //checks if _head has reached the max long value, so reinitialize _head and make _tailMaxReached is set to false as _head<_tail is now again valid
{
_head = -1;
_tailMaxReached = false;
}
index = ++_head;
operation = (TQueueITem)_queue[index] ; //get key on which the operation is to be performed from the head of the queue
if (operation != null)
{
string cacheKey = _indexToKeyMap[index] as string;
_keyToIndexMap.Remove(cacheKey); //update map
_indexToKeyMap.Remove(index);
_queue.Remove(index); //update queue
_size -= operation.Size;
_count--;
}
}
else
break;
} while (operation == null);
}
}
catch (Exception exp)
{
throw exp;
}
return operation;
}
// Returns the object at the head of the queue. The object remains in the
// queue. If the queue is empty, this method throws an
// InvalidOperationException.
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Peek"]/*' />
public bool Peek(out TQueueITem item)
{
item = default(TQueueITem);
try
{
lock (_sync_mutex)
{
int index = 0;
int peekHead = _head;
do //fetch the next valid operation from the queue
{
if (peekHead < _tail) //or contition checks if the _tail has reached max long value and _head has not yet reached there , so in this case _head<_tail will fail bcz _tail has been reinitialized
{
index = ++peekHead;
item = (TQueueITem)_queue[index]; //get key on which the operation is to be performed from the head of the queue
if (item != null)
{
return true;
}
else
{
if (_head == int.MaxValue) //checks if _head has reached the max long value, so reinitialize _head and make _tailMaxReached is set to false as _head<_tail is now again valid
{
_head = -1;
_tailMaxReached = false;
}
_head++;
}
}
else
break;
} while (item == null);
}
}
catch (Exception exp)
{
throw exp;
}
return false;
}
public bool TryGetValue(TKey key,out TQueueITem value)
{
value = default(TQueueITem);
lock (_sync_mutex)
{
if (_keyToIndexMap.ContainsKey(key))
{
int index = (int)_keyToIndexMap[key];
value = (TQueueITem)_queue[index];
return true;
}
}
return false;
}
public bool ContainsKey(TKey key)
{
lock (_sync_mutex)
{
return _keyToIndexMap.ContainsKey(key);
}
}
public bool AllowRemoval(string key)
{
lock (_sync_mutex) { return !_keyToIndexMap.ContainsKey(key); }
}
public TQueueITem Remove(string key)
{
lock (_sync_mutex)
{
if (_keyToIndexMap.ContainsKey(key))
{
int index = (int)_keyToIndexMap[key];
TQueueITem operation = (TQueueITem)_queue[index];
_keyToIndexMap.Remove(key);
_indexToKeyMap.Remove(index);
_queue.Remove(index);
_size -= operation.Size;
_count--;
if (index == _head)
{
if (_head == int.MaxValue) //checks if _head has reached the max long value, so reinitialize _head and make _tailMaxReached is set to false as _head<_tail is now again valid
{
_head = -1;
_tailMaxReached = false;
}
_head++;
}
return operation;
}
}
return default(TQueueITem);
}
public bool Contains(string cacheKey)
{
lock (_sync_mutex)
{
return _keyToIndexMap.ContainsKey(cacheKey);
}
}
public TQueueITem this[string key]
{
get
{
lock (_sync_mutex)
{
if (_keyToIndexMap.ContainsKey(key))
{
int index = (int)_keyToIndexMap[key];
TQueueITem operation = (TQueueITem)_queue[index] ;
return operation;
}
}
return default(TQueueITem);
}
}
/// <summary>
/// Clears queue and helping datastructures like map, cache, itemstobereplicated
/// </summary>
public void Clear()
{
try
{
lock (_sync_mutex)
{
_queue.Clear();
_keyToIndexMap.Clear();
_indexToKeyMap.Clear();
_tail = _head = -1;
_tailMaxReached = false;
_size = 0;
_count = 0;
}
}
catch (Exception exp)
{
throw exp;
}
}
public bool IsEmpty
{
get { return _count == 0; }
}
public IEnumerator<TQueueITem> GetEnumerator()
{
lock (_sync_mutex)
{
return new ValueEnumerator(this);
}
}
#region IDisposable Members
public void Dispose()
{
lock (_sync_mutex)
{
}
}
#endregion
class ValueEnumerator : IEnumerator<TQueueITem>
{
private OptimizedQueue<TKey, TQueueITem> _parent;
private int _head, _tail;
private long _count;
private bool _tailMaxReached;
private TQueueITem _current = default(TQueueITem);
private bool _isValid = false;
public ValueEnumerator(OptimizedQueue<TKey,TQueueITem> parent)
{
_parent = parent;
Reset();
}
public TQueueITem Current
{
get
{
if (!_isValid) throw new InvalidOperationException("Enumerator is invalid");
return _current;
}
}
object IEnumerator.Current
{
get
{
if (!_isValid) throw new InvalidOperationException("Enumerator is invalid");
return _current;
}
}
public void Dispose()
{
}
public bool MoveNext()
{
_current = default(TQueueITem);
bool hasItem = false;
if (_count > 0)
{
lock (_parent._sync_mutex)
{
int index = 0;
do //fetch the next valid operation from the queue
{
if (_head < _tail || _tailMaxReached) //or contition checks if the _tail has reached max long value and _head has not yet reached there , so in this case _head<_tail will fail bcz _tail has been reinitialized
{
if (_head == int.MaxValue) //checks if _head has reached the max long value, so reinitialize _head and make _tailMaxReached is set to false as _head<_tail is now again valid
{
_head = -1;
_tailMaxReached = false;
}
index = ++_head;
_current = (TQueueITem)_parent._queue[index]; //get key on which the operation is to be performed from the head of the queue
if (_current != null)
{
_count--;
hasItem = true;
}
}
else
break;
} while (_current == null);
}
}
_isValid = hasItem;
return hasItem;
}
public void Reset()
{
_head = _parent._head;
_tail = _parent._tail;
_count = _parent._count;
_tailMaxReached = _parent._tailMaxReached;
}
}
}
}
| |
namespace dotless.Test.Specs
{
using NUnit.Framework;
using System.Collections.Generic;
public class MediaFixture : SpecFixtureBase
{
[Test]
public void MediaDirective()
{
var input = @"
@media all and (min-width: 640px) {
#header {
background-color: #123456;
}
}
";
AssertLessUnchanged(input);
}
[Test]
public void MediaDirective2()
{
var input = @"
@media handheld and (min-width: 20em), screen and (min-width: 20em) {
body {
max-width: 480px;
}
}
";
AssertLessUnchanged(input);
}
[Test]
public void MediaDirectiveEmpty()
{
var input = @"
@media only screen and (min-width: 768px) and (max-width: 959px) {
}
";
AssertLessUnchanged(input);
}
[Test]
public void MediaDirectiveEmptyWithCompressionEnabled()
{
var input = @"
@media only screen and (min-width: 768px) and (max-width: 959px) {
}
";
var createEnv = DefaultEnv;
DefaultEnv = () => {
var env = createEnv();
env.Compress = true;
return env;
};
AssertLess(input, "");
DefaultEnv = createEnv;
}
[Test]
public void MediaDirectiveCanUseVariables()
{
var input =
@"
@var: red;
@media screen {
color: @var;
#header {
background-color: @var;
}
}
";
var expected = @"
@media screen {
color: red;
#header {
background-color: red;
}
}
";
AssertLess(input, expected);
}
[Test]
public void MediaDirectiveCanDeclareVariables()
{
var input =
@"
@media screen {
@var: red;
color: @var;
#header {
background-color: @var;
}
}
";
var expected = @"
@media screen {
color: red;
#header {
background-color: red;
}
}
";
AssertLess(input, expected);
}
[Test]
public void VariablesInMediaDirective()
{
var input = @"
@handheldMinWidth: 15em;
@screenWidth: 20px;
@media handheld and (min-width: @handheldMinWidth), screen and (min-width: @screenWidth) {
body {
max-width: 480px;
}
}
";
var expected = @"
@media handheld and (min-width: 15em), screen and (min-width: 20px) {
body {
max-width: 480px;
}
}
";
AssertLess(input, expected);
}
[Test]
public void VariablesInMediaDirective2()
{
var input = @"
@smartphone: ~""only screen and (max-width: 200px)"";
@media @smartphone {
body {
max-width: 480px;
}
}
";
var expected = @"
@media only screen and (max-width: 200px) {
body {
max-width: 480px;
}
}
";
AssertLess(input, expected);
}
[Test]
public void MediaDirectiveWithDecimal()
{
var input = @"
@media only screen and (min--moz-device-pixel-ratio: 1.5) {
body {
max-width: 480px;
}
}
";
AssertLessUnchanged(input);
}
[Test]
public void MediaDirectiveWithSlash()
{
var input = @"
@media only screen and (-o-min-device-pixel-ratio: 3/2) {
body {
max-width: 480px;
}
}
";
AssertLessUnchanged(input);
}
[Test]
public void MediaDirectiveCanHavePageDirective1()
{
// see https://github.com/dotless/dotless/issues/27
var input =
@"
@media print {
@page {
margin: 0.5cm;
}
}
";
AssertLessUnchanged(input);
}
[Test]
public void MediaDirectiveCanHavePageDirective2()
{
var input =
@"
@media print {
@page :left {
margin: 0.5cm;
}
@page :right {
margin: 0.5cm;
}
@page Test:first {
margin: 1cm;
}
@page :first {
size: 8.5in 11in;
@top-left {
margin: 1cm;
}
@top-left-corner {
margin: 1cm;
}
@top-center {
margin: 1cm;
}
@top-right {
margin: 1cm;
}
@top-right-corner {
margin: 1cm;
}
@bottom-left {
margin: 1cm;
}
@bottom-left-corner {
margin: 1cm;
}
@bottom-center {
margin: 1cm;
}
@bottom-right {
margin: 1cm;
}
@bottom-right-corner {
margin: 1cm;
}
@left-top {
margin: 1cm;
}
@left-middle {
margin: 1cm;
}
@left-bottom {
margin: 1cm;
}
@right-top {
margin: 1cm;
}
@right-middle {
content: ""Page "" counter(page);
}
@right-bottom {
margin: 1cm;
}
}
}
";
AssertLessUnchanged(input);
}
[Test]
public void MediaDirectiveCanHavePageDirective3()
{
var input =
@"
@media print {
@page:first {
margin: 0.5cm;
}
}";
var expected =
@"
@media print {
@page :first {
margin: 0.5cm;
}
}";
AssertLess(input, expected);
}
[Test]
public void MediaBubbling1()
{
var input = @"
body {
@media print {
padding: 20px;
}
}";
var expected = @"
@media print {
body {
padding: 20px;
}
}
";
AssertLess(input, expected);
}
[Test]
public void MediaBubbling2()
{
var input = @"
body {
@media print {
input {
padding: 20px;
}
}
}";
var expected = @"
@media print {
body input {
padding: 20px;
}
}
";
AssertLess(input, expected);
}
[Test]
public void MediaBubbling3()
{
var input = @"
@media print {
@media (orientation:landscape) {
body {
margin-left: 20px;
}
}
}
";
var expected = @"
@media print {
}
@media print and (orientation: landscape) {
body {
margin-left: 20px;
}
}
";
AssertLess(input, expected);
}
[Test]
public void MediaBubbling4()
{
var input = @"
body {
@media print {
padding: 20px;
header {
background-color: red;
}
@media (orientation:landscape) {
margin-left: 20px;
}
}
}
";
var expected = @"
@media print {
body {
padding: 20px;
}
body header {
background-color: red;
}
}
@media print and (orientation: landscape) {
body {
margin-left: 20px;
}
}
";
AssertLess(input, expected);
}
[Test]
public void MediaBubbling5()
{
var input = @"
body {
@media a, b and c {
width: 95%;
@media x, y {
width: 100%;
}
}
}";
var expected = @"
@media a, b and c {
body {
width: 95%;
}
}
@media a and x, b and c and x, a and y, b and c and y {
body {
width: 100%;
}
}
";
AssertLess(input, expected);
}
[Test]
public void MediaBubbling6()
{
var input = @"
@media screen {
.sidebar {
width: 300px;
@media (orientation: landscape) {
width: 500px;
}
}
}";
var expected = @"
@media screen {
.sidebar {
width: 300px;
}
}
@media screen and (orientation: landscape) {
.sidebar {
width: 500px;
}
}";
AssertLess(input, expected);
}
[Test]
public void MediaBubbling7()
{
var input = @"
@media a {
.first {
@media b {
.second {
.third {
width: 300px;
@media c {
width: 500px;
}
}
.fourth {
width: 3;
}
}
}
}
}";
var expected = @"
@media a {
}
@media a and b {
.first .second .third {
width: 300px;
}
.first .second .fourth {
width: 3;
}
}
@media b and a and c {
.first .second .third {
width: 500px;
}
}
";
AssertLess(input, expected);
}
[Test]
public void MediaMixin1()
{
var input = @"
.mediaMixin(@fallback: 200px) {
background: black;
@media handheld {
background: white;
@media (max-width: @fallback) {
background: red;
}
}
}
.a {
.mediaMixin(100px);
}
";
var expected = @"
.a {
background: black;
}
@media handheld {
.a {
background: white;
}
}
@media handheld and (max-width: 100px) {
.a {
background: red;
}
}
";
AssertLess(input, expected);
}
[Test]
public void MediaMixin2()
{
var input = @"
.mediaMixin(@fallback: 200px) {
background: black;
@media handheld {
background: white;
@media (max-width: @fallback) {
background: red;
}
}
}
.b {
.mediaMixin();
}
";
var expected = @"
.b {
background: black;
}
@media handheld {
.b {
background: white;
}
}
@media handheld and (max-width: 200px) {
.b {
background: red;
}
}
";
AssertLess(input, expected);
}
[Test]
public void MediaUsesDpiUnit()
{
var input = @"
@media handheld and (min-resolution: 200dpi) {
background: red;
}
";
AssertLessUnchanged(input);
}
[Test]
public void MixinCallNotDefinition()
{
var input = @"
.mixin_def(@url, @position){
background-image: @url;
background-position: @position;
}
.error{
@s: ""/"";
.mixin_def( ""@{s}a.png"", center center);
}";
var expected = @"
.error {
background-image: ""/a.png"";
background-position: center center;
}
";
AssertLess(input, expected);
}
[Test]
public void VariableInMediaQueryWithNestedMediaBlock() {
var input = @"
@screen-sm-max: 979px;
@media (max-width: @screen-sm-max) {
.text { font-size: 14px; }
.item
{
@media (min-width: 600px) {
top: 0;
}
}
}";
var expected = @"
@media (max-width: 979px) {
.text {
font-size: 14px;
}
}
@media (max-width: 979px) and (min-width: 600px) {
.item {
top: 0;
}
}
";
AssertLess(input, expected);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gcdcv = Google.Cloud.Dialogflow.Cx.V3;
using sys = System;
namespace Google.Cloud.Dialogflow.Cx.V3
{
/// <summary>Resource name for the <c>Agent</c> resource.</summary>
public sealed partial class AgentName : gax::IResourceName, sys::IEquatable<AgentName>
{
/// <summary>The possible contents of <see cref="AgentName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/agents/{agent}</c>.
/// </summary>
ProjectLocationAgent = 1,
}
private static gax::PathTemplate s_projectLocationAgent = new gax::PathTemplate("projects/{project}/locations/{location}/agents/{agent}");
/// <summary>Creates a <see cref="AgentName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="AgentName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static AgentName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AgentName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AgentName"/> with the pattern <c>projects/{project}/locations/{location}/agents/{agent}</c>
/// .
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AgentName"/> constructed from the provided ids.</returns>
public static AgentName FromProjectLocationAgent(string projectId, string locationId, string agentId) =>
new AgentName(ResourceNameType.ProjectLocationAgent, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AgentName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AgentName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string agentId) =>
FormatProjectLocationAgent(projectId, locationId, agentId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AgentName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AgentName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}</c>.
/// </returns>
public static string FormatProjectLocationAgent(string projectId, string locationId, string agentId) =>
s_projectLocationAgent.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)));
/// <summary>Parses the given resource name string into a new <see cref="AgentName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/agents/{agent}</c></description></item>
/// </list>
/// </remarks>
/// <param name="agentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AgentName"/> if successful.</returns>
public static AgentName Parse(string agentName) => Parse(agentName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AgentName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/agents/{agent}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="agentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="AgentName"/> if successful.</returns>
public static AgentName Parse(string agentName, bool allowUnparsed) =>
TryParse(agentName, allowUnparsed, out AgentName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AgentName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/agents/{agent}</c></description></item>
/// </list>
/// </remarks>
/// <param name="agentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AgentName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string agentName, out AgentName result) => TryParse(agentName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AgentName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/agents/{agent}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="agentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AgentName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string agentName, bool allowUnparsed, out AgentName result)
{
gax::GaxPreconditions.CheckNotNull(agentName, nameof(agentName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationAgent.TryParseName(agentName, out resourceName))
{
result = FromProjectLocationAgent(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(agentName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private AgentName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string agentId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AgentId = agentId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AgentName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
public AgentName(string projectId, string locationId, string agentId) : this(ResourceNameType.ProjectLocationAgent, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Agent</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AgentId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationAgent: return s_projectLocationAgent.Expand(ProjectId, LocationId, AgentId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as AgentName);
/// <inheritdoc/>
public bool Equals(AgentName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AgentName a, AgentName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AgentName a, AgentName b) => !(a == b);
}
/// <summary>Resource name for the <c>AgentValidationResult</c> resource.</summary>
public sealed partial class AgentValidationResultName : gax::IResourceName, sys::IEquatable<AgentValidationResultName>
{
/// <summary>The possible contents of <see cref="AgentValidationResultName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/agents/{agent}/validationResult</c>
/// .
/// </summary>
ProjectLocationAgent = 1,
}
private static gax::PathTemplate s_projectLocationAgent = new gax::PathTemplate("projects/{project}/locations/{location}/agents/{agent}/validationResult");
/// <summary>Creates a <see cref="AgentValidationResultName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="AgentValidationResultName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static AgentValidationResultName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AgentValidationResultName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AgentValidationResultName"/> with the pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/validationResult</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="AgentValidationResultName"/> constructed from the provided ids.
/// </returns>
public static AgentValidationResultName FromProjectLocationAgent(string projectId, string locationId, string agentId) =>
new AgentValidationResultName(ResourceNameType.ProjectLocationAgent, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AgentValidationResultName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/validationResult</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AgentValidationResultName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/validationResult</c>.
/// </returns>
public static string Format(string projectId, string locationId, string agentId) =>
FormatProjectLocationAgent(projectId, locationId, agentId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AgentValidationResultName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/validationResult</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AgentValidationResultName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/validationResult</c>.
/// </returns>
public static string FormatProjectLocationAgent(string projectId, string locationId, string agentId) =>
s_projectLocationAgent.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="AgentValidationResultName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/agents/{agent}/validationResult</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="agentValidationResultName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AgentValidationResultName"/> if successful.</returns>
public static AgentValidationResultName Parse(string agentValidationResultName) =>
Parse(agentValidationResultName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AgentValidationResultName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/agents/{agent}/validationResult</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="agentValidationResultName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="AgentValidationResultName"/> if successful.</returns>
public static AgentValidationResultName Parse(string agentValidationResultName, bool allowUnparsed) =>
TryParse(agentValidationResultName, allowUnparsed, out AgentValidationResultName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AgentValidationResultName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/agents/{agent}/validationResult</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="agentValidationResultName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AgentValidationResultName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string agentValidationResultName, out AgentValidationResultName result) =>
TryParse(agentValidationResultName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AgentValidationResultName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/agents/{agent}/validationResult</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="agentValidationResultName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AgentValidationResultName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string agentValidationResultName, bool allowUnparsed, out AgentValidationResultName result)
{
gax::GaxPreconditions.CheckNotNull(agentValidationResultName, nameof(agentValidationResultName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationAgent.TryParseName(agentValidationResultName, out resourceName))
{
result = FromProjectLocationAgent(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(agentValidationResultName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private AgentValidationResultName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string agentId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AgentId = agentId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AgentValidationResultName"/> class from the component parts of
/// pattern <c>projects/{project}/locations/{location}/agents/{agent}/validationResult</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
public AgentValidationResultName(string projectId, string locationId, string agentId) : this(ResourceNameType.ProjectLocationAgent, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Agent</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AgentId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationAgent: return s_projectLocationAgent.Expand(ProjectId, LocationId, AgentId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as AgentValidationResultName);
/// <inheritdoc/>
public bool Equals(AgentValidationResultName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AgentValidationResultName a, AgentValidationResultName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AgentValidationResultName a, AgentValidationResultName b) => !(a == b);
}
public partial class Agent
{
/// <summary>
/// <see cref="gcdcv::AgentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdcv::AgentName AgentName
{
get => string.IsNullOrEmpty(Name) ? null : gcdcv::AgentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="FlowName"/>-typed view over the <see cref="StartFlow"/> resource name property.
/// </summary>
public FlowName StartFlowAsFlowName
{
get => string.IsNullOrEmpty(StartFlow) ? null : FlowName.Parse(StartFlow, allowUnparsed: true);
set => StartFlow = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="SecuritySettingsName"/>-typed view over the <see cref="SecuritySettings"/> resource name
/// property.
/// </summary>
public SecuritySettingsName SecuritySettingsAsSecuritySettingsName
{
get => string.IsNullOrEmpty(SecuritySettings) ? null : SecuritySettingsName.Parse(SecuritySettings, allowUnparsed: true);
set => SecuritySettings = value?.ToString() ?? "";
}
}
public partial class ListAgentsRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetAgentRequest
{
/// <summary>
/// <see cref="gcdcv::AgentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdcv::AgentName AgentName
{
get => string.IsNullOrEmpty(Name) ? null : gcdcv::AgentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateAgentRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteAgentRequest
{
/// <summary>
/// <see cref="gcdcv::AgentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdcv::AgentName AgentName
{
get => string.IsNullOrEmpty(Name) ? null : gcdcv::AgentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ExportAgentRequest
{
/// <summary>
/// <see cref="gcdcv::AgentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdcv::AgentName AgentName
{
get => string.IsNullOrEmpty(Name) ? null : gcdcv::AgentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="EnvironmentName"/>-typed view over the <see cref="Environment"/> resource name property.
/// </summary>
public EnvironmentName EnvironmentAsEnvironmentName
{
get => string.IsNullOrEmpty(Environment) ? null : EnvironmentName.Parse(Environment, allowUnparsed: true);
set => Environment = value?.ToString() ?? "";
}
}
public partial class RestoreAgentRequest
{
/// <summary>
/// <see cref="gcdcv::AgentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdcv::AgentName AgentName
{
get => string.IsNullOrEmpty(Name) ? null : gcdcv::AgentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ValidateAgentRequest
{
/// <summary>
/// <see cref="gcdcv::AgentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdcv::AgentName AgentName
{
get => string.IsNullOrEmpty(Name) ? null : gcdcv::AgentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetAgentValidationResultRequest
{
/// <summary>
/// <see cref="gcdcv::AgentValidationResultName"/>-typed view over the <see cref="Name"/> resource name
/// property.
/// </summary>
public gcdcv::AgentValidationResultName AgentValidationResultName
{
get => string.IsNullOrEmpty(Name) ? null : gcdcv::AgentValidationResultName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class AgentValidationResult
{
/// <summary>
/// <see cref="gcdcv::AgentValidationResultName"/>-typed view over the <see cref="Name"/> resource name
/// property.
/// </summary>
public gcdcv::AgentValidationResultName AgentValidationResultName
{
get => string.IsNullOrEmpty(Name) ? null : gcdcv::AgentValidationResultName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using YAF.Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using JCG = J2N.Collections.Generic;
using ArrayUtil = YAF.Lucene.Net.Util.ArrayUtil;
namespace YAF.Lucene.Net.Codecs.Compressing
{
/*
* 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 AtomicReader = YAF.Lucene.Net.Index.AtomicReader;
using IBits = YAF.Lucene.Net.Util.IBits;
using BlockPackedWriter = YAF.Lucene.Net.Util.Packed.BlockPackedWriter;
using BufferedChecksumIndexInput = YAF.Lucene.Net.Store.BufferedChecksumIndexInput;
using BytesRef = YAF.Lucene.Net.Util.BytesRef;
using ChecksumIndexInput = YAF.Lucene.Net.Store.ChecksumIndexInput;
using DataInput = YAF.Lucene.Net.Store.DataInput;
using Directory = YAF.Lucene.Net.Store.Directory;
using FieldInfo = YAF.Lucene.Net.Index.FieldInfo;
using FieldInfos = YAF.Lucene.Net.Index.FieldInfos;
using Fields = YAF.Lucene.Net.Index.Fields;
using GrowableByteArrayDataOutput = YAF.Lucene.Net.Util.GrowableByteArrayDataOutput;
using IndexFileNames = YAF.Lucene.Net.Index.IndexFileNames;
using IndexInput = YAF.Lucene.Net.Store.IndexInput;
using IndexOutput = YAF.Lucene.Net.Store.IndexOutput;
using IOContext = YAF.Lucene.Net.Store.IOContext;
using IOUtils = YAF.Lucene.Net.Util.IOUtils;
using MergeState = YAF.Lucene.Net.Index.MergeState;
using PackedInt32s = YAF.Lucene.Net.Util.Packed.PackedInt32s;
using SegmentInfo = YAF.Lucene.Net.Index.SegmentInfo;
using SegmentReader = YAF.Lucene.Net.Index.SegmentReader;
using StringHelper = YAF.Lucene.Net.Util.StringHelper;
/// <summary>
/// <see cref="TermVectorsWriter"/> for <see cref="CompressingTermVectorsFormat"/>.
/// <para/>
/// @lucene.experimental
/// </summary>
public sealed class CompressingTermVectorsWriter : TermVectorsWriter
{
// hard limit on the maximum number of documents per chunk
internal const int MAX_DOCUMENTS_PER_CHUNK = 128;
internal const string VECTORS_EXTENSION = "tvd";
internal const string VECTORS_INDEX_EXTENSION = "tvx";
internal const string CODEC_SFX_IDX = "Index";
internal const string CODEC_SFX_DAT = "Data";
internal const int VERSION_START = 0;
internal const int VERSION_CHECKSUM = 1;
internal const int VERSION_CURRENT = VERSION_CHECKSUM;
internal const int BLOCK_SIZE = 64;
internal const int POSITIONS = 0x01;
internal const int OFFSETS = 0x02;
internal const int PAYLOADS = 0x04;
internal static readonly int FLAGS_BITS = PackedInt32s.BitsRequired(POSITIONS | OFFSETS | PAYLOADS);
private readonly Directory directory;
private readonly string segment;
private readonly string segmentSuffix;
private CompressingStoredFieldsIndexWriter indexWriter;
private IndexOutput vectorsStream;
private readonly CompressionMode compressionMode;
private readonly Compressor compressor;
private readonly int chunkSize;
/// <summary>
/// A pending doc. </summary>
private class DocData
{
private readonly CompressingTermVectorsWriter outerInstance;
internal readonly int numFields;
internal readonly LinkedList<FieldData> fields;
internal readonly int posStart, offStart, payStart;
internal DocData(CompressingTermVectorsWriter outerInstance, int numFields, int posStart, int offStart, int payStart)
{
this.outerInstance = outerInstance;
this.numFields = numFields;
this.fields = new LinkedList<FieldData>();
this.posStart = posStart;
this.offStart = offStart;
this.payStart = payStart;
}
internal virtual FieldData AddField(int fieldNum, int numTerms, bool positions, bool offsets, bool payloads)
{
FieldData field;
if (fields.Count == 0)
{
field = new FieldData(outerInstance, fieldNum, numTerms, positions, offsets, payloads, posStart, offStart, payStart);
}
else
{
FieldData last = fields.Last.Value;
int posStart = last.posStart + (last.hasPositions ? last.totalPositions : 0);
int offStart = last.offStart + (last.hasOffsets ? last.totalPositions : 0);
int payStart = last.payStart + (last.hasPayloads ? last.totalPositions : 0);
field = new FieldData(outerInstance, fieldNum, numTerms, positions, offsets, payloads, posStart, offStart, payStart);
}
fields.AddLast(field);
return field;
}
}
private DocData AddDocData(int numVectorFields)
{
FieldData last = null;
//for (IEnumerator<DocData> it = PendingDocs.Reverse(); it.MoveNext();)
foreach (DocData doc in pendingDocs.Reverse())
{
if (!(doc.fields.Count == 0))
{
last = doc.fields.Last.Value;
break;
}
}
DocData newDoc;
if (last == null)
{
newDoc = new DocData(this, numVectorFields, 0, 0, 0);
}
else
{
int posStart = last.posStart + (last.hasPositions ? last.totalPositions : 0);
int offStart = last.offStart + (last.hasOffsets ? last.totalPositions : 0);
int payStart = last.payStart + (last.hasPayloads ? last.totalPositions : 0);
newDoc = new DocData(this, numVectorFields, posStart, offStart, payStart);
}
pendingDocs.AddLast(newDoc);
return newDoc;
}
/// <summary>
/// A pending field. </summary>
private class FieldData
{
private readonly CompressingTermVectorsWriter outerInstance;
internal readonly bool hasPositions, hasOffsets, hasPayloads;
internal readonly int fieldNum, flags, numTerms;
internal readonly int[] freqs, prefixLengths, suffixLengths;
internal readonly int posStart, offStart, payStart;
internal int totalPositions;
internal int ord;
internal FieldData(CompressingTermVectorsWriter outerInstance, int fieldNum, int numTerms, bool positions, bool offsets, bool payloads, int posStart, int offStart, int payStart)
{
this.outerInstance = outerInstance;
this.fieldNum = fieldNum;
this.numTerms = numTerms;
this.hasPositions = positions;
this.hasOffsets = offsets;
this.hasPayloads = payloads;
this.flags = (positions ? POSITIONS : 0) | (offsets ? OFFSETS : 0) | (payloads ? PAYLOADS : 0);
this.freqs = new int[numTerms];
this.prefixLengths = new int[numTerms];
this.suffixLengths = new int[numTerms];
this.posStart = posStart;
this.offStart = offStart;
this.payStart = payStart;
totalPositions = 0;
ord = 0;
}
internal virtual void AddTerm(int freq, int prefixLength, int suffixLength)
{
freqs[ord] = freq;
prefixLengths[ord] = prefixLength;
suffixLengths[ord] = suffixLength;
++ord;
}
internal virtual void AddPosition(int position, int startOffset, int length, int payloadLength)
{
if (hasPositions)
{
if (posStart + totalPositions == outerInstance.positionsBuf.Length)
{
outerInstance.positionsBuf = ArrayUtil.Grow(outerInstance.positionsBuf);
}
outerInstance.positionsBuf[posStart + totalPositions] = position;
}
if (hasOffsets)
{
if (offStart + totalPositions == outerInstance.startOffsetsBuf.Length)
{
int newLength = ArrayUtil.Oversize(offStart + totalPositions, 4);
outerInstance.startOffsetsBuf = Arrays.CopyOf(outerInstance.startOffsetsBuf, newLength);
outerInstance.lengthsBuf = Arrays.CopyOf(outerInstance.lengthsBuf, newLength);
}
outerInstance.startOffsetsBuf[offStart + totalPositions] = startOffset;
outerInstance.lengthsBuf[offStart + totalPositions] = length;
}
if (hasPayloads)
{
if (payStart + totalPositions == outerInstance.payloadLengthsBuf.Length)
{
outerInstance.payloadLengthsBuf = ArrayUtil.Grow(outerInstance.payloadLengthsBuf);
}
outerInstance.payloadLengthsBuf[payStart + totalPositions] = payloadLength;
}
++totalPositions;
}
}
private int numDocs; // total number of docs seen
private readonly LinkedList<DocData> pendingDocs; // pending docs
private DocData curDoc; // current document
private FieldData curField; // current field
private readonly BytesRef lastTerm;
private int[] positionsBuf, startOffsetsBuf, lengthsBuf, payloadLengthsBuf;
private readonly GrowableByteArrayDataOutput termSuffixes; // buffered term suffixes
private readonly GrowableByteArrayDataOutput payloadBytes; // buffered term payloads
private readonly BlockPackedWriter writer;
/// <summary>
/// Sole constructor. </summary>
public CompressingTermVectorsWriter(Directory directory, SegmentInfo si, string segmentSuffix, IOContext context, string formatName, CompressionMode compressionMode, int chunkSize)
{
Debug.Assert(directory != null);
this.directory = directory;
this.segment = si.Name;
this.segmentSuffix = segmentSuffix;
this.compressionMode = compressionMode;
this.compressor = compressionMode.NewCompressor();
this.chunkSize = chunkSize;
numDocs = 0;
pendingDocs = new LinkedList<DocData>();
termSuffixes = new GrowableByteArrayDataOutput(ArrayUtil.Oversize(chunkSize, 1));
payloadBytes = new GrowableByteArrayDataOutput(ArrayUtil.Oversize(1, 1));
lastTerm = new BytesRef(ArrayUtil.Oversize(30, 1));
bool success = false;
IndexOutput indexStream = directory.CreateOutput(IndexFileNames.SegmentFileName(segment, segmentSuffix, VECTORS_INDEX_EXTENSION), context);
try
{
vectorsStream = directory.CreateOutput(IndexFileNames.SegmentFileName(segment, segmentSuffix, VECTORS_EXTENSION), context);
string codecNameIdx = formatName + CODEC_SFX_IDX;
string codecNameDat = formatName + CODEC_SFX_DAT;
CodecUtil.WriteHeader(indexStream, codecNameIdx, VERSION_CURRENT);
CodecUtil.WriteHeader(vectorsStream, codecNameDat, VERSION_CURRENT);
Debug.Assert(CodecUtil.HeaderLength(codecNameDat) == vectorsStream.GetFilePointer());
Debug.Assert(CodecUtil.HeaderLength(codecNameIdx) == indexStream.GetFilePointer());
indexWriter = new CompressingStoredFieldsIndexWriter(indexStream);
indexStream = null;
vectorsStream.WriteVInt32(PackedInt32s.VERSION_CURRENT);
vectorsStream.WriteVInt32(chunkSize);
writer = new BlockPackedWriter(vectorsStream, BLOCK_SIZE);
positionsBuf = new int[1024];
startOffsetsBuf = new int[1024];
lengthsBuf = new int[1024];
payloadLengthsBuf = new int[1024];
success = true;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(indexStream);
Abort();
}
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
try
{
IOUtils.Dispose(vectorsStream, indexWriter);
}
finally
{
vectorsStream = null;
indexWriter = null;
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override void Abort()
{
IOUtils.DisposeWhileHandlingException(this);
IOUtils.DeleteFilesIgnoringExceptions(directory, IndexFileNames.SegmentFileName(segment, segmentSuffix, VECTORS_EXTENSION), IndexFileNames.SegmentFileName(segment, segmentSuffix, VECTORS_INDEX_EXTENSION));
}
public override void StartDocument(int numVectorFields)
{
curDoc = AddDocData(numVectorFields);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override void FinishDocument()
{
// append the payload bytes of the doc after its terms
termSuffixes.WriteBytes(payloadBytes.Bytes, payloadBytes.Length);
payloadBytes.Length = 0;
++numDocs;
if (TriggerFlush())
{
Flush();
}
curDoc = null;
}
public override void StartField(FieldInfo info, int numTerms, bool positions, bool offsets, bool payloads)
{
curField = curDoc.AddField(info.Number, numTerms, positions, offsets, payloads);
lastTerm.Length = 0;
}
public override void FinishField()
{
curField = null;
}
public override void StartTerm(BytesRef term, int freq)
{
Debug.Assert(freq >= 1);
int prefix = StringHelper.BytesDifference(lastTerm, term);
curField.AddTerm(freq, prefix, term.Length - prefix);
termSuffixes.WriteBytes(term.Bytes, term.Offset + prefix, term.Length - prefix);
// copy last term
if (lastTerm.Bytes.Length < term.Length)
{
lastTerm.Bytes = new byte[ArrayUtil.Oversize(term.Length, 1)];
}
lastTerm.Offset = 0;
lastTerm.Length = term.Length;
Array.Copy(term.Bytes, term.Offset, lastTerm.Bytes, 0, term.Length);
}
public override void AddPosition(int position, int startOffset, int endOffset, BytesRef payload)
{
Debug.Assert(curField.flags != 0);
curField.AddPosition(position, startOffset, endOffset - startOffset, payload == null ? 0 : payload.Length);
if (curField.hasPayloads && payload != null)
{
payloadBytes.WriteBytes(payload.Bytes, payload.Offset, payload.Length);
}
}
private bool TriggerFlush()
{
return termSuffixes.Length >= chunkSize || pendingDocs.Count >= MAX_DOCUMENTS_PER_CHUNK;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void Flush()
{
int chunkDocs = pendingDocs.Count;
Debug.Assert(chunkDocs > 0, chunkDocs.ToString());
// write the index file
indexWriter.WriteIndex(chunkDocs, vectorsStream.GetFilePointer());
int docBase = numDocs - chunkDocs;
vectorsStream.WriteVInt32(docBase);
vectorsStream.WriteVInt32(chunkDocs);
// total number of fields of the chunk
int totalFields = FlushNumFields(chunkDocs);
if (totalFields > 0)
{
// unique field numbers (sorted)
int[] fieldNums = FlushFieldNums();
// offsets in the array of unique field numbers
FlushFields(totalFields, fieldNums);
// flags (does the field have positions, offsets, payloads?)
FlushFlags(totalFields, fieldNums);
// number of terms of each field
FlushNumTerms(totalFields);
// prefix and suffix lengths for each field
FlushTermLengths();
// term freqs - 1 (because termFreq is always >=1) for each term
FlushTermFreqs();
// positions for all terms, when enabled
FlushPositions();
// offsets for all terms, when enabled
FlushOffsets(fieldNums);
// payload lengths for all terms, when enabled
FlushPayloadLengths();
// compress terms and payloads and write them to the output
compressor.Compress(termSuffixes.Bytes, 0, termSuffixes.Length, vectorsStream);
}
// reset
pendingDocs.Clear();
curDoc = null;
curField = null;
termSuffixes.Length = 0;
}
private int FlushNumFields(int chunkDocs)
{
if (chunkDocs == 1)
{
int numFields = pendingDocs.First.Value.numFields;
vectorsStream.WriteVInt32(numFields);
return numFields;
}
else
{
writer.Reset(vectorsStream);
int totalFields = 0;
foreach (DocData dd in pendingDocs)
{
writer.Add(dd.numFields);
totalFields += dd.numFields;
}
writer.Finish();
return totalFields;
}
}
/// <summary>
/// Returns a sorted array containing unique field numbers. </summary>
private int[] FlushFieldNums()
{
JCG.SortedSet<int> fieldNums = new JCG.SortedSet<int>();
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
fieldNums.Add(fd.fieldNum);
}
}
int numDistinctFields = fieldNums.Count;
Debug.Assert(numDistinctFields > 0);
int bitsRequired = PackedInt32s.BitsRequired(fieldNums.Max);
int token = (Math.Min(numDistinctFields - 1, 0x07) << 5) | bitsRequired;
vectorsStream.WriteByte((byte)(sbyte)token);
if (numDistinctFields - 1 >= 0x07)
{
vectorsStream.WriteVInt32(numDistinctFields - 1 - 0x07);
}
PackedInt32s.Writer writer = PackedInt32s.GetWriterNoHeader(vectorsStream, PackedInt32s.Format.PACKED, fieldNums.Count, bitsRequired, 1);
foreach (int fieldNum in fieldNums)
{
writer.Add(fieldNum);
}
writer.Finish();
int[] fns = new int[fieldNums.Count];
int i = 0;
foreach (int key in fieldNums)
{
fns[i++] = key;
}
return fns;
}
private void FlushFields(int totalFields, int[] fieldNums)
{
PackedInt32s.Writer writer = PackedInt32s.GetWriterNoHeader(vectorsStream, PackedInt32s.Format.PACKED, totalFields, PackedInt32s.BitsRequired(fieldNums.Length - 1), 1);
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
int fieldNumIndex = Array.BinarySearch(fieldNums, fd.fieldNum);
Debug.Assert(fieldNumIndex >= 0);
writer.Add(fieldNumIndex);
}
}
writer.Finish();
}
private void FlushFlags(int totalFields, int[] fieldNums)
{
// check if fields always have the same flags
bool nonChangingFlags = true;
int[] fieldFlags = new int[fieldNums.Length];
Arrays.Fill(fieldFlags, -1);
bool breakOuterLoop;
foreach (DocData dd in pendingDocs)
{
breakOuterLoop = false;
foreach (FieldData fd in dd.fields)
{
int fieldNumOff = Array.BinarySearch(fieldNums, fd.fieldNum);
Debug.Assert(fieldNumOff >= 0);
if (fieldFlags[fieldNumOff] == -1)
{
fieldFlags[fieldNumOff] = fd.flags;
}
else if (fieldFlags[fieldNumOff] != fd.flags)
{
nonChangingFlags = false;
breakOuterLoop = true;
}
}
if (breakOuterLoop)
break;
}
if (nonChangingFlags)
{
// write one flag per field num
vectorsStream.WriteVInt32(0);
PackedInt32s.Writer writer = PackedInt32s.GetWriterNoHeader(vectorsStream, PackedInt32s.Format.PACKED, fieldFlags.Length, FLAGS_BITS, 1);
foreach (int flags in fieldFlags)
{
Debug.Assert(flags >= 0);
writer.Add(flags);
}
Debug.Assert(writer.Ord == fieldFlags.Length - 1);
writer.Finish();
}
else
{
// write one flag for every field instance
vectorsStream.WriteVInt32(1);
PackedInt32s.Writer writer = PackedInt32s.GetWriterNoHeader(vectorsStream, PackedInt32s.Format.PACKED, totalFields, FLAGS_BITS, 1);
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
writer.Add(fd.flags);
}
}
Debug.Assert(writer.Ord == totalFields - 1);
writer.Finish();
}
}
private void FlushNumTerms(int totalFields)
{
int maxNumTerms = 0;
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
maxNumTerms |= fd.numTerms;
}
}
int bitsRequired = PackedInt32s.BitsRequired(maxNumTerms);
vectorsStream.WriteVInt32(bitsRequired);
PackedInt32s.Writer writer = PackedInt32s.GetWriterNoHeader(vectorsStream, PackedInt32s.Format.PACKED, totalFields, bitsRequired, 1);
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
writer.Add(fd.numTerms);
}
}
Debug.Assert(writer.Ord == totalFields - 1);
writer.Finish();
}
private void FlushTermLengths()
{
writer.Reset(vectorsStream);
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
for (int i = 0; i < fd.numTerms; ++i)
{
writer.Add(fd.prefixLengths[i]);
}
}
}
writer.Finish();
writer.Reset(vectorsStream);
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
for (int i = 0; i < fd.numTerms; ++i)
{
writer.Add(fd.suffixLengths[i]);
}
}
}
writer.Finish();
}
private void FlushTermFreqs()
{
writer.Reset(vectorsStream);
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
for (int i = 0; i < fd.numTerms; ++i)
{
writer.Add(fd.freqs[i] - 1);
}
}
}
writer.Finish();
}
private void FlushPositions()
{
writer.Reset(vectorsStream);
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
if (fd.hasPositions)
{
int pos = 0;
for (int i = 0; i < fd.numTerms; ++i)
{
int previousPosition = 0;
for (int j = 0; j < fd.freqs[i]; ++j)
{
int position = positionsBuf[fd.posStart + pos++];
writer.Add(position - previousPosition);
previousPosition = position;
}
}
Debug.Assert(pos == fd.totalPositions);
}
}
}
writer.Finish();
}
private void FlushOffsets(int[] fieldNums)
{
bool hasOffsets = false;
long[] sumPos = new long[fieldNums.Length];
long[] sumOffsets = new long[fieldNums.Length];
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
hasOffsets |= fd.hasOffsets;
if (fd.hasOffsets && fd.hasPositions)
{
int fieldNumOff = Array.BinarySearch(fieldNums, fd.fieldNum);
int pos = 0;
for (int i = 0; i < fd.numTerms; ++i)
{
int previousPos = 0;
int previousOff = 0;
for (int j = 0; j < fd.freqs[i]; ++j)
{
int position = positionsBuf[fd.posStart + pos];
int startOffset = startOffsetsBuf[fd.offStart + pos];
sumPos[fieldNumOff] += position - previousPos;
sumOffsets[fieldNumOff] += startOffset - previousOff;
previousPos = position;
previousOff = startOffset;
++pos;
}
}
Debug.Assert(pos == fd.totalPositions);
}
}
}
if (!hasOffsets)
{
// nothing to do
return;
}
float[] charsPerTerm = new float[fieldNums.Length];
for (int i = 0; i < fieldNums.Length; ++i)
{
charsPerTerm[i] = (sumPos[i] <= 0 || sumOffsets[i] <= 0) ? 0 : (float)((double)sumOffsets[i] / sumPos[i]);
}
// start offsets
for (int i = 0; i < fieldNums.Length; ++i)
{
vectorsStream.WriteInt32(J2N.BitConversion.SingleToInt32Bits(charsPerTerm[i]));
}
writer.Reset(vectorsStream);
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
if ((fd.flags & OFFSETS) != 0)
{
int fieldNumOff = Array.BinarySearch(fieldNums, fd.fieldNum);
float cpt = charsPerTerm[fieldNumOff];
int pos = 0;
for (int i = 0; i < fd.numTerms; ++i)
{
int previousPos = 0;
int previousOff = 0;
for (int j = 0; j < fd.freqs[i]; ++j)
{
int position = fd.hasPositions ? positionsBuf[fd.posStart + pos] : 0;
int startOffset = startOffsetsBuf[fd.offStart + pos];
writer.Add(startOffset - previousOff - (int)(cpt * (position - previousPos)));
previousPos = position;
previousOff = startOffset;
++pos;
}
}
}
}
}
writer.Finish();
// lengths
writer.Reset(vectorsStream);
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
if ((fd.flags & OFFSETS) != 0)
{
int pos = 0;
for (int i = 0; i < fd.numTerms; ++i)
{
for (int j = 0; j < fd.freqs[i]; ++j)
{
writer.Add(lengthsBuf[fd.offStart + pos++] - fd.prefixLengths[i] - fd.suffixLengths[i]);
}
}
Debug.Assert(pos == fd.totalPositions);
}
}
}
writer.Finish();
}
private void FlushPayloadLengths()
{
writer.Reset(vectorsStream);
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
if (fd.hasPayloads)
{
for (int i = 0; i < fd.totalPositions; ++i)
{
writer.Add(payloadLengthsBuf[fd.payStart + i]);
}
}
}
}
writer.Finish();
}
public override void Finish(FieldInfos fis, int numDocs)
{
if (!(pendingDocs.Count == 0))
{
Flush();
}
if (numDocs != this.numDocs)
{
throw new Exception("Wrote " + this.numDocs + " docs, finish called with numDocs=" + numDocs);
}
indexWriter.Finish(numDocs, vectorsStream.GetFilePointer());
CodecUtil.WriteFooter(vectorsStream);
}
public override IComparer<BytesRef> Comparer
{
get
{
return BytesRef.UTF8SortedAsUnicodeComparer;
}
}
public override void AddProx(int numProx, DataInput positions, DataInput offsets)
{
Debug.Assert((curField.hasPositions) == (positions != null));
Debug.Assert((curField.hasOffsets) == (offsets != null));
if (curField.hasPositions)
{
int posStart = curField.posStart + curField.totalPositions;
if (posStart + numProx > positionsBuf.Length)
{
positionsBuf = ArrayUtil.Grow(positionsBuf, posStart + numProx);
}
int position = 0;
if (curField.hasPayloads)
{
int payStart = curField.payStart + curField.totalPositions;
if (payStart + numProx > payloadLengthsBuf.Length)
{
payloadLengthsBuf = ArrayUtil.Grow(payloadLengthsBuf, payStart + numProx);
}
for (int i = 0; i < numProx; ++i)
{
int code = positions.ReadVInt32();
if ((code & 1) != 0)
{
// this position has a payload
int payloadLength = positions.ReadVInt32();
payloadLengthsBuf[payStart + i] = payloadLength;
payloadBytes.CopyBytes(positions, payloadLength);
}
else
{
payloadLengthsBuf[payStart + i] = 0;
}
position += (int)((uint)code >> 1);
positionsBuf[posStart + i] = position;
}
}
else
{
for (int i = 0; i < numProx; ++i)
{
position += ((int)((uint)positions.ReadVInt32() >> 1));
positionsBuf[posStart + i] = position;
}
}
}
if (curField.hasOffsets)
{
int offStart = curField.offStart + curField.totalPositions;
if (offStart + numProx > startOffsetsBuf.Length)
{
int newLength = ArrayUtil.Oversize(offStart + numProx, 4);
startOffsetsBuf = Arrays.CopyOf(startOffsetsBuf, newLength);
lengthsBuf = Arrays.CopyOf(lengthsBuf, newLength);
}
int lastOffset = 0, startOffset, endOffset;
for (int i = 0; i < numProx; ++i)
{
startOffset = lastOffset + offsets.ReadVInt32();
endOffset = startOffset + offsets.ReadVInt32();
lastOffset = endOffset;
startOffsetsBuf[offStart + i] = startOffset;
lengthsBuf[offStart + i] = endOffset - startOffset;
}
}
curField.totalPositions += numProx;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override int Merge(MergeState mergeState)
{
int docCount = 0;
int idx = 0;
foreach (AtomicReader reader in mergeState.Readers)
{
SegmentReader matchingSegmentReader = mergeState.MatchingSegmentReaders[idx++];
CompressingTermVectorsReader matchingVectorsReader = null;
if (matchingSegmentReader != null)
{
TermVectorsReader vectorsReader = matchingSegmentReader.TermVectorsReader;
// we can only bulk-copy if the matching reader is also a CompressingTermVectorsReader
if (vectorsReader != null && vectorsReader is CompressingTermVectorsReader)
{
matchingVectorsReader = (CompressingTermVectorsReader)vectorsReader;
}
}
int maxDoc = reader.MaxDoc;
IBits liveDocs = reader.LiveDocs;
if (matchingVectorsReader == null || matchingVectorsReader.Version != VERSION_CURRENT || matchingVectorsReader.CompressionMode != compressionMode || matchingVectorsReader.ChunkSize != chunkSize || matchingVectorsReader.PackedInt32sVersion != PackedInt32s.VERSION_CURRENT)
{
// naive merge...
for (int i = NextLiveDoc(0, liveDocs, maxDoc); i < maxDoc; i = NextLiveDoc(i + 1, liveDocs, maxDoc))
{
Fields vectors = reader.GetTermVectors(i);
AddAllDocVectors(vectors, mergeState);
++docCount;
mergeState.CheckAbort.Work(300);
}
}
else
{
CompressingStoredFieldsIndexReader index = matchingVectorsReader.Index;
IndexInput vectorsStreamOrig = matchingVectorsReader.VectorsStream;
vectorsStreamOrig.Seek(0);
ChecksumIndexInput vectorsStream = new BufferedChecksumIndexInput((IndexInput)vectorsStreamOrig.Clone());
for (int i = NextLiveDoc(0, liveDocs, maxDoc); i < maxDoc; )
{
// We make sure to move the checksum input in any case, otherwise the final
// integrity check might need to read the whole file a second time
long startPointer = index.GetStartPointer(i);
if (startPointer > vectorsStream.GetFilePointer())
{
vectorsStream.Seek(startPointer);
}
if ((pendingDocs.Count == 0) && (i == 0 || index.GetStartPointer(i - 1) < startPointer)) // start of a chunk
{
int docBase = vectorsStream.ReadVInt32();
int chunkDocs = vectorsStream.ReadVInt32();
Debug.Assert(docBase + chunkDocs <= matchingSegmentReader.MaxDoc);
if (docBase + chunkDocs < matchingSegmentReader.MaxDoc && NextDeletedDoc(docBase, liveDocs, docBase + chunkDocs) == docBase + chunkDocs)
{
long chunkEnd = index.GetStartPointer(docBase + chunkDocs);
long chunkLength = chunkEnd - vectorsStream.GetFilePointer();
indexWriter.WriteIndex(chunkDocs, this.vectorsStream.GetFilePointer());
this.vectorsStream.WriteVInt32(docCount);
this.vectorsStream.WriteVInt32(chunkDocs);
this.vectorsStream.CopyBytes(vectorsStream, chunkLength);
docCount += chunkDocs;
this.numDocs += chunkDocs;
mergeState.CheckAbort.Work(300 * chunkDocs);
i = NextLiveDoc(docBase + chunkDocs, liveDocs, maxDoc);
}
else
{
for (; i < docBase + chunkDocs; i = NextLiveDoc(i + 1, liveDocs, maxDoc))
{
Fields vectors = reader.GetTermVectors(i);
AddAllDocVectors(vectors, mergeState);
++docCount;
mergeState.CheckAbort.Work(300);
}
}
}
else
{
Fields vectors = reader.GetTermVectors(i);
AddAllDocVectors(vectors, mergeState);
++docCount;
mergeState.CheckAbort.Work(300);
i = NextLiveDoc(i + 1, liveDocs, maxDoc);
}
}
vectorsStream.Seek(vectorsStream.Length - CodecUtil.FooterLength());
CodecUtil.CheckFooter(vectorsStream);
}
}
Finish(mergeState.FieldInfos, docCount);
return docCount;
}
private static int NextLiveDoc(int doc, IBits liveDocs, int maxDoc)
{
if (liveDocs == null)
{
return doc;
}
while (doc < maxDoc && !liveDocs.Get(doc))
{
++doc;
}
return doc;
}
private static int NextDeletedDoc(int doc, IBits liveDocs, int maxDoc)
{
if (liveDocs == null)
{
return maxDoc;
}
while (doc < maxDoc && liveDocs.Get(doc))
{
++doc;
}
return doc;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Management.Automation.Language;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell
{
/// <summary>
/// Executor wraps a Pipeline instance, and provides helper methods for executing commands in that pipeline. It is used to
/// provide bookkeeping and structure to the use of pipeline in such a way that they can be interrupted and cancelled by a
/// break event handler, and track nesting of pipelines (which happens with interrupted input loops (aka subshells) and use
/// of tab-completion in prompts. The bookkeeping is necessary because the break handler is static and global, and there is
/// no means for tying a break handler to an instance of an object.
///
/// The class' instance methods manage a single pipeline. The class' static methods track the outstanding instances to
/// ensure that only one instance is 'active' (and therefore cancellable) at a time.
/// </summary>
internal class Executor
{
[Flags]
internal enum ExecutionOptions
{
None = 0x0,
AddOutputter = 0x01,
AddToHistory = 0x02,
ReadInputObjects = 0x04
}
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="parent">
/// A reference to the parent ConsoleHost that created this instance.
/// </param>
/// <param name="useNestedPipelines">
/// true if the executor is supposed to use nested pipelines; false if not.
/// </param>
/// <param name="isPromptFunctionExecutor">
/// True if the instance will be used to execute the prompt function, which will delay stopping the pipeline by some
/// milliseconds. This we prevent us from stopping the pipeline so quickly that when the user leans on the ctrl-c key
/// that the prompt "stops working" (because it is being stopped faster than it can run to completion).
/// </param>
internal Executor(ConsoleHost parent, bool useNestedPipelines, bool isPromptFunctionExecutor)
{
Dbg.Assert(parent != null, "parent should not be null");
_parent = parent;
this.useNestedPipelines = useNestedPipelines;
_isPromptFunctionExecutor = isPromptFunctionExecutor;
Reset();
}
#region async
// called on the pipeline thread
private void OutputObjectStreamHandler(object sender, EventArgs e)
{
// e is just an empty instance of EventArgs, so we ignore it. sender is the PipelineReader that raised it's
// DataReady event that calls this handler, which is the PipelineReader for the Output object stream.
PipelineReader<PSObject> reader = (PipelineReader<PSObject>)sender;
// we use NonBlockingRead instead of Read, as Read would block if the reader has no objects. While it would be
// inconsistent for this method to be called when there are no objects, since it will be called synchronously on
// the pipeline thread, blocking in this call until an object is streamed would deadlock the pipeline. So we
// prefer to take no chance of blocking.
Collection<PSObject> objects = reader.NonBlockingRead();
foreach (PSObject obj in objects)
{
_parent.OutputSerializer.Serialize(obj);
}
}
// called on the pipeline thread
private void ErrorObjectStreamHandler(object sender, EventArgs e)
{
// e is just an empty instance of EventArgs, so we ignore it. sender is the PipelineReader that raised it's
// DataReady event that calls this handler, which is the PipelineReader for the Error object stream.
PipelineReader<object> reader = (PipelineReader<object>)sender;
// we use NonBlockingRead instead of Read, as Read would block if the reader has no objects. While it would be
// inconsistent for this method to be called when there are no objects, since it will be called synchronously on
// the pipeline thread, blocking in this call until an object is streamed would deadlock the pipeline. So we
// prefer to take no chance of blocking.
Collection<object> objects = reader.NonBlockingRead();
foreach (object obj in objects)
{
_parent.ErrorSerializer.Serialize(obj);
}
}
/// <summary>
/// This method handles the failure in executing pipeline asynchronously.
/// </summary>
/// <param name="ex"></param>
private void AsyncPipelineFailureHandler(Exception ex)
{
ErrorRecord er = null;
IContainsErrorRecord cer = ex as IContainsErrorRecord;
if (cer != null)
{
er = cer.ErrorRecord;
// Exception inside the error record is ParentContainsErrorRecordException which
// doesn't have stack trace. Replace it with top level exception.
er = new ErrorRecord(er, ex);
}
if (er == null)
{
er = new ErrorRecord(ex, "ConsoleHostAsyncPipelineFailure", ErrorCategory.NotSpecified, null);
}
_parent.ErrorSerializer.Serialize(er);
}
private class PipelineFinishedWaitHandle
{
internal PipelineFinishedWaitHandle(Pipeline p)
{
p.StateChanged += new EventHandler<PipelineStateEventArgs>(PipelineStateChangedHandler);
}
internal void Wait()
{
_eventHandle.WaitOne();
}
private void PipelineStateChangedHandler(object sender, PipelineStateEventArgs e)
{
if (
e.PipelineStateInfo.State == PipelineState.Completed
|| e.PipelineStateInfo.State == PipelineState.Failed
|| e.PipelineStateInfo.State == PipelineState.Stopped)
{
_eventHandle.Set();
}
}
private System.Threading.ManualResetEvent _eventHandle = new System.Threading.ManualResetEvent(false);
}
internal void ExecuteCommandAsync(string command, out Exception exceptionThrown, ExecutionOptions options)
{
Dbg.Assert(!useNestedPipelines, "can't async invoke a nested pipeline");
Dbg.Assert(!string.IsNullOrEmpty(command), "command should have a value");
bool addToHistory = (options & ExecutionOptions.AddToHistory) > 0;
Pipeline tempPipeline = _parent.RunspaceRef.CreatePipeline(command, addToHistory, false);
ExecuteCommandAsyncHelper(tempPipeline, out exceptionThrown, options);
}
/// <summary>
/// Executes a pipeline in the console when we are running asnyc.
/// </summary>
/// <param name="tempPipeline">
/// The pipeline to execute.
/// </param>
/// <param name="exceptionThrown">
/// Any exception thrown trying to run the pipeline.
/// </param>
/// <param name="options">
/// The options to use to execute the pipeline.
/// </param>
internal void ExecuteCommandAsyncHelper(Pipeline tempPipeline, out Exception exceptionThrown, ExecutionOptions options)
{
Dbg.Assert(!_isPromptFunctionExecutor, "should not async invoke the prompt");
exceptionThrown = null;
Executor oldCurrent = CurrentExecutor;
CurrentExecutor = this;
lock (_instanceStateLock)
{
Dbg.Assert(_pipeline == null, "no other pipeline should exist");
_pipeline = tempPipeline;
}
try
{
if ((options & ExecutionOptions.AddOutputter) > 0 && _parent.OutputFormat == Serialization.DataFormat.Text)
{
// Tell the script command to merge it's output and error streams
if (tempPipeline.Commands.Count == 1)
{
tempPipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
}
// then add out-default to the pipeline to render everything...
Command outDefault = new Command("Out-Default", /* isScript */false, /* useLocalScope */ true);
tempPipeline.Commands.Add(outDefault);
}
tempPipeline.Output.DataReady += new EventHandler(OutputObjectStreamHandler);
tempPipeline.Error.DataReady += new EventHandler(ErrorObjectStreamHandler);
PipelineFinishedWaitHandle pipelineWaiter = new PipelineFinishedWaitHandle(tempPipeline);
// close the input pipeline so the command will do something
// if we are not reading input
if ((options & Executor.ExecutionOptions.ReadInputObjects) == 0)
{
tempPipeline.Input.Close();
}
tempPipeline.InvokeAsync();
if ((options & ExecutionOptions.ReadInputObjects) > 0 && Console.IsInputRedirected)
{
// read input objects from stdin
WrappedDeserializer des = new WrappedDeserializer(_parent.InputFormat, "Input", _parent.ConsoleIn.Value);
while (!des.AtEnd)
{
object o = des.Deserialize();
if (o == null)
{
break;
}
try
{
tempPipeline.Input.Write(o);
}
catch (PipelineClosedException)
{
// This exception can occurs when input is closed. This can happen
// for various reasons. For ex:Command in the pipeline is invalid and
// command discovery throws exception which closes the pipeline and
// hence the Input pipe.
break;
}
};
des.End();
}
tempPipeline.Input.Close();
pipelineWaiter.Wait();
// report error if pipeline failed
if (tempPipeline.PipelineStateInfo.State == PipelineState.Failed && tempPipeline.PipelineStateInfo.Reason != null)
{
if (_parent.OutputFormat == Serialization.DataFormat.Text)
{
// Report the exception using normal error reporting
exceptionThrown = tempPipeline.PipelineStateInfo.Reason;
}
else
{
// serialize the error record
AsyncPipelineFailureHandler(tempPipeline.PipelineStateInfo.Reason);
}
}
}
catch (Exception e)
{
exceptionThrown = e;
}
finally
{
// Once we have the results, or an exception is thrown, we throw away the pipeline.
_parent.ui.ResetProgress();
CurrentExecutor = oldCurrent;
Reset();
}
}
#endregion async
internal Pipeline CreatePipeline()
{
if (useNestedPipelines)
{
return _parent.RunspaceRef.CreateNestedPipeline();
}
else
{
return _parent.RunspaceRef.CreatePipeline();
}
}
internal Pipeline CreatePipeline(string command, bool addToHistory)
{
Dbg.Assert(!string.IsNullOrEmpty(command), "command should have a value");
return _parent.RunspaceRef.CreatePipeline(command, addToHistory, useNestedPipelines);
}
/// <summary>
/// All calls to the Runspace to execute a command line must be done with this function, which properly synchronizes
/// access to the running pipeline between the main thread and the break handler thread. This synchronization is
/// necessary so that executions can be aborted with Ctrl-C (including evaluation of the prompt and collection of
/// command-completion candidates.
///
/// On any given Executor instance, ExecuteCommand should be called at most once at a time by any one thread. It is NOT
/// reentrant.
/// </summary>
/// <param name="command">
/// The command line to be executed. Must be non-null.
/// </param>
/// <param name="exceptionThrown">
/// Receives the Exception thrown by the execution of the command, if any. If no exception is thrown, then set to null.
/// Can be tested to see if the execution was successful or not.
/// </param>
/// <param name="options">
/// options to govern the execution
/// </param>
/// <returns>
/// the object stream resulting from the execution. May be null.
/// </returns>
internal Collection<PSObject> ExecuteCommand(string command, out Exception exceptionThrown, ExecutionOptions options)
{
Dbg.Assert(!string.IsNullOrEmpty(command), "command should have a value");
// Experimental:
// Check for implicit remoting commands that can be batched, and execute as batched if able.
if (ExperimentalFeature.IsEnabled("PSImplicitRemotingBatching"))
{
var addOutputter = ((options & ExecutionOptions.AddOutputter) > 0);
if (addOutputter &&
!_parent.RunspaceRef.IsRunspaceOverridden &&
_parent.RunspaceRef.Runspace.ExecutionContext.Modules != null &&
_parent.RunspaceRef.Runspace.ExecutionContext.Modules.IsImplicitRemotingModuleLoaded &&
Utils.TryRunAsImplicitBatch(command, _parent.RunspaceRef.Runspace))
{
exceptionThrown = null;
return null;
}
}
Pipeline tempPipeline = CreatePipeline(command, (options & ExecutionOptions.AddToHistory) > 0);
return ExecuteCommandHelper(tempPipeline, out exceptionThrown, options);
}
private Command GetOutDefaultCommand(bool endOfStatement)
{
return new Command(command: "Out-Default",
isScript: false,
useLocalScope: true,
mergeUnclaimedPreviousErrorResults: true)
{
IsEndOfStatement = endOfStatement
};
}
internal Collection<PSObject> ExecuteCommandHelper(Pipeline tempPipeline, out Exception exceptionThrown, ExecutionOptions options)
{
Dbg.Assert(tempPipeline != null, "command should have a value");
exceptionThrown = null;
Collection<PSObject> results = null;
if ((options & ExecutionOptions.AddOutputter) > 0)
{
if (tempPipeline.Commands.Count < 2)
{
if (tempPipeline.Commands.Count == 1)
{
// Tell the script command to merge it's output and error streams.
tempPipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
}
// Add Out-Default to the pipeline to render.
tempPipeline.Commands.Add(GetOutDefaultCommand(endOfStatement: false));
}
else
{
// For multiple commands/scripts we need to insert Out-Default at the end of each statement.
CommandCollection executeCommands = new CommandCollection();
foreach (var cmd in tempPipeline.Commands)
{
executeCommands.Add(cmd);
if (cmd.IsEndOfStatement)
{
// End of statement needs to pipe to Out-Default.
cmd.IsEndOfStatement = false;
executeCommands.Add(GetOutDefaultCommand(endOfStatement: true));
}
}
var lastCmd = executeCommands.Last();
if (!((lastCmd.CommandText != null) &&
(lastCmd.CommandText.Equals("Out-Default", StringComparison.OrdinalIgnoreCase)))
)
{
// Ensure pipeline output goes to Out-Default.
executeCommands.Add(GetOutDefaultCommand(endOfStatement: false));
}
tempPipeline.Commands.Clear();
foreach (var cmd in executeCommands)
{
tempPipeline.Commands.Add(cmd);
}
}
}
Executor oldCurrent = CurrentExecutor;
CurrentExecutor = this;
lock (_instanceStateLock)
{
Dbg.Assert(_pipeline == null, "no other pipeline should exist");
_pipeline = tempPipeline;
}
try
{
// blocks until all results are retrieved.
results = tempPipeline.Invoke();
}
catch (Exception e)
{
exceptionThrown = e;
}
finally
{
// Once we have the results, or an exception is thrown, we throw away the pipeline.
_parent.ui.ResetProgress();
CurrentExecutor = oldCurrent;
Reset();
}
return results;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Needed by ProfileTests as mentioned in bug 140572")]
internal Collection<PSObject> ExecuteCommand(string command)
{
Collection<PSObject> result = null;
Exception e = null;
do
{
result = ExecuteCommand(command, out e, ExecutionOptions.None);
if (e != null)
{
break;
}
if (result == null)
{
break;
}
} while (false);
return result;
}
/// <summary>
/// Executes a command (by calling this.ExecuteCommand), and coerces the first result object to a string. Any Exception
/// thrown in the course of execution is returned thru the exceptionThrown parameter.
/// </summary>
/// <param name="command">
/// The command to execute. May be any valid monad command.
/// </param>
/// <param name="exceptionThrown">
/// Receives the Exception thrown by the execution of the command, if any. If no exception is thrown, then set to null.
/// Can be tested to see if the execution was successful or not.
/// </param>
/// <returns>
/// The string representation of the first result object returned, or null if an exception was thrown or no objects were
/// returned by the command.
/// </returns>
internal string ExecuteCommandAndGetResultAsString(string command, out Exception exceptionThrown)
{
exceptionThrown = null;
string result = null;
do
{
Collection<PSObject> streamResults = ExecuteCommand(command, out exceptionThrown, ExecutionOptions.None);
if (exceptionThrown != null)
{
break;
}
if (streamResults == null || streamResults.Count == 0)
{
break;
}
// we got back one or more objects. Pick off the first result.
if (streamResults[0] == null)
return string.Empty;
// And convert the base object into a string. We can't use the proxied
// ToString() on the PSObject because there is no default runspace
// available.
PSObject msho = streamResults[0] as PSObject;
if (msho != null)
result = msho.BaseObject.ToString();
else
result = streamResults[0].ToString();
}
while (false);
return result;
}
/// <summary>
/// Executes a command (by calling this.ExecuteCommand), and coerces the first result object to a bool. Any Exception
/// thrown in the course of execution is caught and ignored.
/// </summary>
/// <param name="command">
/// The command to execute. May be any valid monad command.
/// </param>
/// <returns>
/// The Nullable`bool representation of the first result object returned, or null if an exception was thrown or no
/// objects were returned by the command.
/// </returns>
internal bool? ExecuteCommandAndGetResultAsBool(string command)
{
Exception unused = null;
bool? result = ExecuteCommandAndGetResultAsBool(command, out unused);
return result;
}
/// <summary>
/// Executes a command (by calling this.ExecuteCommand), and coerces the first result object to a bool. Any Exception
/// thrown in the course of execution is returned thru the exceptionThrown parameter.
/// </summary>
/// <param name="command">
/// The command to execute. May be any valid monad command.
/// </param>
/// <param name="exceptionThrown">
/// Receives the Exception thrown by the execution of the command, if any. If no exception is thrown, then set to null.
/// Can be tested to see if the execution was successful or not.
/// </param>
/// <returns>
/// The Nullable`bool representation of the first result object returned, or null if an exception was thrown or no
/// objects were returned by the command.
/// </returns>
internal bool? ExecuteCommandAndGetResultAsBool(string command, out Exception exceptionThrown)
{
exceptionThrown = null;
Dbg.Assert(!string.IsNullOrEmpty(command), "command should have a value");
bool? result = null;
do
{
Collection<PSObject> streamResults = ExecuteCommand(command, out exceptionThrown, ExecutionOptions.None);
if (exceptionThrown != null)
{
break;
}
if (streamResults == null || streamResults.Count == 0)
{
break;
}
// we got back one or more objects.
result = (streamResults.Count > 1) || (LanguagePrimitives.IsTrue(streamResults[0]));
}
while (false);
return result;
}
/// <summary>
/// Cancels execution of the current instance. If the current instance is not running, then does nothing. Called in
/// response to a break handler, by the static Executor.Cancel method.
/// </summary>
private void Cancel()
{
// if there's a pipeline running, stop it.
lock (_instanceStateLock)
{
if (_pipeline != null && !_cancelled)
{
_cancelled = true;
if (_isPromptFunctionExecutor)
{
System.Threading.Thread.Sleep(100);
}
_pipeline.Stop();
}
}
}
internal void BlockCommandOutput()
{
RemotePipeline remotePipeline = _pipeline as RemotePipeline;
if (remotePipeline != null)
{
// Waits until queued data is handled.
remotePipeline.DrainIncomingData();
// Blocks any new data.
remotePipeline.SuspendIncomingData();
}
}
internal void ResumeCommandOutput()
{
RemotePipeline remotePipeline = _pipeline as RemotePipeline;
if (remotePipeline != null)
{
// Resumes data flow.
remotePipeline.ResumeIncomingData();
}
}
/// <summary>
/// Resets the instance to its post-ctor state. Does not cancel execution.
/// </summary>
private void Reset()
{
lock (_instanceStateLock)
{
_pipeline = null;
_cancelled = false;
}
}
/// <summary>
/// Makes the given instance the "current" instance, that is, the instance that will receive a Cancel call if the break
/// handler is triggered and calls the static Cancel method.
/// </summary>
/// <value>
/// The instance to make current. Null is allowed.
/// </value>
/// <remarks>
/// Here are some state-transition cases to illustrate the use of CurrentExecutor
///
/// null is current
/// p1.ExecuteCommand
/// set p1 as current
/// promptforparams
/// tab complete
/// p2.ExecuteCommand
/// set p2 as current
/// p2.Execute completes
/// restore old current to p1
/// p1.Execute completes
/// restore null as current
///
/// Here's another case:
/// null is current
/// p1.ExecuteCommand
/// set p1 as current
/// ShouldProcess - suspend
/// EnterNestedPrompt
/// set null as current so that break does not exit the subshell
/// evaluate prompt
/// p2.ExecuteCommand
/// set p2 as current
/// Execute completes
/// restore null as current
/// nested loop exit
/// restore p1 as current
///
/// Summary:
/// ExecuteCommand always saves/sets/restores CurrentExecutor
/// Host.EnterNestedPrompt always saves/clears/restores CurrentExecutor
/// </remarks>
internal static Executor CurrentExecutor
{
get
{
Executor result = null;
lock (s_staticStateLock)
{
result = s_currentExecutor;
}
return result;
}
set
{
lock (s_staticStateLock)
{
// null is acceptable.
s_currentExecutor = value;
}
}
}
/// <summary>
/// Cancels the execution of the current instance (the instance last passed to PushCurrentExecutor), if any. If no
/// instance is Current, then does nothing.
/// </summary>
internal static void CancelCurrentExecutor()
{
Executor temp = null;
lock (s_staticStateLock)
{
temp = s_currentExecutor;
}
if (temp != null)
{
temp.Cancel();
}
}
// These statics are threadsafe, as there can be only one instance of ConsoleHost in a process at a time, and access
// to currentExecutor is guarded by staticStateLock, and static initializers are run by the CLR at program init time.
private static Executor s_currentExecutor;
private static object s_staticStateLock = new object();
private ConsoleHost _parent;
private Pipeline _pipeline;
private bool _cancelled;
internal bool useNestedPipelines;
private object _instanceStateLock = new object();
private bool _isPromptFunctionExecutor;
}
} // namespace
| |
// 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.Contracts;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace System.ServiceModel.Channels
{
/// <summary>
/// This class is based on BufferedStream from the Desktop version of .Net. Only the write functionality
/// is needed by WCF so the read capability has been removed. This allowed some extra logic to be removed
/// from the write code path. Also some validation code has been removed as this class is no longer
/// general purpose and is only used in pre-known scenarios and only called by WCF code. Some validation
/// checks have been converted to only run on a debug build to allow catching code bugs in other WCF code,
/// but not causing release build overhead.
///
/// One of the design goals here is to prevent the buffer from getting in the way and slowing
/// down underlying stream accesses when it is not needed.
/// See a large comment in Write for the details of the write buffer heuristic.
///
/// This class will never cache more bytes than the max specified buffer size.
/// However, it may use a temporary buffer of up to twice the size in order to combine several IO operations on
/// the underlying stream into a single operation. This is because we assume that memory copies are significantly
/// faster than IO operations on the underlying stream (if this was not true, using buffering is never appropriate).
/// The max size of this "shadow" buffer is limited as to not allocate it on the LOH.
/// Shadowing is always transient. Even when using this technique, this class still guarantees that the number of
/// bytes cached (not yet written to the target stream or not yet consumed by the user) is never larger than the
/// actual specified buffer size.
/// </summary>
internal sealed class BufferedWriteStream : Stream
{
public const int DefaultBufferSize = 8192;
private Stream _stream; // Underlying stream. Close sets _stream to null.
private BufferManager _bufferManager;
private byte[] _buffer; // Write buffer.
private readonly int _bufferSize; // Length of internal buffer (not counting the shadow buffer).
private int _writePos; // Write pointer within buffer.
private readonly SemaphoreSlim _sem = new SemaphoreSlim(1, 1);
public BufferedWriteStream(Stream stream) : this(stream, null, DefaultBufferSize) { }
public BufferedWriteStream(Stream stream, BufferManager bufferManager) : this(stream, bufferManager, DefaultBufferSize) { }
public BufferedWriteStream(Stream stream, BufferManager bufferManager, int bufferSize)
{
Contract.Assert(stream != Null, "stream != Stream.Null");
Contract.Assert(stream != null, "stream != null");
Contract.Assert(bufferSize > 0, "bufferSize > 0");
Contract.Assert(stream.CanWrite);
_stream = stream;
_bufferManager = bufferManager;
_bufferSize = bufferSize;
EnsureBufferAllocated();
}
private void EnsureNotClosed()
{
if (_stream == null)
throw new ObjectDisposedException(nameof(BufferedWriteStream));
}
private void EnsureCanWrite()
{
Contract.Assert(_stream != null);
Contract.Assert(_stream.CanWrite);
}
/// <summary><code>MaxShadowBufferSize</code> is chosen such that shadow buffers are not allocated on the Large Object Heap.
/// Currently, an object is allocated on the LOH if it is larger than 85000 bytes.
/// We will go with exactly 80 KBytes, although this is somewhat arbitrary.</summary>
private const int MaxShadowBufferSize = 81920; // Make sure not to get to the Large Object Heap.
private void EnsureShadowBufferAllocated()
{
Contract.Assert(_buffer != null);
Contract.Assert(_bufferSize > 0);
// Already have shadow buffer?
if (_buffer.Length != _bufferSize || _bufferSize >= MaxShadowBufferSize)
{
return;
}
byte[] shadowBuffer = new byte[Math.Min(_bufferSize + _bufferSize, MaxShadowBufferSize)];
Array.Copy(_buffer, 0, shadowBuffer, 0, _writePos);
_buffer = shadowBuffer;
}
private void EnsureBufferAllocated()
{
if (_buffer == null)
{
if (_bufferManager != null)
{
_buffer = _bufferManager.TakeBuffer(_bufferSize);
}
else
{
_buffer = new byte[_bufferSize];
}
}
}
public override bool CanRead
{
get { return false; }
}
public override bool CanWrite
{
get { return _stream != null && _stream.CanWrite; }
}
public override bool CanSeek
{
get { return false; }
}
public override long Length
{
get { throw new NotSupportedException(nameof(Length)); }
}
public override long Position
{
get { throw new NotSupportedException(nameof(Position)); }
set { throw new NotSupportedException(nameof(Position)); }
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
try
{
_stream?.Dispose();
}
finally
{
_stream = null;
var tempBuffer = _buffer;
_buffer = null;
_bufferManager?.ReturnBuffer(tempBuffer);
_bufferManager = null;
}
}
// Call base.Dispose(bool) to cleanup async IO resources
base.Dispose(disposing);
}
public override void Flush()
{
EnsureNotClosed();
// Has WRITE data in the buffer:
if (_writePos > 0)
{
FlushWrite();
Contract.Assert(_writePos == 0);
return;
}
// We had no data in the buffer, but we still need to tell the underlying stream to flush.
_stream.Flush();
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
EnsureNotClosed();
return FlushAsyncInternal(cancellationToken);
}
private async Task FlushAsyncInternal(CancellationToken cancellationToken)
{
await _sem.WaitAsync().ConfigureAwait(false);
try
{
if (_writePos > 0)
{
await FlushWriteAsync(cancellationToken).ConfigureAwait(false);
Contract.Assert(_writePos == 0);
return;
}
// We had no data in the buffer, but we still need to tell the underlying stream to flush.
await _stream.FlushAsync(cancellationToken).ConfigureAwait(false);
// There was nothing in the buffer:
Contract.Assert(_writePos == 0);
}
finally
{
_sem.Release();
}
}
private void FlushWrite()
{
Contract.Assert(_buffer != null && _bufferSize >= _writePos,
"BufferedWriteStream: Write buffer must be allocated and write position must be in the bounds of the buffer in FlushWrite!");
_stream.Write(_buffer, 0, _writePos);
_writePos = 0;
_stream.Flush();
}
private async Task FlushWriteAsync(CancellationToken cancellationToken)
{
Contract.Assert(_buffer != null && _bufferSize >= _writePos,
"BufferedWriteStream: Write buffer must be allocated and write position must be in the bounds of the buffer in FlushWrite!");
await _stream.WriteAsync(_buffer, 0, _writePos, cancellationToken).ConfigureAwait(false);
_writePos = 0;
await _stream.FlushAsync(cancellationToken).ConfigureAwait(false);
}
public override int Read(byte[] array, int offset, int count)
{
throw new NotSupportedException(nameof(Read));
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
throw new NotSupportedException(nameof(ReadAsync));
}
public override int ReadByte()
{
throw new NotSupportedException(nameof(ReadByte));
}
private void WriteToBuffer(byte[] array, ref int offset, ref int count)
{
int bytesToWrite = Math.Min(_bufferSize - _writePos, count);
if (bytesToWrite <= 0)
{
return;
}
Array.Copy(array, offset, _buffer, _writePos, bytesToWrite);
_writePos += bytesToWrite;
count -= bytesToWrite;
offset += bytesToWrite;
}
private void WriteToBuffer(byte[] array, ref int offset, ref int count, out Exception error)
{
try
{
error = null;
WriteToBuffer(array, ref offset, ref count);
}
catch (Exception ex)
{
error = ex;
}
}
public override void Write(byte[] array, int offset, int count)
{
Contract.Assert(array != null);
Contract.Assert(offset >= 0);
Contract.Assert(count >= 0);
Contract.Assert(count <= array.Length - offset);
EnsureNotClosed();
EnsureCanWrite();
#region Write algorithm comment
// We need to use the buffer, while avoiding unnecessary buffer usage / memory copies.
// We ASSUME that memory copies are much cheaper than writes to the underlying stream, so if an extra copy is
// guaranteed to reduce the number of writes, we prefer it.
// We pick a simple strategy that makes degenerate cases rare if our assumptions are right.
//
// For every write, we use a simple heuristic (below) to decide whether to use the buffer.
// The heuristic has the desirable property (*) that if the specified user data can fit into the currently available
// buffer space without filling it up completely, the heuristic will always tell us to use the buffer. It will also
// tell us to use the buffer in cases where the current write would fill the buffer, but the remaining data is small
// enough such that subsequent operations can use the buffer again.
//
// Algorithm:
// Determine whether or not to buffer according to the heuristic (below).
// If we decided to use the buffer:
// Copy as much user data as we can into the buffer.
// If we consumed all data: We are finished.
// Otherwise, write the buffer out.
// Copy the rest of user data into the now cleared buffer (no need to write out the buffer again as the heuristic
// will prevent it from being filled twice).
// If we decided not to use the buffer:
// Can the data already in the buffer and current user data be combines to a single write
// by allocating a "shadow" buffer of up to twice the size of _bufferSize (up to a limit to avoid LOH)?
// Yes, it can:
// Allocate a larger "shadow" buffer and ensure the buffered data is moved there.
// Copy user data to the shadow buffer.
// Write shadow buffer to the underlying stream in a single operation.
// No, it cannot (amount of data is still too large):
// Write out any data possibly in the buffer.
// Write out user data directly.
//
// Heuristic:
// If the subsequent write operation that follows the current write operation will result in a write to the
// underlying stream in case that we use the buffer in the current write, while it would not have if we avoided
// using the buffer in the current write (by writing current user data to the underlying stream directly), then we
// prefer to avoid using the buffer since the corresponding memory copy is wasted (it will not reduce the number
// of writes to the underlying stream, which is what we are optimising for).
// ASSUME that the next write will be for the same amount of bytes as the current write (most common case) and
// determine if it will cause a write to the underlying stream. If the next write is actually larger, our heuristic
// still yields the right behaviour, if the next write is actually smaller, we may making an unnecessary write to
// the underlying stream. However, this can only occur if the current write is larger than half the buffer size and
// we will recover after one iteration.
// We have:
// useBuffer = (_writePos + count + count < _bufferSize + _bufferSize)
//
// Example with _bufferSize = 20, _writePos = 6, count = 10:
//
// +---------------------------------------+---------------------------------------+
// | current buffer | next iteration's "future" buffer |
// +---------------------------------------+---------------------------------------+
// |0| | | | | | | | | |1| | | | | | | | | |2| | | | | | | | | |3| | | | | | | | | |
// |0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9|
// +-----------+-------------------+-------------------+---------------------------+
// | _writePos | current count | assumed next count|avail buff after next write|
// +-----------+-------------------+-------------------+---------------------------+
//
// A nice property (*) of this heuristic is that it will always succeed if the user data completely fits into the
// available buffer, i.e. if count < (_bufferSize - _writePos).
#endregion Write algorithm comment
Contract.Assert(_writePos < _bufferSize);
int totalUserBytes;
bool useBuffer;
checked
{
// We do not expect buffer sizes big enough for an overflow, but if it happens, lets fail early:
totalUserBytes = _writePos + count;
useBuffer = (totalUserBytes + count < (_bufferSize + _bufferSize));
}
if (useBuffer)
{
WriteToBuffer(array, ref offset, ref count);
if (_writePos < _bufferSize)
{
Contract.Assert(count == 0);
return;
}
Contract.Assert(count >= 0);
Contract.Assert(_writePos == _bufferSize);
Contract.Assert(_buffer != null);
_stream.Write(_buffer, 0, _writePos);
_writePos = 0;
WriteToBuffer(array, ref offset, ref count);
Contract.Assert(count == 0);
Contract.Assert(_writePos < _bufferSize);
}
else
{
// if (!useBuffer)
// Write out the buffer if necessary.
if (_writePos > 0)
{
Contract.Assert(_buffer != null);
Contract.Assert(totalUserBytes >= _bufferSize);
// Try avoiding extra write to underlying stream by combining previously buffered data with current user data:
if (totalUserBytes <= (_bufferSize + _bufferSize) && totalUserBytes <= MaxShadowBufferSize)
{
EnsureShadowBufferAllocated();
Array.Copy(array, offset, _buffer, _writePos, count);
_stream.Write(_buffer, 0, totalUserBytes);
_writePos = 0;
return;
}
_stream.Write(_buffer, 0, _writePos);
_writePos = 0;
}
// Write out user data.
_stream.Write(array, offset, count);
}
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
Contract.Assert(buffer != null);
Contract.Assert(offset >= 0);
Contract.Assert(count >= 0);
Contract.Assert(count <= buffer.Length - offset);
// Fast path check for cancellation already requested
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<int>(cancellationToken);
EnsureNotClosed();
EnsureCanWrite();
// Try to satisfy the request from the buffer synchronously. But still need a sem-lock in case that another
// Async IO Task accesses the buffer concurrently. If we fail to acquire the lock without waiting, make this
// an Async operation.
Task semaphoreLockTask = _sem.WaitAsync(cancellationToken);
if (semaphoreLockTask.Status == TaskStatus.RanToCompletion)
{
bool completeSynchronously = true;
try
{
Contract.Assert(_writePos < _bufferSize);
// If the write completely fits into the buffer, we can complete synchronously:
completeSynchronously = (count < _bufferSize - _writePos);
if (completeSynchronously)
{
Exception error;
WriteToBuffer(buffer, ref offset, ref count, out error);
Contract.Assert(count == 0);
return (error == null)
? Task.CompletedTask
: Task.FromException(error);
}
}
finally
{
if (completeSynchronously)
{
// if this is FALSE, we will be entering WriteToUnderlyingStreamAsync and releasing there.
_sem.Release();
}
}
}
// Delegate to the async implementation.
return WriteToUnderlyingStreamAsync(buffer, offset, count, cancellationToken, semaphoreLockTask);
}
private async Task WriteToUnderlyingStreamAsync(byte[] array, int offset, int count,
CancellationToken cancellationToken,
Task semaphoreLockTask)
{
EnsureNotClosed();
EnsureCanWrite();
// See the LARGE COMMENT in Write(..) for the explanation of the write buffer algorithm.
await semaphoreLockTask.ConfigureAwait(false);
try
{
// The buffer might have been changed by another async task while we were waiting on the semaphore.
// However, note that if we recalculate the sync completion condition to TRUE, then useBuffer will also be TRUE.
int totalUserBytes;
bool useBuffer;
checked
{
// We do not expect buffer sizes big enough for an overflow, but if it happens, lets fail early:
totalUserBytes = _writePos + count;
useBuffer = (totalUserBytes + count < (_bufferSize + _bufferSize));
}
if (useBuffer)
{
WriteToBuffer(array, ref offset, ref count);
if (_writePos < _bufferSize)
{
Contract.Assert(count == 0);
return;
}
Contract.Assert(count >= 0);
Contract.Assert(_writePos == _bufferSize);
Contract.Assert(_buffer != null);
await _stream.WriteAsync(_buffer, 0, _writePos, cancellationToken).ConfigureAwait(false);
_writePos = 0;
WriteToBuffer(array, ref offset, ref count);
Contract.Assert(count == 0);
Contract.Assert(_writePos < _bufferSize);
}
else
{
// if (!useBuffer)
// Write out the buffer if necessary.
if (_writePos > 0)
{
Contract.Assert(_buffer != null);
Contract.Assert(totalUserBytes >= _bufferSize);
// Try avoiding extra write to underlying stream by combining previously buffered data with current user data:
if (totalUserBytes <= (_bufferSize + _bufferSize) && totalUserBytes <= MaxShadowBufferSize)
{
EnsureShadowBufferAllocated();
Buffer.BlockCopy(array, offset, _buffer, _writePos, count);
await _stream.WriteAsync(_buffer, 0, totalUserBytes, cancellationToken).ConfigureAwait(false);
_writePos = 0;
return;
}
await _stream.WriteAsync(_buffer, 0, _writePos, cancellationToken).ConfigureAwait(false);
_writePos = 0;
}
// Write out user data.
await _stream.WriteAsync(array, offset, count, cancellationToken).ConfigureAwait(false);
}
}
finally
{
_sem.Release();
}
}
public override void WriteByte(byte value)
{
EnsureNotClosed();
// We should not be flushing here, but only writing to the underlying stream, but previous version flushed, so we keep this.
if (_writePos >= _bufferSize - 1)
{
FlushWrite();
}
_buffer[_writePos++] = value;
Contract.Assert(_writePos < _bufferSize);
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException(nameof(Seek));
}
public override void SetLength(long value)
{
throw new NotSupportedException(nameof(SetLength));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//------------------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient.Resources;
using System.Diagnostics;
namespace System.Data.SqlClient
{
internal sealed class SqlStatistics
{
static internal SqlStatistics StartTimer(SqlStatistics statistics)
{
if ((null != statistics) && !statistics.RequestExecutionTimer())
{
// we're re-entrant -- don't bother.
statistics = null;
}
return statistics;
}
static internal void StopTimer(SqlStatistics statistics)
{
if (null != statistics)
{
statistics.ReleaseAndUpdateExecutionTimer();
}
}
// internal values that are not exposed through properties
internal long _closeTimestamp;
internal long _openTimestamp;
internal long _startExecutionTimestamp;
internal long _startFetchTimestamp;
internal long _startNetworkServerTimestamp;
// internal values that are exposed through properties
internal long _buffersReceived;
internal long _buffersSent;
internal long _bytesReceived;
internal long _bytesSent;
internal long _connectionTime;
internal long _cursorOpens;
internal long _executionTime;
internal long _iduCount;
internal long _iduRows;
internal long _networkServerTime;
internal long _preparedExecs;
internal long _prepares;
internal long _selectCount;
internal long _selectRows;
internal long _serverRoundtrips;
internal long _sumResultSets;
internal long _transactions;
internal long _unpreparedExecs;
// these flags are required if statistics is turned on/off in the middle of command execution
private bool _waitForDoneAfterRow;
private bool _waitForReply;
internal bool WaitForDoneAfterRow
{
get
{
return _waitForDoneAfterRow;
}
set
{
_waitForDoneAfterRow = value;
}
}
internal bool WaitForReply
{
get
{
return _waitForReply;
}
}
internal SqlStatistics()
{
}
internal void ContinueOnNewConnection()
{
_startExecutionTimestamp = 0;
_startFetchTimestamp = 0;
_waitForDoneAfterRow = false;
_waitForReply = false;
}
internal IDictionary GetDictionary()
{
const int Count = 18;
var dictionary = new StatisticsDictionary(Count)
{
{ "BuffersReceived", _buffersReceived },
{ "BuffersSent", _buffersSent },
{ "BytesReceived", _bytesReceived },
{ "BytesSent", _bytesSent },
{ "CursorOpens", _cursorOpens },
{ "IduCount", _iduCount },
{ "IduRows", _iduRows },
{ "PreparedExecs", _preparedExecs },
{ "Prepares", _prepares },
{ "SelectCount", _selectCount },
{ "SelectRows", _selectRows },
{ "ServerRoundtrips", _serverRoundtrips },
{ "SumResultSets", _sumResultSets },
{ "Transactions", _transactions },
{ "UnpreparedExecs", _unpreparedExecs },
{ "ConnectionTime", ADP.TimerToMilliseconds(_connectionTime) },
{ "ExecutionTime", ADP.TimerToMilliseconds(_executionTime) },
{ "NetworkServerTime", ADP.TimerToMilliseconds(_networkServerTime) }
};
Debug.Assert(dictionary.Count == Count);
return dictionary;
}
internal bool RequestExecutionTimer()
{
if (_startExecutionTimestamp == 0)
{
ADP.TimerCurrent(out _startExecutionTimestamp);
return true;
}
return false;
}
internal void RequestNetworkServerTimer()
{
Debug.Assert(_startExecutionTimestamp != 0, "No network time expected outside execution period");
if (_startNetworkServerTimestamp == 0)
{
ADP.TimerCurrent(out _startNetworkServerTimestamp);
}
_waitForReply = true;
}
internal void ReleaseAndUpdateExecutionTimer()
{
if (_startExecutionTimestamp > 0)
{
_executionTime += (ADP.TimerCurrent() - _startExecutionTimestamp);
_startExecutionTimestamp = 0;
}
}
internal void ReleaseAndUpdateNetworkServerTimer()
{
if (_waitForReply && _startNetworkServerTimestamp > 0)
{
_networkServerTime += (ADP.TimerCurrent() - _startNetworkServerTimestamp);
_startNetworkServerTimestamp = 0;
}
_waitForReply = false;
}
internal void Reset()
{
_buffersReceived = 0;
_buffersSent = 0;
_bytesReceived = 0;
_bytesSent = 0;
_connectionTime = 0;
_cursorOpens = 0;
_executionTime = 0;
_iduCount = 0;
_iduRows = 0;
_networkServerTime = 0;
_preparedExecs = 0;
_prepares = 0;
_selectCount = 0;
_selectRows = 0;
_serverRoundtrips = 0;
_sumResultSets = 0;
_transactions = 0;
_unpreparedExecs = 0;
_waitForDoneAfterRow = false;
_waitForReply = false;
_startExecutionTimestamp = 0;
_startNetworkServerTimestamp = 0;
}
internal void SafeAdd(ref long value, long summand)
{
if (long.MaxValue - value > summand)
{
value += summand;
}
else
{
value = long.MaxValue;
}
}
internal long SafeIncrement(ref long value)
{
if (value < long.MaxValue) value++;
return value;
}
internal void UpdateStatistics()
{
// update connection time
if (_closeTimestamp >= _openTimestamp)
{
SafeAdd(ref _connectionTime, _closeTimestamp - _openTimestamp);
}
else
{
_connectionTime = long.MaxValue;
}
}
// We subclass Dictionary to provide our own implementation of CopyTo, Keys.CopyTo, and
// Values.CopyTo to match the behavior of Hashtable, which is used in the full framework:
//
// - When arrayIndex > array.Length, Hashtable throws ArgumentException whereas Dictionary
// throws ArgumentOutOfRangeException.
//
// - Hashtable specifies the ArgumentOutOfRangeException paramName as "arrayIndex" whereas
// Dictionary uses "index".
//
// - When the array is of a mismatched type, Hashtable throws InvalidCastException whereas
// Dictionary throws ArrayTypeMismatchException.
//
// - Hashtable allows copying values to a long[] array via Values.CopyTo, whereas Dictionary
// throws ArgumentException due to the "Target array type is not compatible with type of
// items in the collection" (when Dictionary<object, object> is used).
//
// Ideally this would derive from Dictionary<string, long>, but that would break compatibility
// with the full framework, which allows adding keys/values of any type.
private sealed class StatisticsDictionary : Dictionary<object, object>, IDictionary
{
private Collection _keys;
private Collection _values;
public StatisticsDictionary(int capacity) : base(capacity) { }
ICollection IDictionary.Keys => _keys ?? (_keys = new Collection(this, Keys));
ICollection IDictionary.Values => _values ?? (_values = new Collection(this, Values));
void ICollection.CopyTo(Array array, int arrayIndex)
{
ValidateCopyToArguments(array, arrayIndex);
foreach (KeyValuePair<object, object> pair in this)
{
var entry = new DictionaryEntry(pair.Key, pair.Value);
array.SetValue(entry, arrayIndex++);
}
}
private void CopyKeys(Array array, int arrayIndex)
{
ValidateCopyToArguments(array, arrayIndex);
foreach (KeyValuePair<object, object> pair in this)
{
array.SetValue(pair.Key, arrayIndex++);
}
}
private void CopyValues(Array array, int arrayIndex)
{
ValidateCopyToArguments(array, arrayIndex);
foreach (KeyValuePair<object, object> pair in this)
{
array.SetValue(pair.Value, arrayIndex++);
}
}
private void ValidateCopyToArguments(Array array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(Res.Arg_RankMultiDimNotSupported);
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException(nameof(arrayIndex), Res.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - arrayIndex < Count)
throw new ArgumentException(Res.Arg_ArrayPlusOffTooSmall);
}
private sealed class Collection : ICollection
{
private readonly StatisticsDictionary _dictionary;
private readonly ICollection _collection;
public Collection(StatisticsDictionary dictionary, ICollection collection)
{
Debug.Assert(dictionary != null);
Debug.Assert(collection != null);
Debug.Assert((collection is KeyCollection) || (collection is ValueCollection));
_dictionary = dictionary;
_collection = collection;
}
int ICollection.Count => _collection.Count;
bool ICollection.IsSynchronized => _collection.IsSynchronized;
object ICollection.SyncRoot => _collection.SyncRoot;
void ICollection.CopyTo(Array array, int arrayIndex)
{
if (_collection is KeyCollection)
{
_dictionary.CopyKeys(array, arrayIndex);
}
else
{
_dictionary.CopyValues(array, arrayIndex);
}
}
IEnumerator IEnumerable.GetEnumerator() => _collection.GetEnumerator();
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: ContractBase
**
** Purpose: Provides default implementations of IContract members
**
===========================================================*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.AddIn.Contract;
using System.AddIn;
using System.Runtime.Remoting.Lifetime;
using System.Security.Permissions;
using System.Security;
using System.Diagnostics.Contracts;
using System.Threading;
namespace System.AddIn.Pipeline
{
/// <summary>
/// Provides default implementations of IContract members
/// </summary>
public class ContractBase : MarshalByRefObject, IContract, ISponsor
{
private List<int> m_lifetimeTokens = new List<int>();
private List<String> m_contractIdentifiers;
private readonly Object m_contractIdentifiersLock = new Object();
private Random m_random;
// flag to indicate that the references that were taken have all been removed;
private bool m_zeroReferencesLeft = false;
private const int MaxAppDomainUnloadWaits = 15; // must be <=30, and 15 corresponds to ~16 sec
private int m_tokenOfAppdomainOwner;
public virtual bool RemoteEquals(IContract contract)
{
return this.Equals(contract);
}
public virtual String RemoteToString()
{
return this.ToString();
}
public virtual int GetRemoteHashCode()
{
return this.GetHashCode();
}
//
// return 'this' if we implement the contract, null otherwise
//
public virtual IContract QueryContract(String contractIdentifier)
{
if (contractIdentifier == null)
throw new ArgumentNullException("contractIdentifier");
System.Diagnostics.Contracts.Contract.EndContractBlock();
if (m_contractIdentifiers == null)
{
lock (m_contractIdentifiersLock)
{
if (m_contractIdentifiers == null)
{
Type t = this.GetType();
Type[] interfaces = t.GetInterfaces();
List<String> identifiers = new List<String>(interfaces.Length);
Type typeOfIContract = typeof(IContract);
foreach (Type iface in interfaces)
{
if (typeOfIContract.IsAssignableFrom(iface))
{
identifiers.Add(iface.AssemblyQualifiedName);
}
}
identifiers.Sort();
System.Threading.Thread.MemoryBarrier();
m_contractIdentifiers = identifiers;
}
}
}
int i = m_contractIdentifiers.BinarySearch(contractIdentifier);
return i >= 0 ? this : null;
}
public int AcquireLifetimeToken()
{
if (m_zeroReferencesLeft)
{
throw new InvalidOperationException(Res.TokenCountZero);
}
int next;
lock (m_lifetimeTokens)
{
// Lazily initialize m_random for perf.
if (m_random == null)
{
m_random = new Random();
}
next = m_random.Next();
while (m_lifetimeTokens.Contains(next))
{
next = m_random.Next();
}
m_lifetimeTokens.Add(next);
if (m_lifetimeTokens.Count == 1)
{
// Register as a sponsor the first time a token is aquired.
// need to do this here instead of in InitializeLifetimeService because of a bug in remoting
// involving security.
RegisterAsSponsor();
// Increment ref count on appdomain owner if needed
IContract owner = ContractHandle.AppDomainOwner(AppDomain.CurrentDomain);
if (owner != null && owner != this)
{
m_tokenOfAppdomainOwner = owner.AcquireLifetimeToken();
}
}
}
return next;
}
// <SecurityKernel Critical="True" Ring="0">
// <Asserts Name="Imperative: System.Security.Permissions.SecurityPermission" />
// <ReferencesCritical Name="Method: AppDomainUnload():Void" Ring="1" />
// </SecurityKernel>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2129:SecurityTransparentCodeShouldNotReferenceNonpublicSecurityCriticalCode", Justification = "This is a SecurityRules.Level1 assembly, in which this rule is being incorrectly applied")]
[System.Security.SecuritySafeCritical]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2128:SecurityTransparentCodeShouldNotAssert", Justification = "This is a SecurityRules.Level1 assembly, in which this rule is being incorrectly applied")]
public void RevokeLifetimeToken(int token)
{
lock (m_lifetimeTokens)
{
if (!m_lifetimeTokens.Remove(token))
throw new InvalidOperationException(Res.LifetimeTokenNotFound);
if (m_lifetimeTokens.Count == 0)
{
m_zeroReferencesLeft = true;
// hook to allow subclasses to clean up
OnFinalRevoke();
IContract owner = ContractHandle.AppDomainOwner(AppDomain.CurrentDomain);
if (owner != null)
{
if (owner == this)
{
// Create a separate thread to unload this appdomain, because we
// cannot shut down an appdomain from the Finalizer thread (though there
// is a bug that allows us to do so after the first appdomain has been
// unloaded, but let's not rely on that).
// We can consider using an threadpool thread to do this, but that would add
// test burden.
SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.ControlThread);
permission.Assert();
System.Threading.ThreadStart threadDelegate = new System.Threading.ThreadStart(AppDomainUnload);
System.Threading.Thread unloaderThread = new System.Threading.Thread(threadDelegate);
unloaderThread.Start();
}
else
owner.RevokeLifetimeToken(m_tokenOfAppdomainOwner);
}
}
}
}
// To be overridden if needed.
// This is similar to the Dispose pattern, but it is not public.
protected virtual void OnFinalRevoke()
{
}
// <SecurityKernel Critical="True" Ring="0">
// <Asserts Name="Imperative: System.Security.Permissions.SecurityPermission" />
// </SecurityKernel>
[System.Security.SecurityCritical]
private void AppDomainUnload()
{
// assert is needed for the Internet named permission set.
SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.ControlAppDomain);
permission.Assert();
// Sadly, AppDomains can refuse to unload under certain circumstances - mainly when threads get stuck in native code.
// If that happens, we will retry with increasing intervals.
// Other exceptions can also happen, in which case, we will trace the error message and quiety leave, otherwise the process might be torn down
// and this is never what we want as the user has no way to catch anything thrown by this thread.
try
{
for (int wait = 0; wait < MaxAppDomainUnloadWaits; wait++)
{
try
{
AppDomain.Unload(AppDomain.CurrentDomain);
// if we get here successfully, we have unloaded the AppDomain, and thus life is good
return;
}
catch (CannotUnloadAppDomainException)
{
// Double the interval and wait
Thread.Sleep(1 << wait);
}
}
// We end up here if all retries failed. We try once more, and if that throws - so be it.
// The outer handler will eat it and trace it out
Thread.Sleep(1 << MaxAppDomainUnloadWaits);
AppDomain.Unload(AppDomain.CurrentDomain);
}
// We are unloading our own AppDomain so one of these two will typically happen. They actually indicate success, and we don't need to report these
catch (AppDomainUnloadedException) { }
catch (ThreadAbortException) { }
// If we got here, this means that either we are done trying to unload or something unexpected happened during the unload. We trace that out
catch (Exception ex)
{
Trace.WriteLine(String.Format(System.Globalization.CultureInfo.CurrentCulture, Res.FailedToUnloadAppDomain, AppDomain.CurrentDomain.FriendlyName, ex.Message));
}
}
// <SecurityKernel Critical="True" Ring="0">
// <SatisfiesLinkDemand Name="ILease.get_InitialLeaseTime():System.TimeSpan" />
// </SecurityKernel>
[System.Security.SecurityCritical]
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Justification="SecurityRules.Level1 assemblies cannot contain Critical code, so they need LinkDemands to protect overridden Critical members from SecurityRules.Level2 assemblies")]
public TimeSpan Renewal(ILease lease)
{
if (lease == null)
throw new ArgumentNullException("lease");
System.Diagnostics.Contracts.Contract.EndContractBlock();
lock (m_lifetimeTokens)
{
return m_lifetimeTokens.Count > 0 ? lease.InitialLeaseTime : TimeSpan.Zero;
}
}
// <SecurityKernel Critical="True" Ring="0">
// <SatisfiesLinkDemand Name="MarshalByRefObject.GetLifetimeService():System.Object" />
// <SatisfiesLinkDemand Name="ILease.Register(System.Runtime.Remoting.Lifetime.ISponsor):System.Void" />
// <Asserts Name="Imperative: System.Security.Permissions.SecurityPermission" />
// </SecurityKernel>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification="Reviewed")]
[System.Security.SecuritySafeCritical]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2128:SecurityTransparentCodeShouldNotAssert", Justification = "This is a SecurityRules.Level1 assembly, in which this rule is being incorrectly applied")]
private void RegisterAsSponsor()
{
ILease baseLease = (ILease)GetLifetimeService();
if (baseLease != null)
{
// Assert permission to register as a sponsor for this lease. This is needed for the Internet permission level.
SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.RemotingConfiguration);
permission.Assert();
try
{
// register for sponsorship
baseLease.Register(this);
}
finally
{
CodeAccessPermission.RevertAssert();
}
}
// baseLease == null when we are not in a separate appdomain
}
}
}
| |
using System;
using VDS.RDF.Parsing;
using VDS.RDF;
using System.IO;
using System.Collections.Generic;
using VDS.RDF.Nodes;
using it.unifi.dsi.stlab.exceptions;
using System.Reflection;
using it.unifi.dsi.stlab.extension_methods.for_rdf_library;
using it.unifi.dsi.stlab.extension_methods;
using it.unifi.dsi.stlab.networkreasoner.model.gas;
namespace it.unifi.dsi.stlab.networkreasoner.model.rdfinterface
{
public class SpecificationLoader
{
private IRdfReader Reader{ get; set; }
private SpecificationLoader (IRdfReader reader)
{
this.Reader = reader;
}
public static SpecificationLoader MakeNTurtleSpecificationLoader ()
{
return new SpecificationLoader (new TurtleParser ());
}
public void LoadFileIntoGraphReraisingParseException (
String filename,
IGraph g)
{
this.LoadFileIntoGraph (
filename,
g,
HandleRdfParseException,
HandleRdfException
);
}
protected virtual void HandleRdfParseException (RdfParseException ex)
{
throw ex;
}
protected virtual void HandleRdfException (RdfException ex)
{
throw ex;
}
public void LoadFileIntoGraph (
String filename,
IGraph g,
Action<RdfParseException> onRdfParseException,
Action<RdfException> onRdfException)
{
try {
this.Reader.Load (g, filename);
} catch (RdfParseException parseEx) {
onRdfParseException.Invoke (parseEx);
} catch (RdfException rdfEx) {
onRdfException.Invoke (rdfEx);
}
}
public object Instantiate (Triple typeSpecification)
{
Object instance = null;
var canProceedToInstantiate = isPredicateNodeForQualifiedTypename (
typeSpecification.Predicate.AsValuedNode ().AsString ());
if (canProceedToInstantiate) {
Type typeToInstantiateFrom = Type.GetType (
typeSpecification.Object.ToString (), true);
instance = Activator.CreateInstance (typeToInstantiateFrom);
} else {
throw new ArgumentException (
"The given triple doesn't represent a type instantiation request.");
}
return instance;
}
protected virtual Boolean isPredicateNodeForQualifiedTypename (
String aPredicate)
{
return aPredicate.EndsWith ("/qualified-fullname");
}
public Dictionary<string, object> InstantiateObjects (
IGraph g)
{
Dictionary<String, Object> objects =
new Dictionary<String, Object> ();
INode rdfTypePredicateMatch = g.CreateUriNode (NamespaceRepository.rdf_type ());
var triples = g.GetTriplesWithPredicate (rdfTypePredicateMatch);
foreach (Triple triple in triples) {
String key = triple.Subject.AsValuedNode ().AsString ();
if (objects.ContainsKey (key) == false) {
INode pred = g.CreateUriNode (
NamespaceRepository.csharp_qualified_fullname ());
var enumerableOfTypeSpecifications = g.GetTriplesWithSubjectPredicate (
triple.Object, pred);
var typeSpecification = enumerableOfTypeSpecifications.
FetchExactlyOneThrowingExceptionsIfErrorsOccurs ();
objects.Add (key, this.Instantiate (typeSpecification));
}
}
return objects;
}
public class A : INodeExtensionMethods.NodeTypeDispatchingThrowExceptionForEachCase
{
Action<ILiteralNode> forLiteralNode { get; set; }
Action<IUriNode> forUriNode { get; set; }
public A (Action<ILiteralNode> forLiteralNode,
Action<IUriNode> forUriNode,
Exception ex):base(ex)
{
this.forLiteralNode = forLiteralNode;
this.forUriNode = forUriNode;
}
public override void literalNode (ILiteralNode iLiteralNode)
{
forLiteralNode.Invoke (iLiteralNode);
}
public override void uriNode (IUriNode iUriNode)
{
forUriNode.Invoke (iUriNode);
}
}
public void setPropertiesOnInstances (
Dictionary<string, object> objectsByUri, IGraph g)
{
foreach (Triple triple in g.Triples) {
String predicateAsString = triple.Predicate.AsValuedNode ().AsString ();
if (predicateAsString.Contains ("/property/")) {
String propertyName = predicateAsString.Substring (
predicateAsString.LastIndexOf ("/") + 1);
String subjectAsString = triple.Subject.AsValuedNode ().AsString ();
Object instance = objectsByUri [subjectAsString];
var propertyToSet = instance.GetType ().GetProperty (propertyName);
if (propertyToSet == null) {
throw new Exception (string.Format ("The property with " +
"name {0} cannot be used since it isn't present in " +
"the object to be modified", propertyName)
);
}
triple.Object.DispatchOnNodeType (new A (
forLiteralNode: aLiteralNode => setProperty (
propertyToSet, instance, ValueOfLiteralNode (aLiteralNode))
, forUriNode: aUriNode => {
Object alreadyExistingObject = this.ValueOfUriNode (
aUriNode, objectsByUri);
setProperty (propertyToSet, instance, alreadyExistingObject);
}, ex: new ShouldNotImplementException ())
);
}
}
}
protected virtual void setProperty (
PropertyInfo property, Object instance, Object value)
{
try {
property.SetValue (instance, value, null);
} catch (Exception e) {
throw e;
}
}
protected virtual Object ValueOfUriNode (IUriNode node,
Dictionary<string, object> objectsByUri)
{
Func<Uri, Object> mapper = uri => {
return objectsByUri [uri.AbsoluteUri];
};
return node.GetValue (mapper);
}
protected virtual Object ValueOfLiteralNode (ILiteralNode node)
{
return node.GetValue ();
}
public object FindMainNetwork (Dictionary<string, object> objectsByUri, IGraph g)
{
var triples = g.GetTriplesWithPredicate (
NamespaceRepository.tag_main_network ());
var mainNetworkTripleWithTag = triples.
FetchExactlyOneThrowingExceptionsIfErrorsOccurs ();
String key = mainNetworkTripleWithTag.Subject.AsValuedNode ().AsString ();
return objectsByUri [key];
}
public ParserResultReceiver GetParserResultReceiverFrom (
Dictionary<string, object> objectsByUri, IGraph g)
{
var triples = g.GetTriplesWithPredicate (
NamespaceRepository.tag_parser_result_receiver_property_name ());
var mainNetworkTripleWithTag = triples.
FetchExactlyOneThrowingExceptionsIfErrorsOccurs ();
String mainNetworkKey = mainNetworkTripleWithTag.Subject.AsValuedNode ().AsString ();
String propertyName = mainNetworkTripleWithTag.Object.ToString ();
Object mainNetwork = objectsByUri [mainNetworkKey];
var parserResultReceiver = mainNetwork.GetType ().GetProperty (
propertyName).GetValue (mainNetwork, null);
return parserResultReceiver as ParserResultReceiver;
}
public void Load (
string filename, ParserResultReceiver parserResultReceiver)
{
IGraph g = new Graph ();
Dictionary<String, Object> objectsByUri = null;
ReifySpecification (filename, g, out objectsByUri);
sendResultTo (parserResultReceiver, objectsByUri);
}
public T Load <T> (string filename) where T : class
{
IGraph g = new Graph ();
Dictionary<String, Object> objectsByUri = null;
ReifySpecification (filename, g, out objectsByUri);
T mainNetwork = this.FindMainNetwork (objectsByUri, g)as T;
var parserResultReceiver = this.GetParserResultReceiverFrom (objectsByUri, g);
sendResultTo (parserResultReceiver, objectsByUri);
return mainNetwork;
}
protected virtual void sendResultTo (
ParserResultReceiver parserResultReceiver,
Dictionary<String, Object> parserResult)
{
parserResultReceiver.receiveResults (parserResult);
}
public void ReifySpecification (string filename,
IGraph g,
out Dictionary<string, object> objectsByUri)
{
this.LoadFileIntoGraphReraisingParseException (filename, g);
objectsByUri = this.InstantiateObjects (g);
this.setPropertiesOnInstances (objectsByUri, g);
this.removeDefinitionsAfterParsing (objectsByUri, g);
}
public void removeDefinitionsAfterParsing (
Dictionary<string, object> objectsByUri, IGraph g)
{
var triples = g.GetTriplesWithPredicate (
NamespaceRepository.tag_delete_after_parsing ());
foreach (Triple triple in triples) {
var handler = new A (aLiteralNode => {
Boolean reallyDelete;
if (Boolean.TryParse (aLiteralNode.Value, out reallyDelete)) {
if (reallyDelete) {
String objKeyToDelete = triple.Subject.AsValuedNode ().AsString ();
objectsByUri.Remove (objKeyToDelete);
// g.Retract (triple);
}
}
}, aUriNode => {}, null);
triple.Object.DispatchOnNodeType (handler);
}
}
}
}
| |
// 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.Runtime;
using System.ServiceModel.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace System.ServiceModel.Channels
{
public abstract class RequestChannel : ChannelBase, IRequestChannel, IAsyncRequestChannel
{
private bool _manualAddressing;
private List<IRequestBase> _outstandingRequests = new List<IRequestBase>();
private EndpointAddress _to;
private Uri _via;
private TaskCompletionSource<object> _closedTcs;
private bool _closed;
private int _outstandRequestCloseCount;
protected RequestChannel(ChannelManagerBase channelFactory, EndpointAddress to, Uri via, bool manualAddressing)
: base(channelFactory)
{
if (!manualAddressing)
{
if (to == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("to");
}
}
_manualAddressing = manualAddressing;
_to = to;
_via = via;
}
protected bool ManualAddressing
{
get
{
return _manualAddressing;
}
}
public EndpointAddress RemoteAddress
{
get
{
return _to;
}
}
public Uri Via
{
get
{
return _via;
}
}
protected void AbortPendingRequests()
{
IRequestBase[] requestsToAbort = CopyPendingRequests(false);
if (requestsToAbort != null)
{
foreach (IRequestBase request in requestsToAbort)
{
request.Abort(this);
}
}
}
private void FinishClose()
{
lock (_outstandingRequests)
{
if (!_closed)
{
_closed = true;
var closedTcs = _closedTcs;
if (closedTcs != null)
{
closedTcs.TrySetResult(null);
_closedTcs = null;
}
}
}
}
private IRequestBase[] SetupWaitForPendingRequests()
{
return this.CopyPendingRequests(true);
}
protected void WaitForPendingRequests(TimeSpan timeout)
{
WaitForPendingRequestsAsync(timeout).Wait();
}
internal protected async Task WaitForPendingRequestsAsync(TimeSpan timeout)
{
IRequestBase[] pendingRequests = SetupWaitForPendingRequests();
if (pendingRequests != null)
{
if (!await _closedTcs.Task.AwaitWithTimeout(timeout))
{
foreach (IRequestBase request in pendingRequests)
{
request.Abort(this);
}
}
}
FinishClose();
}
private IRequestBase[] CopyPendingRequests(bool createTcsIfNecessary)
{
IRequestBase[] requests = null;
lock (_outstandingRequests)
{
if (_outstandingRequests.Count > 0)
{
requests = new IRequestBase[_outstandingRequests.Count];
_outstandingRequests.CopyTo(requests);
_outstandingRequests.Clear();
if (createTcsIfNecessary && _closedTcs == null)
{
_closedTcs = new TaskCompletionSource<object>();
}
}
}
return requests;
}
protected void FaultPendingRequests()
{
IRequestBase[] requestsToFault = CopyPendingRequests(false);
if (requestsToFault != null)
{
foreach (IRequestBase request in requestsToFault)
{
request.Fault(this);
}
}
}
public override T GetProperty<T>()
{
if (typeof(T) == typeof(IRequestChannel))
{
return (T)(object)this;
}
T baseProperty = base.GetProperty<T>();
if (baseProperty != null)
{
return baseProperty;
}
return default(T);
}
protected override void OnAbort()
{
AbortPendingRequests();
}
private void ReleaseRequest(IRequestBase request)
{
try
{
if (request != null)
{
// Synchronization of OnReleaseRequest is the
// responsibility of the concrete implementation of request.
request.OnReleaseRequest();
}
}
finally
{
// Setting _closedTcs needs to happen in a finally block to guarantee that we complete
// a waiting close even if OnReleaseRequest throws
lock (_outstandingRequests)
{
_outstandingRequests.Remove(request);
var outstandingRequestCloseCount = Interlocked.Decrement(ref _outstandRequestCloseCount);
if (outstandingRequestCloseCount == 0 && _closedTcs != null)
{
// When we are closed or closing, _closedTcs is managed by the close logic.
if (!_closed)
{
// Protect against close altering _closedTcs concurrently by caching the value.
// Calling TrySetResult on an already completed TCS is a no-op
var closedTcs = _closedTcs;
if (closedTcs != null)
{
closedTcs.TrySetResult(null);
}
}
}
}
}
}
private void TrackRequest(IRequestBase request)
{
lock (_outstandingRequests)
{
ThrowIfDisposedOrNotOpen(); // make sure that we haven't already snapshot our collection
_outstandingRequests.Add(request);
Interlocked.Increment(ref _outstandRequestCloseCount);
}
}
public IAsyncResult BeginRequest(Message message, AsyncCallback callback, object state)
{
return this.BeginRequest(message, this.DefaultSendTimeout, callback, state);
}
public IAsyncResult BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, object state)
{
return RequestAsync(message, timeout).ToApm(callback, state);
}
protected abstract IAsyncRequest CreateAsyncRequest(Message message);
public Message EndRequest(IAsyncResult result)
{
return result.ToApmEnd<Message>();
}
public Message Request(Message message)
{
return this.Request(message, this.DefaultSendTimeout);
}
public Message Request(Message message, TimeSpan timeout)
{
return RequestAsyncInternal(message, timeout).WaitForCompletionNoSpin();
}
public Task<Message> RequestAsync(Message message)
{
return RequestAsync(message, this.DefaultSendTimeout);
}
private async Task<Message> RequestAsyncInternal(Message message, TimeSpan timeout)
{
await TaskHelpers.EnsureDefaultTaskScheduler();
return await RequestAsync(message, timeout);
}
public async Task<Message> RequestAsync(Message message, TimeSpan timeout)
{
if (message == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
}
if (timeout < TimeSpan.Zero)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("timeout", timeout, SR.SFxTimeoutOutOfRange0));
ThrowIfDisposedOrNotOpen();
AddHeadersTo(message);
IAsyncRequest request = CreateAsyncRequest(message);
TrackRequest(request);
try
{
Message reply;
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
TimeSpan savedTimeout = timeoutHelper.RemainingTime();
try
{
await request.SendRequestAsync(message, timeoutHelper);
}
catch (TimeoutException timeoutException)
{
throw TraceUtility.ThrowHelperError(new TimeoutException(SR.Format(SR.RequestChannelSendTimedOut, savedTimeout),
timeoutException), message);
}
savedTimeout = timeoutHelper.RemainingTime();
try
{
reply = await request.ReceiveReplyAsync(timeoutHelper);
}
catch (TimeoutException timeoutException)
{
throw TraceUtility.ThrowHelperError(new TimeoutException(SR.Format(SR.RequestChannelWaitForReplyTimedOut, savedTimeout),
timeoutException), message);
}
return reply;
}
finally
{
ReleaseRequest(request);
}
}
protected virtual void AddHeadersTo(Message message)
{
if (!_manualAddressing && _to != null)
{
_to.ApplyTo(message);
}
}
}
public interface IRequestBase
{
void Abort(RequestChannel requestChannel);
void Fault(RequestChannel requestChannel);
void OnReleaseRequest();
}
public interface IAsyncRequest : IRequestBase
{
Task SendRequestAsync(Message message, TimeoutHelper timeoutHelper);
Task<Message> ReceiveReplyAsync(TimeoutHelper timeoutHelper);
}
}
| |
//
// System.Web.Services.Description.ProtocolImporter.cs
//
// Author:
// Tim Coleman (tim@timcoleman.com)
// Lluis Sanchez Gual (lluis@ximian.com)
//
// Copyright (C) Tim Coleman, 2002
//
//
// 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.CodeDom;
using System.CodeDom.Compiler;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Schema;
using System.Collections;
using System.Configuration;
namespace System.Web.Services.Description {
public abstract class ProtocolImporter {
#region Fields
Binding binding;
string className;
CodeIdentifiers classNames;
CodeNamespace codeNamespace;
CodeCompileUnit codeCompileUnit;
CodeTypeDeclaration codeTypeDeclaration;
Message inputMessage;
string methodName;
Operation operation;
OperationBinding operationBinding;
Message outputMessage;
Port port;
PortType portType;
string protocolName;
Service service;
ServiceDescriptionImportWarnings warnings = (ServiceDescriptionImportWarnings)0;
ServiceDescriptionImporter descriptionImporter;
ImportInfo iinfo;
XmlSchemas xmlSchemas;
XmlSchemas soapSchemas;
#if NET_2_0
ArrayList asyncTypes = new ArrayList ();
#endif
#endregion // Fields
#region Constructors
protected ProtocolImporter ()
{
}
#endregion // Constructors
#region Properties
[MonoTODO]
public XmlSchemas AbstractSchemas {
get { return descriptionImporter.Schemas; }
}
public Binding Binding {
get { return binding; }
}
public string ClassName {
get { return className; }
}
public CodeIdentifiers ClassNames {
get { return classNames; }
}
public CodeNamespace CodeNamespace {
get { return codeNamespace; }
}
public CodeTypeDeclaration CodeTypeDeclaration {
get { return codeTypeDeclaration; }
}
[MonoTODO]
public XmlSchemas ConcreteSchemas {
get { return descriptionImporter.Schemas; }
}
public Message InputMessage {
get { return inputMessage; }
}
public string MethodName {
get { return methodName; }
}
public Operation Operation {
get { return operation; }
}
public OperationBinding OperationBinding {
get { return operationBinding; }
}
public Message OutputMessage {
get { return outputMessage; }
}
public Port Port {
get { return port; }
}
public PortType PortType {
get { return portType; }
}
public abstract string ProtocolName {
get;
}
public XmlSchemas Schemas {
get { return descriptionImporter.Schemas; }
}
public Service Service {
get { return service; }
}
public ServiceDescriptionCollection ServiceDescriptions {
get { return descriptionImporter.ServiceDescriptions; }
}
public ServiceDescriptionImportStyle Style {
get { return descriptionImporter.Style; }
}
public ServiceDescriptionImportWarnings Warnings {
get { return warnings; }
set { warnings = value; }
}
internal ImportInfo ImportInfo
{
get { return iinfo; }
}
internal XmlSchemas LiteralSchemas
{
get { return xmlSchemas; }
}
internal XmlSchemas EncodedSchemas
{
get { return soapSchemas; }
}
#if NET_2_0
internal CodeGenerationOptions CodeGenerationOptions {
get { return descriptionImporter.CodeGenerationOptions; }
}
internal ICodeGenerator CodeGenerator {
get { return descriptionImporter.CodeGenerator; }
}
internal ImportContext ImportContext {
get { return descriptionImporter.Context; }
}
#endif
#endregion // Properties
#region Methods
internal bool Import (ServiceDescriptionImporter descriptionImporter, CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit, ArrayList importInfo)
{
this.descriptionImporter = descriptionImporter;
this.classNames = new CodeIdentifiers();;
this.codeNamespace = codeNamespace;
this.codeCompileUnit = codeCompileUnit;
warnings = (ServiceDescriptionImportWarnings) 0;
bool found = false;
ClasifySchemas (importInfo);
BeginNamespace ();
foreach (ImportInfo info in importInfo)
{
foreach (Service service in info.ServiceDescription.Services)
{
this.service = service;
int bindingCount = 0;
foreach (Port port in service.Ports)
{
binding = ServiceDescriptions.GetBinding (port.Binding);
if (IsBindingSupported ()) bindingCount ++;
}
foreach (Port port in service.Ports)
{
this.iinfo = info;
this.port = port;
binding = ServiceDescriptions.GetBinding (port.Binding);
if (!IsBindingSupported ()) continue;
found = true;
ImportPortBinding (bindingCount > 1);
}
}
}
if (!found)
{
// Looks like MS.NET generates classes for all bindings if
// no services are present
foreach (ImportInfo info in importInfo)
{
this.iinfo = info;
foreach (Binding b in info.ServiceDescription.Bindings)
{
this.binding = b;
this.service = null;
this.port = null;
if (!IsBindingSupported ()) continue;
found = true;
ImportPortBinding (true);
}
}
}
EndNamespace ();
if (!found) warnings = ServiceDescriptionImportWarnings.NoCodeGenerated;
return true;
}
void ImportPortBinding (bool multipleBindings)
{
if (port != null) {
if (multipleBindings) className = port.Name;
else className = service.Name;
}
else
className = binding.Name;
className = classNames.AddUnique (CodeIdentifier.MakeValid (className), port);
className = className.Replace ("_x0020_", ""); // MS.NET seems to do this
try
{
portType = ServiceDescriptions.GetPortType (binding.Type);
if (portType == null) throw new Exception ("Port type not found: " + binding.Type);
CodeTypeDeclaration codeClass = BeginClass ();
codeTypeDeclaration = codeClass;
AddCodeType (codeClass, port != null ? port.Documentation : null);
codeClass.Attributes = MemberAttributes.Public;
if (service != null && service.Documentation != null && service.Documentation != "")
AddComments (codeClass, service.Documentation);
if (Style == ServiceDescriptionImportStyle.Client) {
CodeAttributeDeclaration att = new CodeAttributeDeclaration ("System.Diagnostics.DebuggerStepThroughAttribute");
AddCustomAttribute (codeClass, att, true);
att = new CodeAttributeDeclaration ("System.ComponentModel.DesignerCategoryAttribute");
att.Arguments.Add (GetArg ("code"));
AddCustomAttribute (codeClass, att, true);
}
else
codeClass.TypeAttributes = System.Reflection.TypeAttributes.Abstract | System.Reflection.TypeAttributes.Public;
if (binding.Operations.Count == 0) {
warnings |= ServiceDescriptionImportWarnings.NoMethodsGenerated;
return;
}
foreach (OperationBinding oper in binding.Operations)
{
operationBinding = oper;
operation = FindPortOperation ();
if (operation == null) throw new Exception ("Operation " + operationBinding.Name + " not found in portType " + PortType.Name);
foreach (OperationMessage omsg in operation.Messages)
{
Message msg = ServiceDescriptions.GetMessage (omsg.Message);
if (msg == null) throw new Exception ("Message not found: " + omsg.Message);
if (omsg is OperationInput)
inputMessage = msg;
else
outputMessage = msg;
}
CodeMemberMethod method = GenerateMethod ();
if (method != null)
{
methodName = method.Name;
if (operation.Documentation != null && operation.Documentation != "")
AddComments (method, operation.Documentation);
#if NET_2_0
if (Style == ServiceDescriptionImportStyle.Client)
AddAsyncMembers (method.Name, method);
#endif
}
}
#if NET_2_0
if (Style == ServiceDescriptionImportStyle.Client)
AddAsyncTypes ();
#endif
EndClass ();
}
catch (InvalidOperationException ex)
{
warnings |= ServiceDescriptionImportWarnings.NoCodeGenerated;
UnsupportedBindingWarning (ex.Message);
}
}
Operation FindPortOperation ()
{
string inMessage = null;
string outMessage = null;
int numMsg = 1;
if (operationBinding.Input == null) throw new InvalidOperationException ("Input operation binding not found");
inMessage = (operationBinding.Input.Name != null) ? operationBinding.Input.Name : operationBinding.Name;
if (operationBinding.Output != null) {
outMessage = (operationBinding.Output.Name != null) ? operationBinding.Output.Name : operationBinding.Name;
numMsg++;
}
string operName = operationBinding.Name;
Operation foundOper = null;
foreach (Operation oper in PortType.Operations)
{
if (oper.Name == operName)
{
int hits = 0;
foreach (OperationMessage omsg in oper.Messages)
{
if (omsg is OperationInput && GetOperMessageName (omsg, operName) == inMessage) hits++;
if (omsg is OperationOutput && GetOperMessageName (omsg, operName) == outMessage) hits++;
}
if (hits == numMsg) return oper;
foundOper = oper;
}
}
return foundOper;
}
string GetOperMessageName (OperationMessage msg, string operName)
{
if (msg.Name == null) return operName;
else return msg.Name;
}
internal void GenerateServiceUrl (string location, CodeStatementCollection stms)
{
if (ImportInfo.AppSettingUrlKey == null || ImportInfo.AppSettingUrlKey == string.Empty) {
if (location != null) {
CodeExpression ce = new CodeFieldReferenceExpression (new CodeThisReferenceExpression(), "Url");
CodeAssignStatement cas = new CodeAssignStatement (ce, new CodePrimitiveExpression (location));
stms.Add (cas);
}
}
else
{
CodeExpression prop = new CodePropertyReferenceExpression (new CodeTypeReferenceExpression ("System.Configuration.ConfigurationSettings"), "AppSettings");
prop = new CodeIndexerExpression (prop, new CodePrimitiveExpression (ImportInfo.AppSettingUrlKey));
stms.Add (new CodeVariableDeclarationStatement (typeof(string), "urlSetting", prop));
CodeExpression urlSetting = new CodeVariableReferenceExpression ("urlSetting");
CodeExpression thisUrl = new CodeFieldReferenceExpression (new CodeThisReferenceExpression(), "Url");
CodeStatement[] trueStms = new CodeStatement [1];
CodeExpression ce = urlSetting;
CodeExpression cond = new CodeBinaryOperatorExpression (urlSetting, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));
if (ImportInfo.AppSettingBaseUrl != null)
ce = new CodeMethodInvokeExpression (new CodeTypeReferenceExpression (typeof(string)), "Concat", ce, new CodePrimitiveExpression (ImportInfo.AppSettingBaseUrl));
trueStms [0] = new CodeAssignStatement (thisUrl, ce);
if (location != null) {
CodeStatement[] falseStms = new CodeStatement [1];
falseStms [0] = new CodeAssignStatement (thisUrl, new CodePrimitiveExpression (location));
stms.Add (new CodeConditionStatement (cond, trueStms, falseStms));
}
else
stms.Add (new CodeConditionStatement (cond, trueStms));
}
}
void ClasifySchemas (ArrayList importInfo)
{
// I don't like this, but I could not find any other way of clasifying
// schemas between encoded and literal.
xmlSchemas = new XmlSchemas ();
soapSchemas = new XmlSchemas ();
foreach (ImportInfo info in importInfo)
{
foreach (Service service in info.ServiceDescription.Services)
{
foreach (Port port in service.Ports)
{
this.iinfo = info;
this.port = port;
binding = ServiceDescriptions.GetBinding (port.Binding);
if (binding == null) continue;
portType = ServiceDescriptions.GetPortType (binding.Type);
if (portType == null) continue;
foreach (OperationBinding oper in binding.Operations)
{
operationBinding = oper;
operation = FindPortOperation ();
if (operation == null) continue;
foreach (OperationMessage omsg in operation.Messages)
{
Message msg = ServiceDescriptions.GetMessage (omsg.Message);
if (msg == null) continue;
if (omsg is OperationInput)
inputMessage = msg;
else
outputMessage = msg;
}
if (GetMessageEncoding (oper.Input) == SoapBindingUse.Encoded)
AddMessageSchema (soapSchemas, oper.Input, inputMessage);
else
AddMessageSchema (xmlSchemas, oper.Input, inputMessage);
if (oper.Output != null) {
if (GetMessageEncoding (oper.Output) == SoapBindingUse.Encoded)
AddMessageSchema (soapSchemas, oper.Output, outputMessage);
else
AddMessageSchema (xmlSchemas, oper.Output, outputMessage);
}
}
}
}
}
XmlSchemas defaultList = xmlSchemas;
if (xmlSchemas.Count == 0 && soapSchemas.Count > 0)
defaultList = soapSchemas;
// Schemas not referenced by any message
foreach (XmlSchema sc in Schemas)
{
if (!soapSchemas.Contains (sc) && !xmlSchemas.Contains (sc)) {
if (ImportsEncodedNamespace (sc))
soapSchemas.Add (sc);
else
defaultList.Add (sc);
}
}
}
void AddMessageSchema (XmlSchemas schemas, MessageBinding mb, Message msg)
{
foreach (MessagePart part in msg.Parts)
{
if (part.Element != XmlQualifiedName.Empty)
AddIncludingSchema (schemas, part.Element.Namespace);
else if (part.Type != XmlQualifiedName.Empty)
AddIncludingSchema (schemas, part.Type.Namespace);
}
SoapBodyBinding sbb = mb.Extensions.Find (typeof(SoapBodyBinding)) as SoapBodyBinding;
if (sbb != null) AddIncludingSchema (schemas, sbb.Namespace);
}
void AddIncludingSchema (XmlSchemas list, string ns)
{
XmlSchema sc = Schemas [ns];
if (sc == null || list.Contains (sc)) return;
list.Add (sc);
foreach (XmlSchemaObject ob in sc.Includes)
{
XmlSchemaImport import = ob as XmlSchemaImport;
if (import != null) AddIncludingSchema (list, import.Namespace);
}
}
SoapBindingUse GetMessageEncoding (MessageBinding mb)
{
SoapBodyBinding sbb = mb.Extensions.Find (typeof(SoapBodyBinding)) as SoapBodyBinding;
if (sbb == null)
{
if (mb is InputBinding) return SoapBindingUse.Encoded;
else return SoapBindingUse.Literal;
}
else
if (sbb.Use == SoapBindingUse.Encoded) return SoapBindingUse.Encoded;
else
return SoapBindingUse.Literal;
}
bool ImportsEncodedNamespace (XmlSchema sc)
{
foreach (XmlSchemaObject ob in sc.Includes)
{
XmlSchemaImport import = ob as XmlSchemaImport;
if (import.Namespace == SoapProtocolReflector.EncodingNamespace) return true;
}
return false;
}
#if NET_2_0
void AddAsyncTypes ()
{
foreach (CodeTypeDeclaration type in asyncTypes)
codeNamespace.Types.Add (type);
asyncTypes.Clear ();
}
void AddAsyncMembers (string messageName, CodeMemberMethod method)
{
CodeThisReferenceExpression ethis = new CodeThisReferenceExpression();
CodePrimitiveExpression enull = new CodePrimitiveExpression (null);
CodeMemberField codeField = new CodeMemberField (typeof(System.Threading.SendOrPostCallback), messageName + "OperationCompleted");
codeField.Attributes = MemberAttributes.Private;
CodeTypeDeclaration.Members.Add (codeField);
// Event arguments class
string argsClassName = classNames.AddUnique (messageName + "CompletedEventArgs", null);
CodeTypeDeclaration argsClass = new CodeTypeDeclaration (argsClassName);
argsClass.BaseTypes.Add (new CodeTypeReference ("System.ComponentModel.AsyncCompletedEventArgs"));
CodeMemberField resultsField = new CodeMemberField (typeof(object[]), "results");
resultsField.Attributes = MemberAttributes.Private;
argsClass.Members.Add (resultsField);
CodeConstructor cc = new CodeConstructor ();
cc.Attributes = MemberAttributes.Assembly;
cc.Parameters.Add (new CodeParameterDeclarationExpression (typeof(object[]), "results"));
cc.Parameters.Add (new CodeParameterDeclarationExpression (typeof(System.Exception), "exception"));
cc.Parameters.Add (new CodeParameterDeclarationExpression (typeof(bool), "cancelled"));
cc.Parameters.Add (new CodeParameterDeclarationExpression (typeof(object), "userState"));
cc.BaseConstructorArgs.Add (new CodeVariableReferenceExpression ("exception"));
cc.BaseConstructorArgs.Add (new CodeVariableReferenceExpression ("cancelled"));
cc.BaseConstructorArgs.Add (new CodeVariableReferenceExpression ("userState"));
CodeExpression thisResults = new CodeFieldReferenceExpression (ethis, "results");
cc.Statements.Add (new CodeAssignStatement (thisResults, new CodeVariableReferenceExpression ("results")));
argsClass.Members.Add (cc);
int ind = 0;
if (method.ReturnType.BaseType != "System.Void")
argsClass.Members.Add (CreateArgsProperty (method.ReturnType, "Result", ind++));
foreach (CodeParameterDeclarationExpression par in method.Parameters)
{
if (par.Direction == FieldDirection.Out || par.Direction == FieldDirection.Ref)
argsClass.Members.Add (CreateArgsProperty (par.Type, par.Name, ind++));
}
bool needsArgsClass = (ind > 0);
if (needsArgsClass)
asyncTypes.Add (argsClass);
else
argsClassName = "System.ComponentModel.AsyncCompletedEventArgs";
// Event delegate type
CodeTypeDelegate delegateType = new CodeTypeDelegate (messageName + "CompletedEventHandler");
delegateType.Parameters.Add (new CodeParameterDeclarationExpression (typeof(object), "sender"));
delegateType.Parameters.Add (new CodeParameterDeclarationExpression (argsClassName, "args"));
// Event member
CodeMemberEvent codeEvent = new CodeMemberEvent ();
codeEvent.Name = messageName + "Completed";
codeEvent.Type = new CodeTypeReference (delegateType.Name);
CodeTypeDeclaration.Members.Add (codeEvent);
// Async method (without user state param)
CodeMemberMethod am = new CodeMemberMethod ();
am.Attributes = MemberAttributes.Public | MemberAttributes.Final;
am.Name = method.Name + "Async";
am.ReturnType = new CodeTypeReference (typeof(void));
CodeMethodInvokeExpression inv;
inv = new CodeMethodInvokeExpression (ethis, am.Name);
am.Statements.Add (inv);
// On...Completed method
CodeMemberMethod onCompleted = new CodeMemberMethod ();
onCompleted.Name = "On" + messageName + "Completed";
onCompleted.Attributes = MemberAttributes.Private | MemberAttributes.Final;
onCompleted.ReturnType = new CodeTypeReference (typeof(void));
onCompleted.Parameters.Add (new CodeParameterDeclarationExpression (typeof(object), "arg"));
CodeConditionStatement anIf = new CodeConditionStatement ();
CodeExpression eventField = new CodeEventReferenceExpression (ethis, codeEvent.Name);
anIf.Condition = new CodeBinaryOperatorExpression (eventField, CodeBinaryOperatorType.IdentityInequality, enull);
CodeExpression castedArg = new CodeCastExpression (typeof(System.Web.Services.Protocols.InvokeCompletedEventArgs), new CodeVariableReferenceExpression ("arg"));
CodeStatement invokeArgs = new CodeVariableDeclarationStatement (typeof(System.Web.Services.Protocols.InvokeCompletedEventArgs), "invokeArgs", castedArg);
anIf.TrueStatements.Add (invokeArgs);
CodeDelegateInvokeExpression delegateInvoke = new CodeDelegateInvokeExpression ();
delegateInvoke.TargetObject = eventField;
delegateInvoke.Parameters.Add (ethis);
CodeObjectCreateExpression argsInstance = new CodeObjectCreateExpression (argsClassName);
CodeExpression invokeArgsVar = new CodeVariableReferenceExpression ("invokeArgs");
if (needsArgsClass) argsInstance.Parameters.Add (new CodeFieldReferenceExpression (invokeArgsVar, "Results"));
argsInstance.Parameters.Add (new CodeFieldReferenceExpression (invokeArgsVar, "Error"));
argsInstance.Parameters.Add (new CodeFieldReferenceExpression (invokeArgsVar, "Cancelled"));
argsInstance.Parameters.Add (new CodeFieldReferenceExpression (invokeArgsVar, "UserState"));
delegateInvoke.Parameters.Add (argsInstance);
anIf.TrueStatements.Add (delegateInvoke);
onCompleted.Statements.Add (anIf);
// Async method
CodeMemberMethod asyncMethod = new CodeMemberMethod ();
asyncMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
asyncMethod.Name = method.Name + "Async";
asyncMethod.ReturnType = new CodeTypeReference (typeof(void));
CodeExpression delegateField = new CodeFieldReferenceExpression (ethis, codeField.Name);
anIf = new CodeConditionStatement ();
anIf.Condition = new CodeBinaryOperatorExpression (delegateField, CodeBinaryOperatorType.IdentityEquality, enull);;
CodeExpression delegateRef = new CodeMethodReferenceExpression (ethis, onCompleted.Name);
CodeExpression newDelegate = new CodeObjectCreateExpression (typeof(System.Threading.SendOrPostCallback), delegateRef);
CodeAssignStatement cas = new CodeAssignStatement (delegateField, newDelegate);
anIf.TrueStatements.Add (cas);
asyncMethod.Statements.Add (anIf);
CodeArrayCreateExpression paramsArray = new CodeArrayCreateExpression (typeof(object));
// Assign parameters
CodeIdentifiers paramsIds = new CodeIdentifiers ();
foreach (CodeParameterDeclarationExpression par in method.Parameters)
{
paramsIds.Add (par.Name, null);
if (par.Direction == FieldDirection.In || par.Direction == FieldDirection.Ref) {
CodeParameterDeclarationExpression inpar = new CodeParameterDeclarationExpression (par.Type, par.Name);
am.Parameters.Add (inpar);
asyncMethod.Parameters.Add (inpar);
inv.Parameters.Add (new CodeVariableReferenceExpression (par.Name));
paramsArray.Initializers.Add (new CodeVariableReferenceExpression (par.Name));
}
}
inv.Parameters.Add (enull);
string userStateName = paramsIds.AddUnique ("userState", null);
asyncMethod.Parameters.Add (new CodeParameterDeclarationExpression (typeof(object), userStateName));
CodeExpression userStateVar = new CodeVariableReferenceExpression (userStateName);
asyncMethod.Statements.Add (BuildInvokeAsync (messageName, paramsArray, delegateField, userStateVar));
CodeTypeDeclaration.Members.Add (am);
CodeTypeDeclaration.Members.Add (asyncMethod);
CodeTypeDeclaration.Members.Add (onCompleted);
asyncTypes.Add (delegateType);
}
CodeMemberProperty CreateArgsProperty (CodeTypeReference type, string name, int ind)
{
CodeMemberProperty prop = new CodeMemberProperty ();
prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
prop.HasGet = true;
prop.HasSet = false;
prop.Name = name;
prop.Type = type;
CodeThisReferenceExpression ethis = new CodeThisReferenceExpression();
CodeExpression thisResults = new CodeFieldReferenceExpression (ethis, "results");
prop.GetStatements.Add (new CodeMethodInvokeExpression (ethis, "RaiseExceptionIfNecessary"));
CodeArrayIndexerExpression arrValue = new CodeArrayIndexerExpression (thisResults, new CodePrimitiveExpression (ind));
CodeExpression retval = new CodeCastExpression (type, arrValue);
prop.GetStatements.Add (new CodeMethodReturnStatement (retval));
return prop;
}
internal virtual CodeExpression BuildInvokeAsync (string messageName, CodeArrayCreateExpression paramsArray, CodeExpression delegateField, CodeExpression userStateVar)
{
CodeThisReferenceExpression ethis = new CodeThisReferenceExpression();
CodeMethodInvokeExpression inv2 = new CodeMethodInvokeExpression (ethis, "InvokeAsync");
inv2.Parameters.Add (new CodePrimitiveExpression (messageName));
inv2.Parameters.Add (paramsArray);
inv2.Parameters.Add (delegateField);
inv2.Parameters.Add (userStateVar);
return inv2;
}
#endif
[MonoTODO]
public void AddExtensionWarningComments (CodeCommentStatementCollection comments, ServiceDescriptionFormatExtensionCollection extensions)
{
throw new NotImplementedException ();
}
protected abstract CodeTypeDeclaration BeginClass ();
protected virtual void BeginNamespace ()
{
}
protected virtual void EndClass ()
{
}
protected virtual void EndNamespace ()
{
}
protected abstract CodeMemberMethod GenerateMethod ();
protected abstract bool IsBindingSupported ();
protected abstract bool IsOperationFlowSupported (OperationFlow flow);
[MonoTODO]
public Exception OperationBindingSyntaxException (string text)
{
throw new NotImplementedException ();
}
[MonoTODO]
public Exception OperationSyntaxException (string text)
{
throw new NotImplementedException ();
}
public void UnsupportedBindingWarning (string text)
{
warnings |= ServiceDescriptionImportWarnings.UnsupportedBindingsIgnored;
AddGlobalComments ("WARNING: Could not generate proxy for binding " + binding.Name + ". " + text);
}
public void UnsupportedOperationBindingWarning (string text)
{
warnings |= ServiceDescriptionImportWarnings.UnsupportedOperationsIgnored;
AddGlobalComments ("WARNING: Could not generate operation " + OperationBinding.Name + ". " + text);
}
public void UnsupportedOperationWarning (string text)
{
warnings |= ServiceDescriptionImportWarnings.UnsupportedOperationsIgnored;
AddGlobalComments ("WARNING: Could not generate operation " + OperationBinding.Name + ". " + text);
}
void AddGlobalComments (string comments)
{
codeNamespace.Comments.Add (new CodeCommentStatement (comments, false));
}
void AddComments (CodeTypeMember member, string comments)
{
if (comments == null || comments == "") member.Comments.Add (new CodeCommentStatement ("<remarks/>", true));
else member.Comments.Add (new CodeCommentStatement ("<remarks>\n" + comments + "\n</remarks>", true));
}
void AddCodeType (CodeTypeDeclaration type, string comments)
{
AddComments (type, comments);
codeNamespace.Types.Add (type);
}
internal void AddCustomAttribute (CodeTypeMember ctm, CodeAttributeDeclaration att, bool addIfNoParams)
{
if (att.Arguments.Count == 0 && !addIfNoParams) return;
if (ctm.CustomAttributes == null) ctm.CustomAttributes = new CodeAttributeDeclarationCollection ();
ctm.CustomAttributes.Add (att);
}
internal void AddCustomAttribute (CodeTypeMember ctm, string name, params CodeAttributeArgument[] args)
{
if (ctm.CustomAttributes == null) ctm.CustomAttributes = new CodeAttributeDeclarationCollection ();
ctm.CustomAttributes.Add (new CodeAttributeDeclaration (name, args));
}
internal CodeAttributeArgument GetArg (string name, object value)
{
return new CodeAttributeArgument (name, new CodePrimitiveExpression(value));
}
internal CodeAttributeArgument GetEnumArg (string name, string enumType, string enumValue)
{
return new CodeAttributeArgument (name, new CodeFieldReferenceExpression (new CodeTypeReferenceExpression(enumType), enumValue));
}
internal CodeAttributeArgument GetArg (object value)
{
return new CodeAttributeArgument (new CodePrimitiveExpression(value));
}
internal CodeAttributeArgument GetTypeArg (string name, string typeName)
{
return new CodeAttributeArgument (name, new CodeTypeOfExpression(typeName));
}
#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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CompareGreaterThanOrEqualDouble()
{
var test = new SimpleBinaryOpTest__CompareGreaterThanOrEqualDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareGreaterThanOrEqualDouble
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Double);
private const int Op2ElementCount = VectorSize / sizeof(Double);
private const int RetElementCount = VectorSize / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private SimpleBinaryOpTest__DataTable<Double, Double, Double> _dataTable;
static SimpleBinaryOpTest__CompareGreaterThanOrEqualDouble()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__CompareGreaterThanOrEqualDouble()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Double, Double, Double>(_data1, _data2, new Double[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.CompareGreaterThanOrEqual(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.CompareGreaterThanOrEqual(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.CompareGreaterThanOrEqual(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareGreaterThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareGreaterThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareGreaterThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.CompareGreaterThanOrEqual(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse2.CompareGreaterThanOrEqual(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareGreaterThanOrEqual(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareGreaterThanOrEqual(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__CompareGreaterThanOrEqualDouble();
var result = Sse2.CompareGreaterThanOrEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.CompareGreaterThanOrEqual(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Double> left, Vector128<Double> right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
if (BitConverter.DoubleToInt64Bits(result[0]) != ((left[0] >= right[0]) ? -1 : 0))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != ((left[i] >= right[i]) ? -1 : 0))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.CompareGreaterThanOrEqual)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// *********************************
// Message from Original Author:
//
// 2008 Jose Menendez Poo
// Please give me credit if you use this code. It's all I ask.
// Contact me for more info: menendezpoo@gmail.com
// *********************************
//
// Original project from http://ribbon.codeplex.com/
// Continue to support and maintain by http://officeribbon.codeplex.com/
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Drawing;
namespace System.Windows.Forms
{
[Designer(typeof(RibbonComboBoxDesigner))]
public class RibbonComboBox
: RibbonTextBox, IContainsRibbonComponents, IDropDownRibbonItem
{
#region Fields
private RibbonItemCollection _dropDownItems;
private Rectangle _dropDownBounds;
private bool _dropDownSelected;
private bool _dropDownPressed;
private bool _dropDownVisible;
private bool _dropDownResizable;
private int _dropDownMaxHeight;
private bool _iconsBar;
private bool _DropDownVisible;
// Steve
private RibbonItem _selectedItem;
private Set<RibbonItem> _assignedHandlers = new Set<RibbonItem>();
#endregion
#region Events
/// <summary>
/// Raised when the DropDown is about to be displayed
/// </summary>
public event EventHandler DropDownShowing;
public event RibbonItemEventHandler DropDownItemClicked;
public delegate void RibbonItemEventHandler(object sender, RibbonItemEventArgs e);
#endregion
#region Ctor
public RibbonComboBox()
{
_dropDownItems = new RibbonItemCollection();
_dropDownVisible = true;
AllowTextEdit = true;
_iconsBar = true;
_dropDownMaxHeight = 0;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
RemoveHandlers();
}
base.Dispose(disposing);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the maximum height for the dropdown window. 0 = autosize. If the size is smaller than the contents then scrollbars will be shown.
/// </summary>
[DefaultValue(0)]
[Description("Gets or sets the maximum height for the dropdown window. 0 = Autosize. If the size is smaller than the contents then scrollbars will be shown.")]
public int DropDownMaxHeight
{
get { return _dropDownMaxHeight; }
set { _dropDownMaxHeight = value; }
}
/// <summary>
/// Gets or sets a value indicating if the DropDown portion of the combo box is currently shown.
/// </summary>
[DefaultValue(false)]
[Description("Indicates if the dropdown window is currently visible")]
public bool DropDownVisible
{
get { return _DropDownVisible; }
}
/// <summary>
/// Gets or sets a value indicating if the DropDown should be resizable
/// </summary>
[DefaultValue(false)]
[Description("Makes the DropDown resizable with a grip on the corner")]
public bool DropDownResizable
{
get { return _dropDownResizable; }
set { _dropDownResizable = value; }
}
/// <summary>
/// Overriden.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public override Rectangle TextBoxTextBounds
{
get
{
Rectangle r = base.TextBoxTextBounds;
r.Width -= DropDownButtonBounds.Width;
return r;
}
}
/// <summary>
/// Gets the collection of items to be displayed on the dropdown
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public RibbonItemCollection DropDownItems
{
get { return _dropDownItems; }
}
// Steve
/// <summary>
/// Gets the selected of item on the dropdown
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public RibbonItem SelectedItem
{
get
{
if (_selectedItem == null)
{
return null;
}
else
{
if (_dropDownItems.Contains(_selectedItem))
{
return _selectedItem;
}
else
{
_selectedItem = null;
return null;
}
}
}
//Steve
set
{
if (value.GetType().BaseType == typeof(RibbonItem))
{
if (_dropDownItems.Contains(value))
{
_selectedItem = value;
TextBoxText = _selectedItem.Text;
}
else
{
//_dropDownItems.Add(value);
_selectedItem = value;
TextBoxText = _selectedItem.Text;
}
}
}
}
// Kevin
/// <summary>
/// Gets or sets the value of selected item on the dropdown.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string SelectedValue
{
get
{
if (_selectedItem == null)
{
return null;
}
else
{
return _selectedItem.Value;
}
}
set
{
foreach (RibbonItem item in DropDownItems)
{
if (item.Value == value)
{
if (_selectedItem != item)
{
_selectedItem = item;
TextBoxText = _selectedItem.Text;
RibbonItemEventArgs arg = new RibbonItemEventArgs(item);
OnDropDownItemClicked(ref arg);
}
}
}
}
}
#endregion
#region Methods
/// <summary>
/// Raises the <see cref="DropDownShowing"/> event;
/// </summary>
/// <param name="e"></param>
public void OnDropDownShowing(EventArgs e)
{
if (DropDownShowing != null)
{
DropDownShowing(this, e);
}
}
/// <summary>
/// Gets or sets if the icons bar should be drawn
/// </summary>
[DefaultValue(true)]
public bool DrawIconsBar
{
get { return _iconsBar; }
set { _iconsBar = value; }
}
/// <summary>
/// Shows the DropDown
/// </summary>
public virtual void ShowDropDown()
{
if (!_DropDownVisible)
{
AssignHandlers();
OnDropDownShowing(EventArgs.Empty);
RibbonDropDown dd = new RibbonDropDown(this, DropDownItems, Owner);
dd.DropDownMaxHeight = _dropDownMaxHeight;
dd.ShowSizingGrip = DropDownResizable;
dd.DrawIconsBar = _iconsBar;
dd.Closed += new EventHandler(DropDown_Closed);
Point location = OnGetDropDownMenuLocation();
dd.Show(location);
_DropDownVisible = true;
}
}
private void DropDown_Closed(object sender, EventArgs e)
{
_DropDownVisible = false;
//Steve - when popup closed, un-highlight the dropdown arrow and redraw
_dropDownPressed = false;
//Kevin - Unselect it as well
_dropDownSelected = false;
RedrawItem();
}
private void AssignHandlers()
{
foreach (RibbonItem item in DropDownItems)
{
if (_assignedHandlers.Contains(item) == false)
{
item.Click += new EventHandler(DropDownItem_Click);
_assignedHandlers.Add(item);
}
}
}
private void RemoveHandlers()
{
foreach (RibbonItem item in _assignedHandlers)
{
item.Click -= DropDownItem_Click;
}
_assignedHandlers.Clear();
}
void DropDownItem_Click(object sender, EventArgs e)
{
// Steve
_selectedItem = (sender as RibbonItem);
TextBoxText = (sender as RibbonItem).Text;
//Kevin Carbis
RibbonItemEventArgs ev = new RibbonItemEventArgs(sender as RibbonItem);
OnDropDownItemClicked(ref ev);
}
#endregion
#region Overrides
protected override bool ClosesDropDownAt(Point p)
{
return false;
}
protected override void InitTextBox(TextBox t)
{
base.InitTextBox(t);
t.Width -= DropDownButtonBounds.Width;
}
public override void SetBounds(Rectangle bounds)
{
base.SetBounds(bounds);
_dropDownBounds = Rectangle.FromLTRB(
bounds.Right - 15,
bounds.Top,
bounds.Right + 1,
bounds.Bottom + 1);
}
public virtual void OnDropDownItemClicked(ref RibbonItemEventArgs e)
{
if (DropDownItemClicked != null)
{
DropDownItemClicked(this, e);
}
}
public override void OnMouseMove(MouseEventArgs e)
{
//bool _tmpAllowTextEdit = this.AllowTextEdit;
if (!Enabled) return;
//base.OnMouseMove(e);
//this.AllowTextEdit = _tmpAllowTextEdit;
bool mustRedraw = false;
if (DropDownButtonBounds.Contains(e.X, e.Y))
{
Owner.Cursor = Cursors.Default;
mustRedraw = !_dropDownSelected;
_dropDownSelected = true;
}
else if (TextBoxBounds.Contains(e.X, e.Y))
{
Owner.Cursor = AllowTextEdit ? Cursors.IBeam : Cursors.Default;
mustRedraw = _dropDownSelected;
_dropDownSelected = false;
}
else
{
Owner.Cursor = Cursors.Default;
}
if (mustRedraw)
{
RedrawItem();
}
}
public override void OnMouseDown(MouseEventArgs e)
{
if (!Enabled) return;
// Steve - if allowtextedit is false, allow the textbox to bring up the popup
if (DropDownButtonBounds.Contains(e.X, e.Y) || (TextBoxBounds.Contains(e.X, e.Y) != AllowTextEdit))
{
_dropDownPressed = true;
ShowDropDown();
}
else if (TextBoxBounds.Contains(e.X, e.Y) && AllowTextEdit)
{
StartEdit();
}
}
public override void OnMouseUp(MouseEventArgs e)
{
if (!Enabled) return;
base.OnMouseUp(e);
//Steve - pressed if set false when popup is closed
//_dropDownPressed = false;
}
public override void OnMouseLeave(MouseEventArgs e)
{
if (!Enabled) return;
base.OnMouseLeave(e);
_dropDownSelected = false;
}
/// <summary>
/// Gets the location where the dropdown menu will be shown
/// </summary>
/// <returns></returns>
internal virtual Point OnGetDropDownMenuLocation()
{
Point location = Point.Empty;
if (Canvas is RibbonDropDown)
{
location = Canvas.PointToScreen(new Point(TextBoxBounds.Left, Bounds.Bottom));
}
else
{
location = Owner.PointToScreen(new Point(TextBoxBounds.Left, Bounds.Bottom));
}
return location;
}
#endregion
#region IContainsRibbonComponents Members
public IEnumerable<Component> GetAllChildComponents()
{
return DropDownItems.ToArray();
}
#endregion
#region IDropDownRibbonItem Members
/// <summary>
/// Gets or sets the bounds of the DropDown button
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Rectangle DropDownButtonBounds
{
get { return _dropDownBounds; }
}
/// <summary>
/// Gets a value indicating if the DropDown is currently visible
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool DropDownButtonVisible
{
get { return _dropDownVisible; }
}
/// <summary>
/// Gets a value indicating if the DropDown button is currently selected
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool DropDownButtonSelected
{
get { return _dropDownSelected; }
}
/// <summary>
/// Gets a value indicating if the DropDown button is currently pressed
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool DropDownButtonPressed
{
get { return _dropDownPressed; }
}
internal override void SetOwner(Ribbon owner)
{
base.SetOwner(owner);
_dropDownItems.SetOwner(owner);
}
internal override void SetOwnerPanel(RibbonPanel ownerPanel)
{
base.SetOwnerPanel(ownerPanel);
_dropDownItems.SetOwnerPanel(ownerPanel);
}
internal override void SetOwnerTab(RibbonTab ownerTab)
{
base.SetOwnerTab(ownerTab);
_dropDownItems.SetOwnerTab(OwnerTab);
}
#endregion
}
}
| |
// Copyright 2009 Auxilium B.V. - http://www.auxilium.nl/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace JelloScrum.Web.Controllers
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using Castle.ActiveRecord;
using Castle.MonoRail.ActiveRecordSupport;
using Castle.MonoRail.Framework;
using Container;
using Helpers;
using Model;
using Model.Entities;
using Model.Enumerations;
using Model.Helpers;
using Model.Services;
using NHibernate.Criterion;
using QueryObjects;
/// <summary>
/// Parameters benodigd voor een correcte werking van de sprintcontroller
/// </summary>
public interface ISprintControllerParameters
{
/// <summary>
/// ProjectId uit de sessie.
/// </summary>
int? SprintControllerParametersProjectId { get; set; }
}
/// <summary>
/// De controller voor de sprint
/// </summary>
[Helper(typeof (BurnDown2Helper))]
[Layout("sprint")]
public class SprintController : SecureController
{
private readonly IExcelExportService excelExportService = IoC.Resolve<IExcelExportService>();
/// <summary>
/// Toont een lijst met taken van de ingelogde gebruiker
/// </summary>
public void MijnTaken()
{
User gb = CurrentUser;
SprintUser sg = gb.GetActiveSprintUser();
//mijn taken
if (sg != null)
PropertyBag.Add("mijnTaken", sg.GetTakenTasks());
}
/// <summary>
/// Toont een lijst met taken van andere gebruikers in deze sprint.
/// </summary>
public void TakenVanAnderen()
{
User gb = CurrentUser;
IList takenVanAnderen = GeefTakenVanAnderen(gb);
if (takenVanAnderen.Count > 0)
PropertyBag.Add("takenVanAnderen", takenVanAnderen);
}
/// <summary>
/// Toont een lijst met onopgepakte taken
/// </summary>
public void OnOpgepakteTaken()
{
User gb = CurrentUser;
IList onopgepakteTaken = GeefOnopgepakteTaken(gb.ActiveSprint);
if (onopgepakteTaken.Count > 0)
PropertyBag.Add("onopgepakteTaken", onopgepakteTaken);
}
/// <summary>
/// Toont een lijst met door de gebruiker afgesloten taken.
/// </summary>
public void MijnAfgeslotenTaken()
{
User gb = CurrentUser;
SprintUser sg = gb.GetActiveSprintUser();
//mijn taken
if (sg != null)
PropertyBag.Add("mijnTaken", sg.GetClosedTasks());
}
/// <summary>
/// Het dashboard van deze sprint.
/// Hier kan de actieve gebruiker de volgende zaken zien:
/// - eigen taken
/// - taken van anderen
/// - nog niet opgepakte taken
/// - eigen afgesloten taken
/// </summary>
public void Dashboard()
{
RedirectToAction("mijntaken");
}
/// <summary>
///
/// </summary>
/// <param name="project"></param>
public void Overzicht([ARFetch("projectId")] Project project)
{
if (project == null)
{
RedirectToAction("Index");
}
PropertyBag.Add("project", project);
CancelLayout();
if (project == null)
{
RedirectToAction("Index");
}
PropertyBag.Add("project", project);
CancelLayout();
}
/// <summary>
/// Nieuwe sprint toevoegen
/// </summary>
/// <param name="project"></param>
[Layout("default")]
public void Nieuw([ARFetch("projectId")] Project project)
{
Sprint sprint = new Sprint(project);
PropertyBag.Add("sprint", sprint);
PropertyBag.Add("project", project);
PropertyBag.Add("availableUsers", GebruikerRepository.FindAll());
Titel = "<a href='/project/project.rails?projectId=" + project.Id + "'>" + project.Name + "</a> > Sprint toevoegen";
RenderView("bewerk");
}
/// <summary>
/// Bewerk een sprint
/// </summary>
/// <param name="sprint"></param>
/// <param name="project"></param>
[Layout("default")]
public void Bewerk([ARFetch("sprintId")] Sprint sprint)
{
Project project = sprint.Project;
PropertyBag.Add("sprint", sprint);
PropertyBag.Add("availableUsers", GebruikerRepository.FindAll());
PropertyBag.Add("project", project);
Titel = "<a href='/project/project.rails?projectId=" + project.Id + "'>" + project.Name + "</a> > <a href='/sprint/sprint.rails?sprintId=" + sprint.Id + "'>" + sprint.Goal + "</a> > Sprint bewerken";
}
/// <summary>
/// Bindt en sla de sprint op met de bijbehorende actieve gebruikers
/// </summary>
/// <param name="sprint"></param>
/// <param name="sprintRolGebruikerHelpers"></param>
/// <param name="project"></param>
public void Opslaan([ARDataBind("sprint", AutoLoad = AutoLoadBehavior.NewInstanceIfInvalidKey)] Sprint sprint,
string BeschikbareUren,
[ARDataBind("rol", AutoLoadBehavior.NewRootInstanceIfInvalidKey)] SprintRoleUserHelper[]
sprintRolGebruikerHelpers,
[ARFetch("projectId")] Project project)
{
sprint.AvailableTime = TimeSpanHelper.Parse(BeschikbareUren);
project.AddSprint(sprint);
foreach (SprintRoleUserHelper sprintRolGebruikerHelper in sprintRolGebruikerHelpers)
{
sprintRolGebruikerHelper.Process(sprint);
}
SprintRepository.Save(sprint);
NameValueCollection args = new NameValueCollection();
args.Add("projectId", project.Id.ToString());
Redirect("Project", "project", args);
}
/// <summary>
/// Maak een lijst van stories en taken die in de sprint nog gedaan moeten worden
/// </summary>
/// <param name="item">Sprint.</param>
public void SprintStories([ARFetch("id")] Sprint item)
{
Dictionary<Priority, IList<SprintStory>> sprintStories = new Dictionary<Priority, IList<SprintStory>>();
sprintStories.Add(Priority.Must,
new List<SprintStory>(item.GetAllOpenSprintStories(Priority.Must)));
sprintStories.Add(Priority.Should,
new List<SprintStory>(item.GetAllOpenSprintStories(Priority.Should)));
sprintStories.Add(Priority.Could,
new List<SprintStory>(item.GetAllOpenSprintStories(Priority.Could)));
sprintStories.Add(Priority.Would,
new List<SprintStory>(item.GetAllOpenSprintStories(Priority.Would)));
PropertyBag.Add("sprintStories", sprintStories);
CancelLayout();
}
/// <summary>
/// Maak een lijst van stories en taken die in de sprint gemarkeerd zijn als afgerond
/// </summary>
/// <param name="item">The item.</param>
public void SprintStoriesAfgerond([ARFetch("id")] Sprint item)
{
Dictionary<Priority, IList<SprintStory>> sprintStories = new Dictionary<Priority, IList<SprintStory>>();
sprintStories.Add(Priority.Must,
new List<SprintStory>(item.GetSprintStoriesWithClosedTasks(Priority.Must)));
sprintStories.Add(Priority.Should,
new List<SprintStory>(item.GetSprintStoriesWithClosedTasks(Priority.Should)));
sprintStories.Add(Priority.Could,
new List<SprintStory>(item.GetSprintStoriesWithClosedTasks(Priority.Could)));
sprintStories.Add(Priority.Would,
new List<SprintStory>(item.GetSprintStoriesWithClosedTasks(Priority.Would)));
PropertyBag.Add("sprintStories", sprintStories);
CancelLayout();
}
/// <summary>
/// De startpagina van iedere sprint
/// </summary>
/// <param name="sprint"></param>
public void Sprint([ARFetch("sprintId")] Sprint sprint)
{
Titel = "<a href='/project/project.rails?projectId=" + sprint.Project.Id + "'>" + sprint.Project.Name + "</a> > " + sprint.Goal;
PropertyBag.Add("sprint", sprint);
}
/// <summary>
/// Sprint Health
/// </summary>
/// <param name="sprint"></param>
public void Health([ARFetch("sprintId")] Sprint sprint)
{
PropertyBag.Add("sprint", sprint);
}
/// <summary>
///
/// </summary>
public void Planning([ARFetch("sprintId")] Sprint sprint)
{
PropertyBag.Add("sprint", sprint);
}
public void KoppelTaskAanSprintGebruiker([ARFetch("sprintGebruiker")] SprintUser sprintGebruiker, [ARFetch("task")] Task task)
{
sprintGebruiker.TakeTask(task);
SprintGebruikerRepository.Save(sprintGebruiker);
PropertyBag.Add("sprintGebruiker", sprintGebruiker);
RenderView("planning_developer");
CancelLayout();
}
/// <summary>
/// Sprint informatie
/// </summary>
/// <param name="item"></param>
public void SprintInformatie([ARFetch("id")] Sprint item)
{
PropertyBag.Add("item", item);
CancelLayout();
}
/// <summary>
/// Toont het scherm waarop de sprint ingericht kan worden met stories uit het productbacklog
/// </summary>
/// <param name="sprint">The sprint.</param>
public void SprintBacklog([ARFetch("sprintId")] Sprint sprint)
{
PropertyBag.Add("sprint", sprint);
Titel = "<a href='/project/project.rails?projectId=" + sprint.Project.Id + "'>" + sprint.Project.Name + "</a> > <a href='/sprint/sprint.rails?sprintId=" + sprint.Id + "'>" + sprint.Goal + "</a> > Sprintbacklog";
}
/// <summary>
/// Exporteer sprintbacklog naar excel
/// </summary>
/// <param name="sprint">sprint</param>
public void ExportSprintBackLog([ARFetch("sprintId")] Sprint sprint)
{
string fileName = this.excelExportService.ExportSprintBacklog(sprint);
Response.ContentType = "application/ms-excel";
Response.AppendHeader("content-disposition", "attachment; filename=\"" + fileName + "\"");
Response.WriteFile(ConfigurationManager.AppSettings["exportLocation"] + fileName);
CancelView();
}
/// <summary>
/// Koppelt de story aan een sprint.en geeft vervolgens de korte sprintinfo terug aan de sprintplanning
/// </summary>
/// <param name="sprint">The sprint.</param>
/// <param name="story">The story.</param>
public void KoppelStoryAanSprint([ARFetch("sprintId")] Sprint sprint, [ARFetch("storyId")] Story story)
{
SprintStory sprintStory = new SprintStory(sprint, story, story.Estimation);
sprintStory.SprintBacklogPriority = story.ProductBacklogPriority;
SprintStoryRepository.Save(sprintStory);
PropertyBag.Add("gekozenSprint", sprint);
PropertyBag.Add("story", story);
RenderView("sprintlogitem", true);
}
/// <summary>
/// Verwijder de story uit de sprint
/// </summary>
/// <param name="sprint"></param>
/// <param name="story"></param>
public void OntkoppelStoryVanSprint([ARFetch("sprintId")] Sprint sprint, [ARFetch("storyId")] Story story)
{
sprint.RemoveStory(story);
SprintRepository.Save(sprint);
PropertyBag.Add("gekozenSprint", sprint);
PropertyBag.Add("story", story);
RenderView("productbacklogitem", true);
}
/// <summary>
/// Geeft de resterende tijd weer die er beschikbaar is in de sprint
/// </summary>
/// <param name="sprint"></param>
public void sprintPlanningSprintTijd([ARFetch("sprintId")] Sprint sprint)
{
PropertyBag.Add("gekozenSprint", sprint);
CancelLayout();
}
/// <summary>
/// Koppelt de story aan een sprint.
/// </summary>
/// <param name="sprint">The sprint.</param>
/// <param name="story">The story.</param>
/// <param name="prioriteit">The prioriteit.</param>
public void KoppelStoryAanSprint([ARFetch("sprintId")] Sprint sprint, [ARFetch("storyId")] Story story,
Priority prioriteit)
{
SprintStory sprintStory = new SprintStory(sprint, story, story.Estimation);
sprintStory.SprintBacklogPriority = prioriteit;
SprintStoryRepository.Save(sprintStory);
NameValueCollection args = new NameValueCollection();
args.Add("sprintId", sprint.Id.ToString());
args.Add("prioriteit", prioriteit.ToString());
RedirectToAction("RenderIngeplandeStorieList", args);
}
/// <summary>
/// Maakt een lijst van sprintstories van een prioriteit van een sprint
/// </summary>
/// <param name="sprint">The sprint.</param>
/// <param name="prioriteit">The prioriteit.</param>
public void RenderIngeplandeStorieList([ARFetch("sprintId")] Sprint sprint, Priority prioriteit)
{
SprintStoriesQuery ingeplandeStories = new SprintStoriesQuery();
ingeplandeStories.Sprint = sprint;
IList list =
ingeplandeStories.GetQuery(ActiveRecordMediator.GetSessionFactoryHolder().CreateSession(typeof(ModelBase))).Add(
Restrictions.Eq("SprintBacklogPriority", prioriteit)).List();
PropertyBag.Add("sprintStories", list);
CancelLayout();
}
/// <summary>
/// Toont een knop waarmee een sprint kan worden afgesloten.
/// </summary>
public void Sluit([ARFetch("sprintId")] Sprint sprint)
{
PropertyBag.Add("sprint", sprint);
}
/// <summary>
/// Sluit de gegeven sprint af.
/// </summary>
public void SprintAfsluiten([ARFetch("sprintId")] Sprint sprint)
{
//todo: security!
IList<Task> taken = sprint.Close();
SprintRepository.Save(sprint);
//Het saven van een sprint spacecadet niet door naar de taken. Die moeten we dus apart saven.
foreach (Task task in taken)
{
TaskRepository.Save(task);
}
NameValueCollection args = new NameValueCollection();
args.Add("projectId", sprint.Project.Id.ToString());
Redirect("project", "overzicht", args);
}
/// <summary>
/// inplannen van de sprint, gekozen vanuit het project.
/// Er is geen specifieke sprint gekozen.
///
/// We moeten dus achterhalen in welke sprint we gaan werken.
/// </summary>
/// <param name="project"></param>
public void SprintPlanning([ARFetch("projectId")] Project project)
{
Titel = "<a href='/project/project.rails?projectId=" + project.Id + "'>" + project.Name + "</a> > Sprintplanning";
IList<Sprint> sprints = project.GetAllOpenSprints();
PropertyBag.Add("sprints", sprints);
PropertyBag.Add("project", project);
/** We moeten altijd zorgen dat zowel de project stories als de sprint stories er zijn **/
// Hier dus nog de gekozen sprint meesturen
if (sprints.Count > 0)
{
PropertyBag.Add("gekozenSprint", sprints[0]);
}
}
/// <summary>
/// inplannen van de sprint
/// </summary>
/// <param name="sprint"></param>
public void SprintPlanning([ARFetch("sprintId")] Sprint sprint)
{
Project project = sprint.Project;
Titel = "<a href='/project/project.rails?projectId=" + project.Id + "'>" + project.Name + "</a> > <a href='/sprint/sprint.rails?sprintId=" + sprint.Id + "'>" + sprint.Goal + "</a> > Sprintplanning";
IList<Sprint> sprints = project.GetAllOpenSprints();
PropertyBag.Add("sprints", sprints);
PropertyBag.Add("sprint", sprint);
PropertyBag.Add("project", project);
/** We moeten altijd zorgen dat zowel de project stories als de sprint stories er zijn **/
// Hier dus nog de gekozen sprint meesturen
if (sprints.Count > 0)
{
PropertyBag.Add("gekozenSprint", sprint);
}
}
/// <summary>
/// Iets zowel met project en sprint
/// Geen sprint dan proberen af tehandelen, door eerste sprint de kiezen.
/// TODO: MARIJN
/// </summary>
public void Stories()
{
// Dit moet dus zowel voor een project de stories geven als mede voor de sprint
CancelLayout();
}
public void Stories([ARFetch("sprintId")] Sprint sprint)
{
// Dit moet dus zowel voor een project de stories geven als mede voor de sprint
PropertyBag.Add("stories", sprint.GetAllStories());
CancelLayout();
}
public void Stories([ARFetch("projectId")] Project project)
{
// Dit moet dus zowel voor een project de stories geven als mede voor de sprint
PropertyBag.Add("stories", project.GetAllPlannableStories());
CancelLayout();
}
/// <summary>
/// Geeft een korte informatie beschrijving van de sprint
/// </summary>
public void ShortSprintInfo()
{
CancelLayout();
}
/// <summary>
/// Geeft een korte informatie beschrijving van de sprint
/// </summary>
public void ShortSprintInfo([ARFetch("sprintId")] Sprint sprint)
{
PropertyBag.Add("gekozenSprint", sprint);
CancelLayout();
}
/// <summary>
/// Geeft een korte informatie beschrijving van de sprint
/// </summary>
public void ShortSprintInfo([ARFetch("projectId")] Project project)
{
PropertyBag.Add("project", project);
RenderView("shortprojectinfo", true);
}
/// <summary>
/// Invullen uren per taak
/// </summary>
public void Uren()
{
}
/// <summary>
///
/// </summary>
public void Burndown([ARFetch("sprintId")] Sprint sprint)
{
PropertyBag.Add("sprintstories", sprint.SprintStories);
PropertyBag.Add("sprint", sprint);
Titel = "<a href='/project/project.rails?projectId=" + sprint.Project.Id + "'>" + sprint.Project.Name + "</a> > <a href='/sprint/sprint.rails?sprintId=" + sprint.Id + "'>" + sprint.Goal + "</a> > Burndown";
}
/// <summary>
///
/// </summary>
/// <param name="sprint"></param>
public void ActieveSprintZetten([ARFetch("sprintId")] Sprint sprint)
{
User gb = CurrentUser;
gb.ActiveSprint = sprint;
try
{
GebruikerRepository.Save(gb);
AddPositiveMessageToFlashBag(sprint.Goal + " is nu je actieve sprint.");
}
catch (Exception e)
{
AddErrorMessageToFlashBag(e.Message);
}
RedirectToReferrer();
}
/// <summary>
/// Taken weergeven voor sprint, wat niet de actieve sprint hoeft te zijn.
/// </summary>
/// <param name="sprint"></param>
public void Taken([ARFetch("sprintId")] Sprint sprint)
{
PropertyBag.Add("sprint", sprint);
Titel = "<a href='/project/project.rails?projectId=" + sprint.Project.Id + "'>" + sprint.Project.Name + "</a> > <a href='/sprint/sprint.rails?sprintId=" + sprint.Id + "'>" + sprint.Goal + "</a> > Taken";
RenderText("Deze pagina wijkt af van het normale dashboard, dit moet dus even gefixed worden.");
}
/// <summary>
/// Sprint voortgang
/// </summary>
public void Voortgang([ARFetch("sprintId")] Sprint sprint)
{
DateTime startdatum = sprint.StartDate;
DateTime einddatum = sprint.EndDate;
DateTime temp = startdatum;
IList<DateTime> werkdagen = new List<DateTime>();
while (temp <= einddatum)
{
if (temp.DayOfWeek != DayOfWeek.Saturday && temp.DayOfWeek != DayOfWeek.Sunday)
{
werkdagen.Add(temp);
}
temp = temp.AddDays(1);
}
PropertyBag.Add("sprint", sprint);
PropertyBag.Add("sprintstories", sprint.SprintStories);
PropertyBag.Add("werkdagen", werkdagen);
Titel = "<a href='/project/project.rails?projectId=" + sprint.Project.Id + "'>" + sprint.Project.Name + "</a> > <a href='/sprint/sprint.rails?sprintId=" + sprint.Id + "'>" + sprint.Goal + "</a> > Voortgang";
}
#region Uren registeren
/// <summary>
/// Urenboek scherm
/// </summary>
public void UrenRegistreren([ARFetch("sprintId")] Sprint sprint, DateTime maandag)
{
SprintUser sprintGebruiker = sprint.GetSprintUserFor(CurrentUser);
Titel = "<a href='/project/project.rails?projectId=" + sprint.Project.Id + "'>" + sprint.Project.Name + "</a> > <a href='/sprint/sprint.rails?sprintId=" + sprint.Id + "'>" + sprint.Goal + "</a> > Uren registreren";
PropertyBag.Add("maandag", maandag);
PropertyBag.Add("sprint", sprint);
PropertyBag.Add("sprintGebruiker", sprintGebruiker);
}
/// <summary>
/// Uren boeken op taken van actieve sprint
/// </summary>
public void UrenBoeken([ARDataBind("urenregistratie", AutoLoadBehavior.OnlyNested)]UrenRegistratieHelper[] urenRegistraties, [ARFetch("sprintId")] Sprint sprint, DateTime maandag)
{
try
{
foreach (UrenRegistratieHelper helper in urenRegistraties)
{
helper.MaakUrenRegistratie();
TaskRepository.Save(helper.Task);
}
}
catch
{
AddErrorMessageToFlashBag("Het opslaan van de urenregistraties is niet gelukt.");
}
NameValueCollection args = new NameValueCollection();
args.Add("sprintId", sprint.Id.ToString());
args.Add("maandag", maandag.ToString("dd-MM-yyyy"));
RedirectToAction("urenregistreren", args);
}
#endregion
#region methods
/// <summary>
/// Geeft de onopgepakte taken in de gegeven sprint.
/// </summary>
/// <param name="sprint">De sprint.</param>
/// <returns>De onopgepakte taken</returns>
private static IList GeefOnopgepakteTaken(Sprint sprint)
{
OpenTasksQuery nietOpgepakteTakenQuery = new OpenTasksQuery();
nietOpgepakteTakenQuery.Sprint = sprint;
return nietOpgepakteTakenQuery.GetQuery(ActiveRecordMediator.GetSessionFactoryHolder().CreateSession(typeof(ModelBase))).List();
}
/// <summary>
/// Geeft de opgepakte taken van anderen dan de gegeven gebruiker.
/// </summary>
/// <param name="gebruiker">De gebruiker.</param>
/// <returns>De taken van anderen.</returns>
private static IList GeefTakenVanAnderen(User gebruiker)
{
TakenTasksQuery opgepakteTakenQuery = new TakenTasksQuery();
opgepakteTakenQuery.Sprint = gebruiker.ActiveSprint;
opgepakteTakenQuery.ExceptForSprintUser = gebruiker.GetActiveSprintUser();
return opgepakteTakenQuery.GetQuery(ActiveRecordMediator.GetSessionFactoryHolder().CreateSession(typeof(ModelBase))).List();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using FoxTrader.UI.Font;
namespace FoxTrader.UI.Control
{
/// <summary>Multiline label with text chunks having different color/font</summary>
internal class RichLabel : GameControl
{
private readonly string[] m_newline;
private readonly List<TextBlock> m_textBlocks;
private bool m_needsRebuild;
/// <summary>Initializes a new instance of the <see cref="RichLabel" /> class</summary>
/// <param name="c_parentControl">Parent control</param>
public RichLabel(GameControl c_parentControl) : base(c_parentControl)
{
m_newline = new[] { Environment.NewLine };
m_textBlocks = new List<TextBlock>();
}
/// <summary>Adds a line break to the control</summary>
public void AddLineBreak()
{
var a_block = new TextBlock { m_type = BlockType.NewLine };
m_textBlocks.Add(a_block);
}
/// <summary>Adds text to the control</summary>
/// <param name="c_text">Text to add</param>
/// <param name="c_color">Text color</param>
/// <param name="c_font">Font to use</param>
public void AddText(string c_text, Color c_color, GameFont c_font = null)
{
if (string.IsNullOrEmpty(c_text))
{
return;
}
var a_lines = c_text.Split(m_newline, StringSplitOptions.None);
for (var a_i = 0; a_i < a_lines.Length; a_i++)
{
if (a_i > 0)
{
AddLineBreak();
}
var a_block = new TextBlock { m_type = BlockType.Text, m_text = a_lines[a_i], m_color = c_color, m_font = c_font };
m_textBlocks.Add(a_block);
m_needsRebuild = true;
Invalidate();
}
}
/// <summary>Resizes the control to fit its children</summary>
/// <param name="c_width">Determines whether to change control's width</param>
/// <param name="c_height">Determines whether to change control's height</param>
/// <returns>True if bounds changed</returns>
public override bool SizeToChildren(bool c_width = true, bool c_height = true)
{
Rebuild();
return base.SizeToChildren(c_width, c_height);
}
protected void SplitLabel(string c_text, GameFont c_font, TextBlock c_block, ref int c_x, ref int c_y, ref int c_lineHeight)
{
var a_spaced = Util.SplitAndKeep(c_text, " ");
if (a_spaced.Length == 0)
{
return;
}
var a_spaceLeft = Width - c_x;
string a_leftOver;
// Does the whole word fit in?
var a_stringSize = Skin.Renderer.MeasureText(c_font, c_text);
if (a_spaceLeft > a_stringSize.Width)
{
CreateLabel(c_text, c_block, ref c_x, ref c_y, ref c_lineHeight, true);
return;
}
// If the first word is bigger than the line, just give up.
var a_wordSize = Skin.Renderer.MeasureText(c_font, a_spaced[0]);
if (a_wordSize.Width >= a_spaceLeft)
{
CreateLabel(a_spaced[0], c_block, ref c_x, ref c_y, ref c_lineHeight, true);
if (a_spaced[0].Length >= c_text.Length)
{
return;
}
a_leftOver = c_text.Substring(a_spaced[0].Length + 1);
SplitLabel(a_leftOver, c_font, c_block, ref c_x, ref c_y, ref c_lineHeight);
return;
}
var a_newString = string.Empty;
for (var a_i = 0; a_i < a_spaced.Length; a_i++)
{
a_wordSize = Skin.Renderer.MeasureText(c_font, a_newString + a_spaced[a_i]);
if (a_wordSize.Width > a_spaceLeft)
{
CreateLabel(a_newString, c_block, ref c_x, ref c_y, ref c_lineHeight, true);
c_x = 0;
c_y += c_lineHeight;
break;
}
a_newString += a_spaced[a_i];
}
var a_newstrLen = a_newString.Length;
if (a_newstrLen < c_text.Length)
{
a_leftOver = c_text.Substring(a_newstrLen + 1);
SplitLabel(a_leftOver, c_font, c_block, ref c_x, ref c_y, ref c_lineHeight);
}
}
protected void CreateLabel(string c_text, TextBlock c_block, ref int c_x, ref int c_y, ref int c_lineHeight, bool c_noSplit)
{
// Use default font or is one set?
var a_font = Skin.DefaultFont;
if (c_block.m_font != null)
{
a_font = c_block.m_font;
}
// This string is too long for us, split it up.
var a_p = Skin.Renderer.MeasureText(a_font, c_text);
if (c_lineHeight == -1)
{
c_lineHeight = a_p.Height;
}
if (!c_noSplit)
{
if (c_x + a_p.Width > Width)
{
SplitLabel(c_text, a_font, c_block, ref c_x, ref c_y, ref c_lineHeight);
return;
}
}
// Wrap
if (c_x + a_p.Width >= Width)
{
CreateNewline(ref c_x, ref c_y, c_lineHeight);
}
var a_label = new Label(this);
a_label.SetText(c_x == 0 ? c_text.TrimStart(' ') : c_text);
a_label.TextColor = c_block.m_color;
a_label.Font = a_font;
a_label.SizeToContents();
a_label.SetPosition(c_x, c_y);
//lineheight = (lineheight + pLabel.Height()) / 2;
c_x += a_label.Width;
if (c_x >= Width)
{
CreateNewline(ref c_x, ref c_y, c_lineHeight);
}
}
protected void CreateNewline(ref int c_x, ref int c_y, int c_lineHeight)
{
c_x = 0;
c_y += c_lineHeight;
}
protected void Rebuild()
{
DeleteAllChildren();
var a_x = 0;
var a_y = 0;
var a_lineHeight = -1;
foreach (var a_block in m_textBlocks)
{
if (a_block.m_type == BlockType.NewLine)
{
CreateNewline(ref a_x, ref a_y, a_lineHeight);
continue;
}
if (a_block.m_type == BlockType.Text)
{
CreateLabel(a_block.m_text, a_block, ref a_x, ref a_y, ref a_lineHeight, false);
}
}
m_needsRebuild = false;
}
/// <summary>Handler invoked when control's bounds change</summary>
/// <param name="c_oldBounds">Old bounds</param>
protected override void OnBoundsChanged(Rectangle c_oldBounds)
{
base.OnBoundsChanged(c_oldBounds);
Rebuild();
}
/// <summary>Lays out the control's interior according to alignment, padding, dock etc</summary>
/// <param name="c_skin">Skin to use</param>
protected override void OnLayout(Skin c_skin)
{
base.OnLayout(c_skin);
if (m_needsRebuild)
{
Rebuild();
}
// align bottoms. this is still not ideal, need to take font metrics into account.
GameControl a_prev = null;
foreach (var a_child in Children)
{
if (a_prev != null && a_child.Y == a_prev.Y)
{
Align.PlaceRightBottom(a_child, a_prev);
}
a_prev = a_child;
}
}
protected struct TextBlock
{
public BlockType m_type;
public string m_text;
public Color m_color;
public GameFont m_font;
}
protected enum BlockType
{
Text,
NewLine
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.DataFactories;
using Microsoft.Azure.Management.DataFactories.Models;
namespace Microsoft.Azure.Management.DataFactories
{
public static partial class DataSliceRunOperationsExtensions
{
/// <summary>
/// Gets a Data Slice Run instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.IDataSliceRunOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='runId'>
/// Required. A unique Data Slice Run Id.
/// </param>
/// <returns>
/// The get Data Slice Run operation response.
/// </returns>
public static DataSliceRunGetResponse Get(this IDataSliceRunOperations operations, string resourceGroupName, string dataFactoryName, string runId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDataSliceRunOperations)s).GetAsync(resourceGroupName, dataFactoryName, runId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a Data Slice Run instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.IDataSliceRunOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='runId'>
/// Required. A unique Data Slice Run Id.
/// </param>
/// <returns>
/// The get Data Slice Run operation response.
/// </returns>
public static Task<DataSliceRunGetResponse> GetAsync(this IDataSliceRunOperations operations, string resourceGroupName, string dataFactoryName, string runId)
{
return operations.GetAsync(resourceGroupName, dataFactoryName, runId, CancellationToken.None);
}
/// <summary>
/// Gets logs for a data slice run
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.IDataSliceRunOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='dataSliceRunId'>
/// Required. A unique data slice run instance id.
/// </param>
/// <returns>
/// The data slice run get logs operation response.
/// </returns>
public static DataSliceRunGetLogsResponse GetLogs(this IDataSliceRunOperations operations, string resourceGroupName, string dataFactoryName, string dataSliceRunId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDataSliceRunOperations)s).GetLogsAsync(resourceGroupName, dataFactoryName, dataSliceRunId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets logs for a data slice run
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.IDataSliceRunOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='dataSliceRunId'>
/// Required. A unique data slice run instance id.
/// </param>
/// <returns>
/// The data slice run get logs operation response.
/// </returns>
public static Task<DataSliceRunGetLogsResponse> GetLogsAsync(this IDataSliceRunOperations operations, string resourceGroupName, string dataFactoryName, string dataSliceRunId)
{
return operations.GetLogsAsync(resourceGroupName, dataFactoryName, dataSliceRunId, CancellationToken.None);
}
/// <summary>
/// Gets the first page of data slice run instances with the link to
/// the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.IDataSliceRunOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='tableName'>
/// Required. A unique table instance name.
/// </param>
/// <param name='dataSliceStartTime'>
/// Required. The start time of the data slice queried in round-trip
/// ISO 8601 format.
/// </param>
/// <returns>
/// The List data slice runs operation response.
/// </returns>
public static DataSliceRunListResponse List(this IDataSliceRunOperations operations, string resourceGroupName, string dataFactoryName, string tableName, string dataSliceStartTime)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDataSliceRunOperations)s).ListAsync(resourceGroupName, dataFactoryName, tableName, dataSliceStartTime);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the first page of data slice run instances with the link to
/// the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.IDataSliceRunOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='tableName'>
/// Required. A unique table instance name.
/// </param>
/// <param name='dataSliceStartTime'>
/// Required. The start time of the data slice queried in round-trip
/// ISO 8601 format.
/// </param>
/// <returns>
/// The List data slice runs operation response.
/// </returns>
public static Task<DataSliceRunListResponse> ListAsync(this IDataSliceRunOperations operations, string resourceGroupName, string dataFactoryName, string tableName, string dataSliceStartTime)
{
return operations.ListAsync(resourceGroupName, dataFactoryName, tableName, dataSliceStartTime, CancellationToken.None);
}
/// <summary>
/// Gets the next page of run instances with the link to the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.IDataSliceRunOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The url to the next data slice runs page.
/// </param>
/// <returns>
/// The List data slice runs operation response.
/// </returns>
public static DataSliceRunListResponse ListNext(this IDataSliceRunOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDataSliceRunOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the next page of run instances with the link to the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.IDataSliceRunOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The url to the next data slice runs page.
/// </param>
/// <returns>
/// The List data slice runs operation response.
/// </returns>
public static Task<DataSliceRunListResponse> ListNextAsync(this IDataSliceRunOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="TransformationUtility.cs" company="Google">
//
// Copyright 2018 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
namespace GoogleARCore.Examples.ObjectManipulationInternal
{
using GoogleARCore;
using UnityEngine;
/// <summary>
/// Provides helper functions for common functionality for transforming objects in AR.
/// </summary>
public static class TransformationUtility
{
/// <summary>
/// Slight offset of the down ray used in GetBestPlacementPosition to ensure that the
/// current groundingPlane is included in the hit results.
/// </summary>
private const float k_DownRayOffset = 0.01f;
/// <summary>
/// Max amount (inches) to offset the screen touch in GetBestPlacementPosition.
/// The actual amount if dependent on the angle of the camera relative.
/// The further downward the camera is angled, the more the screen touch is offset.
/// </summary>
private const float k_MaxScreenTouchOffset = 0.4f;
/// <summary>
/// In GetBestPlacementPosition, when the camera is closer than this value to the object,
/// reduce how much the object hovers.
/// </summary>
private const float k_HoverDistanceThreshold = 1.0f;
/// <summary>
/// Translation mode.
/// </summary>
public enum TranslationMode
{
Horizontal,
Vertical,
Any,
}
/// <summary>
/// Calculates the best position to place an object in AR based on screen position.
/// Could be used for tapping a location on the screen, dragging an object, or using a fixed
/// cursor in the center of the screen for placing and moving objects.
///
/// Objects are placed along the x/z of the grounding plane. When placed on an AR plane
/// below the grounding plane, the object will drop straight down onto it in world space.
/// This prevents the object from being pushed deeper into the scene when moving from a
/// higher plane to a lower plane. When moving from a lower plane to a higher plane, this
/// function returns a new groundingPlane to replace the old one.
/// </summary>
/// <returns>The best placement position.</returns>
/// <param name="currentAnchorPosition">Position of the parent anchor, i.e., where the
/// object is before translation starts.</param>
/// <param name="screenPos">Location on the screen in pixels to place the object at.</param>
/// <param name="groundingPlaneHeight">The starting height of the plane that the object is
/// being placed along.</param>
/// <param name="hoverOffset">How much should the object hover above the groundingPlane
/// before it has been placed.</param>
/// <param name="maxTranslationDistance">The maximum distance that the object can be
/// translated.</param>
/// <param name="translationMode">The translation mode, indicating the plane types allowed.
/// </param>
public static Placement GetBestPlacementPosition(
Vector3 currentAnchorPosition,
Vector2 screenPos,
float groundingPlaneHeight,
float hoverOffset,
float maxTranslationDistance,
TranslationMode translationMode)
{
Placement result = new Placement();
result.UpdatedGroundingPlaneHeight = groundingPlaneHeight;
// Get the angle between the camera and the object's down direction.
float angle = Vector3.Angle(Camera.main.transform.forward, Vector3.down);
angle = 90.0f - angle;
float touchOffsetRatio = Mathf.Clamp01(angle / 90.0f);
float screenTouchOffset = touchOffsetRatio * k_MaxScreenTouchOffset;
screenPos.y += GestureTouchesUtility.InchesToPixels(screenTouchOffset);
float hoverRatio = Mathf.Clamp01(angle / 45.0f);
hoverOffset *= hoverRatio;
float distance = (Camera.main.transform.position - currentAnchorPosition).magnitude;
float distanceHoverRatio = Mathf.Clamp01(distance / k_HoverDistanceThreshold);
hoverOffset *= distanceHoverRatio;
// The best estimate of the point in the plane where the object will be placed:
Vector3 groundingPoint;
// Get the ray to cast into the scene from the perspective of the camera.
TrackableHit hit;
if (Frame.Raycast(
screenPos.x, screenPos.y, TrackableHitFlags.PlaneWithinBounds, out hit))
{
if (hit.Trackable is DetectedPlane)
{
DetectedPlane plane = hit.Trackable as DetectedPlane;
if (IsPlaneTypeAllowed(translationMode, plane.PlaneType))
{
// Avoid detecting the back of existing planes.
if ((hit.Trackable is DetectedPlane) &&
Vector3.Dot(Camera.main.transform.position - hit.Pose.position,
hit.Pose.rotation * Vector3.up) < 0)
{
Debug.Log("Hit at back of the current DetectedPlane");
return result;
}
// Don't allow hovering for vertical or horizontal downward facing planes.
if (plane.PlaneType == DetectedPlaneType.Vertical ||
plane.PlaneType == DetectedPlaneType.HorizontalDownwardFacing)
{
// Limit the translation to maxTranslationDistance.
groundingPoint = LimitTranslation(
hit.Pose.position, currentAnchorPosition, maxTranslationDistance);
result.PlacementPlane = hit;
result.PlacementPosition = groundingPoint;
result.HoveringPosition = groundingPoint;
result.UpdatedGroundingPlaneHeight = groundingPoint.y;
result.PlacementRotation = hit.Pose.rotation;
return result;
}
// Allow hovering for horizontal upward facing planes.
if (plane.PlaneType == DetectedPlaneType.HorizontalUpwardFacing)
{
// Return early if the camera is pointing upwards.
if (angle < 0f)
{
return result;
}
// Limit the translation to maxTranslationDistance.
groundingPoint = LimitTranslation(
hit.Pose.position, currentAnchorPosition, maxTranslationDistance);
// Find the hovering position by casting from the camera onto the
// grounding plane and offsetting the result by the hover offset.
result.HoveringPosition = groundingPoint + (Vector3.up * hoverOffset);
// If the AR Plane is above the grounding plane, then the hit plane's
// position is used to replace the current groundingPlane. Otherwise,
// the hit is ignored because hits are only detected on lower planes by
// casting straight downwards in world space.
if (groundingPoint.y > groundingPlaneHeight)
{
result.PlacementPlane = hit;
result.PlacementPosition = groundingPoint;
result.UpdatedGroundingPlaneHeight = hit.Pose.position.y;
result.PlacementRotation = hit.Pose.rotation;
return result;
}
}
else
{
// Not supported plane type.
return result;
}
}
else
{
// Plane type not allowed.
return result;
}
}
else
{
// Hit is not a plane.
return result;
}
}
// Return early if the camera is pointing upwards.
if (angle < 0f)
{
return result;
}
// If the grounding point is lower than the current gorunding plane height, or if the
// raycast did not return a hit, then we extend the grounding plane to infinity, and do
// a new raycast into the scene from the perspective of the camera.
Ray cameraRay = Camera.main.ScreenPointToRay(screenPos);
Plane groundingPlane =
new Plane(Vector3.up, new Vector3(0.0f, groundingPlaneHeight, 0.0f));
// Find the hovering position by casting from the camera onto the grounding plane
// and offsetting the result by the hover offset.
float enter;
if (groundingPlane.Raycast(cameraRay, out enter))
{
groundingPoint = LimitTranslation(
cameraRay.GetPoint(enter), currentAnchorPosition, maxTranslationDistance);
result.HoveringPosition = groundingPoint + (Vector3.up * hoverOffset);
}
else
{
// If we can't successfully cast onto the groundingPlane, just return early.
return result;
}
// Cast straight down onto AR planes that are lower than the current grounding plane.
if (Frame.Raycast(
groundingPoint + (Vector3.up * k_DownRayOffset), Vector3.down,
out hit, Mathf.Infinity, TrackableHitFlags.PlaneWithinBounds))
{
result.PlacementPosition = hit.Pose.position;
result.PlacementPlane = hit;
result.PlacementRotation = hit.Pose.rotation;
return result;
}
return result;
}
/// <summary>
/// Limits the translation to the maximum distance allowed.
/// </summary>
/// <returns>The new target position, limited so that the object does not tranlsate more
/// than the maximum allowed distance.</returns>
/// <param name="desiredPosition">Desired position.</param>
/// <param name="currentPosition">Current position.</param>
/// <param name="maxTranslationDistance">Max translation distance.</param>
private static Vector3 LimitTranslation(Vector3 desiredPosition, Vector3 currentPosition,
float maxTranslationDistance)
{
if ((desiredPosition - currentPosition).magnitude > maxTranslationDistance)
{
return currentPosition + (
(desiredPosition - currentPosition).normalized * maxTranslationDistance);
}
return desiredPosition;
}
private static bool IsPlaneTypeAllowed(
TranslationMode translationMode, DetectedPlaneType planeType)
{
if (translationMode == TranslationMode.Any)
{
return true;
}
if (translationMode == TranslationMode.Horizontal &&
(planeType == DetectedPlaneType.HorizontalDownwardFacing ||
planeType == DetectedPlaneType.HorizontalUpwardFacing))
{
return true;
}
if (translationMode == TranslationMode.Vertical &&
planeType == DetectedPlaneType.Vertical)
{
return true;
}
return false;
}
/// <summary>
/// Result of the function GetBestPlacementPosition that indicates if a placementPosition
/// was found and information about the placement position.
/// </summary>
public struct Placement
{
/// <summary>
/// The position that the object should be displayed at before the placement has been
/// confirmed.
/// </summary>
public Vector3? HoveringPosition;
/// <summary>
/// The resulting position that the object should be placed at.
/// </summary>
public Vector3? PlacementPosition;
/// <summary>
/// The resulting rotation that the object should have.
/// </summary>
public Quaternion? PlacementRotation;
/// <summary>
/// The AR Plane that the object is being placed on.
/// </summary>
public TrackableHit? PlacementPlane;
/// <summary>
/// This is the updated groundingPlaneHeight resulting from this hit detection.
/// </summary>
public float UpdatedGroundingPlaneHeight;
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using ASC.Common.Logging;
using Newtonsoft.Json;
namespace ASC.Core.Common.Billing
{
public class CouponManager
{
private static IEnumerable<AvangateProduct> Products { get; set; }
private static IEnumerable<string> Groups { get; set; }
private static readonly int Percent;
private static readonly int Schedule;
private static readonly string VendorCode;
private static readonly byte[] Secret;
private static readonly Uri BaseAddress;
private static readonly string ApiVersion;
private static readonly SemaphoreSlim SemaphoreSlim = new SemaphoreSlim(1, 1);
private static readonly ILog Log;
static CouponManager()
{
SemaphoreSlim = new SemaphoreSlim(1, 1);
Log = LogManager.GetLogger("ASC");
try
{
var cfg = (AvangateCfgSectionHandler)ConfigurationManagerExtension.GetSection("avangate");
Secret = Encoding.UTF8.GetBytes(cfg.Secret);
VendorCode = cfg.Vendor;
Percent = cfg.Percent;
Schedule = cfg.Schedule;
BaseAddress = new Uri(cfg.BaseAddress);
ApiVersion = "/rest/" + cfg.ApiVersion.TrimStart('/');
Groups = (cfg.Groups ?? "").Split(',', '|', ' ');
}
catch (Exception e)
{
Secret = Encoding.UTF8.GetBytes("");
VendorCode = "";
Percent = AvangateCfgSectionHandler.DefaultPercent;
Schedule = AvangateCfgSectionHandler.DefaultShedule;
BaseAddress = new Uri(AvangateCfgSectionHandler.DefaultAdress);
ApiVersion = AvangateCfgSectionHandler.DefaultApiVersion;
Groups = new List<string>();
Log.Fatal(e);
}
}
public static string CreateCoupon()
{
return CreatePromotionAsync().Result;
}
private static async Task<string> CreatePromotionAsync()
{
try
{
using (var httpClient = PrepaireClient())
using (var content = new StringContent(await Promotion.GeneratePromotion(Percent, Schedule), Encoding.Default, "application/json"))
using (var response = await httpClient.PostAsync(string.Format("{0}/promotions/", ApiVersion), content))
{
if (!response.IsSuccessStatusCode)
throw new HttpException((int)response.StatusCode, response.ReasonPhrase);
var result = await response.Content.ReadAsStringAsync();
await Task.Delay(1000 - DateTime.UtcNow.Millisecond); // otherwise authorize exception
var createdPromotion = JsonConvert.DeserializeObject<Promotion>(result);
return createdPromotion.Coupon.Code;
}
}
catch (Exception ex)
{
Log.Error(ex.Message, ex);
throw;
}
}
internal static async Task<IEnumerable<AvangateProduct>> GetProducts()
{
if (Products != null) return Products;
await SemaphoreSlim.WaitAsync();
if (Products != null)
{
SemaphoreSlim.Release();
return Products;
}
try
{
using (var httpClient = PrepaireClient())
using (var response = await httpClient.GetAsync(string.Format("{0}/products/?Limit=1000&Enabled=true", ApiVersion)))
{
if (!response.IsSuccessStatusCode)
throw new HttpException((int)response.StatusCode, response.ReasonPhrase);
var result = await response.Content.ReadAsStringAsync();
Log.Debug(result);
var products = JsonConvert.DeserializeObject<List<AvangateProduct>>(result);
products = products.Where(r => r.ProductGroup != null && Groups.Contains(r.ProductGroup.Code)).ToList();
return Products = products;
}
}
catch (Exception ex)
{
Log.Error(ex.Message, ex);
throw;
}
finally
{
SemaphoreSlim.Release();
}
}
private static HttpClient PrepaireClient()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
const string applicationJson = "application/json";
var httpClient = new HttpClient { BaseAddress = BaseAddress, Timeout = TimeSpan.FromMinutes(3) };
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", applicationJson);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", applicationJson);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("X-Avangate-Authentication", CreateAuthHeader());
return httpClient;
}
private static string CreateAuthHeader()
{
using (var hmac = new HMACMD5(Secret))
{
var date = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss");
var hash = VendorCode.Length + VendorCode + date.Length + date;
var data = hmac.ComputeHash(Encoding.UTF8.GetBytes(hash));
var sBuilder = new StringBuilder();
foreach (var t in data)
{
sBuilder.Append(t.ToString("x2"));
}
var stringBuilder = new StringBuilder();
stringBuilder.AppendFormat("code='{0}' ", VendorCode);
stringBuilder.AppendFormat("date='{0}' ", date);
stringBuilder.AppendFormat("hash='{0}'", sBuilder);
return stringBuilder.ToString();
}
}
}
class Promotion
{
public string Code { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public string StartDate { get; set; }
public string EndDate { get; set; }
public bool Enabled { get; set; }
public int MaximumOrdersNumber { get; set; }
public bool InstantDiscount { get; set; }
public string ChannelType { get; set; }
public string ApplyRecurring { get; set; }
public Coupon Coupon { get; set; }
public Discount Discount { get; set; }
public IEnumerable<CouponProduct> Products { get; set; }
public int PublishToAffiliatesNetwork { get; set; }
public int AutoApply { get; set; }
public static async Task<string> GeneratePromotion(int percent, int schedule)
{
try
{
var tenant = CoreContext.TenantManager.GetCurrentTenant();
var startDate = DateTime.UtcNow.Date;
var endDate = startDate.AddDays(schedule);
var code = tenant.TenantAlias;
var promotion = new Promotion
{
Type = "REGULAR",
Enabled = true,
MaximumOrdersNumber = 1,
InstantDiscount = false,
ChannelType = "ECOMMERCE",
ApplyRecurring = "NONE",
PublishToAffiliatesNetwork = 0,
AutoApply = 0,
StartDate = startDate.ToString("yyyy-MM-dd"),
EndDate = endDate.ToString("yyyy-MM-dd"),
Name = string.Format("{0} {1}% off", code, percent),
Coupon = new Coupon { Type = "SINGLE", Code = code },
Discount = new Discount { Type = "PERCENT", Value = percent },
Products = (await CouponManager.GetProducts()).Select(r => new CouponProduct { Code = r.ProductCode })
};
return JsonConvert.SerializeObject(promotion);
}
catch (Exception ex)
{
LogManager.GetLogger("ASC").Error(ex.Message, ex);
throw;
}
}
}
class Coupon
{
public string Type { get; set; }
public string Code { get; set; }
}
class Discount
{
public string Type { get; set; }
public int Value { get; set; }
}
class AvangateProduct
{
public string ProductCode { get; set; }
public string ProductName { get; set; }
public AvangateProductGroup ProductGroup { get; set; }
}
class AvangateProductGroup
{
public string Name { get; set; }
public string Code { get; set; }
}
class CouponProduct
{
public string Code { get; set; }
}
class AvangateCfgSectionHandler : ConfigurationSection
{
public const string DefaultAdress = "https://api.avangate.com/";
public const string DefaultApiVersion = "4.0";
public const int DefaultPercent = 5;
public const int DefaultShedule = 10;
[ConfigurationProperty("secret")]
public string Secret
{
get { return (string)this["secret"]; }
}
[ConfigurationProperty("vendor")]
public string Vendor
{
get { return (string)this["vendor"]; }
set { this["vendor"] = value; }
}
[ConfigurationProperty("percent", DefaultValue = DefaultPercent)]
public int Percent
{
get { return Convert.ToInt32(this["percent"]); }
set { this["percent"] = value; }
}
[ConfigurationProperty("schedule", DefaultValue = DefaultShedule)]
public int Schedule
{
get { return Convert.ToInt32(this["schedule"]); }
set { this["schedule"] = value; }
}
[ConfigurationProperty("groups")]
public string Groups
{
get { return (string)this["groups"]; }
}
[ConfigurationProperty("address", DefaultValue = DefaultAdress)]
public string BaseAddress
{
get { return (string)this["address"]; }
set { this["address"] = value; }
}
[ConfigurationProperty("apiVersion", DefaultValue = DefaultApiVersion)]
public string ApiVersion
{
get { return (string)this["apiVersion"]; }
set { this["apiVersion"] = value; }
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using NUnit.Framework;
using StandardAnalyzer = Lucene.Net.Analysis.Standard.StandardAnalyzer;
using Document = Lucene.Net.Documents.Document;
using Field = Lucene.Net.Documents.Field;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using Term = Lucene.Net.Index.Term;
using QueryParser = Lucene.Net.QueryParsers.QueryParser;
using Directory = Lucene.Net.Store.Directory;
using MockRAMDirectory = Lucene.Net.Store.MockRAMDirectory;
using SpanNearQuery = Lucene.Net.Search.Spans.SpanNearQuery;
using SpanQuery = Lucene.Net.Search.Spans.SpanQuery;
using SpanTermQuery = Lucene.Net.Search.Spans.SpanTermQuery;
namespace Lucene.Net.Search
{
/// <summary> TestExplanations subclass focusing on basic query types</summary>
[TestFixture]
public class TestSimpleExplanations:TestExplanations
{
// we focus on queries that don't rewrite to other queries.
// if we get those covered well, then the ones that rewrite should
// also be covered.
/* simple term tests */
[Test]
public virtual void TestT1()
{
Qtest("w1", new int[]{0, 1, 2, 3});
}
[Test]
public virtual void TestT2()
{
Qtest("w1^1000", new int[]{0, 1, 2, 3});
}
/* MatchAllDocs */
[Test]
public virtual void TestMA1()
{
Qtest(new MatchAllDocsQuery(), new int[]{0, 1, 2, 3});
}
[Test]
public virtual void TestMA2()
{
Query q = new MatchAllDocsQuery();
q.SetBoost(1000);
Qtest(q, new int[]{0, 1, 2, 3});
}
/* some simple phrase tests */
[Test]
public virtual void TestP1()
{
Qtest("\"w1 w2\"", new int[]{0});
}
[Test]
public virtual void TestP2()
{
Qtest("\"w1 w3\"", new int[]{1, 3});
}
[Test]
public virtual void TestP3()
{
Qtest("\"w1 w2\"~1", new int[]{0, 1, 2});
}
[Test]
public virtual void TestP4()
{
Qtest("\"w2 w3\"~1", new int[]{0, 1, 2, 3});
}
[Test]
public virtual void TestP5()
{
Qtest("\"w3 w2\"~1", new int[]{1, 3});
}
[Test]
public virtual void TestP6()
{
Qtest("\"w3 w2\"~2", new int[]{0, 1, 3});
}
[Test]
public virtual void TestP7()
{
Qtest("\"w3 w2\"~3", new int[]{0, 1, 2, 3});
}
/* some simple filtered query tests */
[Test]
public virtual void TestFQ1()
{
Qtest(new FilteredQuery(qp.Parse("w1"), new ItemizedFilter(new int[]{0, 1, 2, 3})), new int[]{0, 1, 2, 3});
}
[Test]
public virtual void TestFQ2()
{
Qtest(new FilteredQuery(qp.Parse("w1"), new ItemizedFilter(new int[]{0, 2, 3})), new int[]{0, 2, 3});
}
[Test]
public virtual void TestFQ3()
{
Qtest(new FilteredQuery(qp.Parse("xx"), new ItemizedFilter(new int[]{1, 3})), new int[]{3});
}
[Test]
public virtual void TestFQ4()
{
Qtest(new FilteredQuery(qp.Parse("xx^1000"), new ItemizedFilter(new int[]{1, 3})), new int[]{3});
}
[Test]
public virtual void TestFQ6()
{
Query q = new FilteredQuery(qp.Parse("xx"), new ItemizedFilter(new int[]{1, 3}));
q.SetBoost(1000);
Qtest(q, new int[]{3});
}
/* ConstantScoreQueries */
[Test]
public virtual void TestCSQ1()
{
Query q = new ConstantScoreQuery(new ItemizedFilter(new int[]{0, 1, 2, 3}));
Qtest(q, new int[]{0, 1, 2, 3});
}
[Test]
public virtual void TestCSQ2()
{
Query q = new ConstantScoreQuery(new ItemizedFilter(new int[]{1, 3}));
Qtest(q, new int[]{1, 3});
}
[Test]
public virtual void TestCSQ3()
{
Query q = new ConstantScoreQuery(new ItemizedFilter(new int[]{0, 2}));
q.SetBoost(1000);
Qtest(q, new int[]{0, 2});
}
/* DisjunctionMaxQuery */
[Test]
public virtual void TestDMQ1()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.0f);
q.Add(qp.Parse("w1"));
q.Add(qp.Parse("w5"));
Qtest(q, new int[]{0, 1, 2, 3});
}
[Test]
public virtual void TestDMQ2()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f);
q.Add(qp.Parse("w1"));
q.Add(qp.Parse("w5"));
Qtest(q, new int[]{0, 1, 2, 3});
}
[Test]
public virtual void TestDMQ3()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f);
q.Add(qp.Parse("QQ"));
q.Add(qp.Parse("w5"));
Qtest(q, new int[]{0});
}
[Test]
public virtual void TestDMQ4()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f);
q.Add(qp.Parse("QQ"));
q.Add(qp.Parse("xx"));
Qtest(q, new int[]{2, 3});
}
[Test]
public virtual void TestDMQ5()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f);
q.Add(qp.Parse("yy -QQ"));
q.Add(qp.Parse("xx"));
Qtest(q, new int[]{2, 3});
}
[Test]
public virtual void TestDMQ6()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f);
q.Add(qp.Parse("-yy w3"));
q.Add(qp.Parse("xx"));
Qtest(q, new int[]{0, 1, 2, 3});
}
[Test]
public virtual void TestDMQ7()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f);
q.Add(qp.Parse("-yy w3"));
q.Add(qp.Parse("w2"));
Qtest(q, new int[]{0, 1, 2, 3});
}
[Test]
public virtual void TestDMQ8()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f);
q.Add(qp.Parse("yy w5^100"));
q.Add(qp.Parse("xx^100000"));
Qtest(q, new int[]{0, 2, 3});
}
[Test]
public virtual void TestDMQ9()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f);
q.Add(qp.Parse("yy w5^100"));
q.Add(qp.Parse("xx^0"));
Qtest(q, new int[]{0, 2, 3});
}
/* MultiPhraseQuery */
[Test]
public virtual void TestMPQ1()
{
MultiPhraseQuery q = new MultiPhraseQuery();
q.Add(Ta(new System.String[]{"w1"}));
q.Add(Ta(new System.String[]{"w2", "w3", "xx"}));
Qtest(q, new int[]{0, 1, 2, 3});
}
[Test]
public virtual void TestMPQ2()
{
MultiPhraseQuery q = new MultiPhraseQuery();
q.Add(Ta(new System.String[]{"w1"}));
q.Add(Ta(new System.String[]{"w2", "w3"}));
Qtest(q, new int[]{0, 1, 3});
}
[Test]
public virtual void TestMPQ3()
{
MultiPhraseQuery q = new MultiPhraseQuery();
q.Add(Ta(new System.String[]{"w1", "xx"}));
q.Add(Ta(new System.String[]{"w2", "w3"}));
Qtest(q, new int[]{0, 1, 2, 3});
}
[Test]
public virtual void TestMPQ4()
{
MultiPhraseQuery q = new MultiPhraseQuery();
q.Add(Ta(new System.String[]{"w1"}));
q.Add(Ta(new System.String[]{"w2"}));
Qtest(q, new int[]{0});
}
[Test]
public virtual void TestMPQ5()
{
MultiPhraseQuery q = new MultiPhraseQuery();
q.Add(Ta(new System.String[]{"w1"}));
q.Add(Ta(new System.String[]{"w2"}));
q.SetSlop(1);
Qtest(q, new int[]{0, 1, 2});
}
[Test]
public virtual void TestMPQ6()
{
MultiPhraseQuery q = new MultiPhraseQuery();
q.Add(Ta(new System.String[]{"w1", "w3"}));
q.Add(Ta(new System.String[]{"w2"}));
q.SetSlop(1);
Qtest(q, new int[]{0, 1, 2, 3});
}
/* some simple tests of boolean queries containing term queries */
[Test]
public virtual void TestBQ1()
{
Qtest("+w1 +w2", new int[]{0, 1, 2, 3});
}
[Test]
public virtual void TestBQ2()
{
Qtest("+yy +w3", new int[]{2, 3});
}
[Test]
public virtual void TestBQ3()
{
Qtest("yy +w3", new int[]{0, 1, 2, 3});
}
[Test]
public virtual void TestBQ4()
{
Qtest("w1 (-xx w2)", new int[]{0, 1, 2, 3});
}
[Test]
public virtual void TestBQ5()
{
Qtest("w1 (+qq w2)", new int[]{0, 1, 2, 3});
}
[Test]
public virtual void TestBQ6()
{
Qtest("w1 -(-qq w5)", new int[]{1, 2, 3});
}
[Test]
public virtual void TestBQ7()
{
Qtest("+w1 +(qq (xx -w2) (+w3 +w4))", new int[]{0});
}
[Test]
public virtual void TestBQ8()
{
Qtest("+w1 (qq (xx -w2) (+w3 +w4))", new int[]{0, 1, 2, 3});
}
[Test]
public virtual void TestBQ9()
{
Qtest("+w1 (qq (-xx w2) -(+w3 +w4))", new int[]{0, 1, 2, 3});
}
[Test]
public virtual void TestBQ10()
{
Qtest("+w1 +(qq (-xx w2) -(+w3 +w4))", new int[]{1});
}
[Test]
public virtual void TestBQ11()
{
Qtest("w1 w2^1000.0", new int[]{0, 1, 2, 3});
}
[Test]
public virtual void TestBQ14()
{
BooleanQuery q = new BooleanQuery(true);
q.Add(qp.Parse("QQQQQ"), BooleanClause.Occur.SHOULD);
q.Add(qp.Parse("w1"), BooleanClause.Occur.SHOULD);
Qtest(q, new int[]{0, 1, 2, 3});
}
[Test]
public virtual void TestBQ15()
{
BooleanQuery q = new BooleanQuery(true);
q.Add(qp.Parse("QQQQQ"), BooleanClause.Occur.MUST_NOT);
q.Add(qp.Parse("w1"), BooleanClause.Occur.SHOULD);
Qtest(q, new int[]{0, 1, 2, 3});
}
[Test]
public virtual void TestBQ16()
{
BooleanQuery q = new BooleanQuery(true);
q.Add(qp.Parse("QQQQQ"), BooleanClause.Occur.SHOULD);
q.Add(qp.Parse("w1 -xx"), BooleanClause.Occur.SHOULD);
Qtest(q, new int[]{0, 1});
}
[Test]
public virtual void TestBQ17()
{
BooleanQuery q = new BooleanQuery(true);
q.Add(qp.Parse("w2"), BooleanClause.Occur.SHOULD);
q.Add(qp.Parse("w1 -xx"), BooleanClause.Occur.SHOULD);
Qtest(q, new int[]{0, 1, 2, 3});
}
[Test]
public virtual void TestBQ19()
{
Qtest("-yy w3", new int[]{0, 1});
}
[Test]
public virtual void TestBQ20()
{
BooleanQuery q = new BooleanQuery();
q.SetMinimumNumberShouldMatch(2);
q.Add(qp.Parse("QQQQQ"), BooleanClause.Occur.SHOULD);
q.Add(qp.Parse("yy"), BooleanClause.Occur.SHOULD);
q.Add(qp.Parse("zz"), BooleanClause.Occur.SHOULD);
q.Add(qp.Parse("w5"), BooleanClause.Occur.SHOULD);
q.Add(qp.Parse("w4"), BooleanClause.Occur.SHOULD);
Qtest(q, new int[]{0, 3});
}
[Test]
public virtual void TestTermQueryMultiSearcherExplain()
{
// creating two directories for indices
Directory indexStoreA = new MockRAMDirectory();
Directory indexStoreB = new MockRAMDirectory();
Document lDoc = new Document();
lDoc.Add(new Field("handle", "1 2", Field.Store.YES, Field.Index.ANALYZED));
Document lDoc2 = new Document();
lDoc2.Add(new Field("handle", "1 2", Field.Store.YES, Field.Index.ANALYZED));
Document lDoc3 = new Document();
lDoc3.Add(new Field("handle", "1 2", Field.Store.YES, Field.Index.ANALYZED));
IndexWriter writerA = new IndexWriter(indexStoreA, new StandardAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
IndexWriter writerB = new IndexWriter(indexStoreB, new StandardAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
writerA.AddDocument(lDoc);
writerA.AddDocument(lDoc2);
writerA.Optimize();
writerA.Close();
writerB.AddDocument(lDoc3);
writerB.Close();
QueryParser parser = new QueryParser("fulltext", new StandardAnalyzer());
Query query = parser.Parse("handle:1");
Searcher[] searchers = new Searcher[2];
searchers[0] = new IndexSearcher(indexStoreB);
searchers[1] = new IndexSearcher(indexStoreA);
Searcher mSearcher = new MultiSearcher(searchers);
ScoreDoc[] hits = mSearcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(3, hits.Length);
Explanation explain = mSearcher.Explain(query, hits[0].doc);
System.String exp = explain.ToString(0);
Assert.IsTrue(exp.IndexOf("maxDocs=3") > - 1, exp);
Assert.IsTrue(exp.IndexOf("docFreq=3") > - 1, exp);
query = parser.Parse("handle:\"1 2\"");
hits = mSearcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(3, hits.Length);
explain = mSearcher.Explain(query, hits[0].doc);
exp = explain.ToString(0);
Assert.IsTrue(exp.IndexOf("1=3") > - 1, exp);
Assert.IsTrue(exp.IndexOf("2=3") > - 1, exp);
query = new SpanNearQuery(new SpanQuery[]{new SpanTermQuery(new Term("handle", "1")), new SpanTermQuery(new Term("handle", "2"))}, 0, true);
hits = mSearcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(3, hits.Length);
explain = mSearcher.Explain(query, hits[0].doc);
exp = explain.ToString(0);
Assert.IsTrue(exp.IndexOf("1=3") > - 1, exp);
Assert.IsTrue(exp.IndexOf("2=3") > - 1, exp);
mSearcher.Close();
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
// ********************************************************************************************************
// 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 4/28/2009 12:00:28 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.ComponentModel;
using System.Linq;
using DotSpatial.Projections;
namespace DotSpatial.Data
{
/// <summary>
/// DataSet
/// </summary>
public class DataSet : DisposeBase, IDataSet
{
#region Private Variables
private volatile static bool _projectionLibraryTested;
private volatile static bool _canProject;
private IProgressHandler _progressHandler;
private ProgressMeter _progressMeter;
private string _proj4String;
#endregion
/// <summary>
/// Gets whether or not projection is based on having the libraries available.
/// </summary>
/// <returns></returns>
public static bool ProjectionSupported()
{
if (_projectionLibraryTested)
{
return _canProject;
}
_projectionLibraryTested = true;
_canProject = AppDomain.CurrentDomain.GetAssemblies().Any(d => d.GetName().Name == "DotSpatial.Projections");
return _canProject;
}
#region Constructors
/// <summary>
/// Creates a new instance of DataSet
/// </summary>
protected DataSet()
{
_progressHandler = DataManager.DefaultDataManager.ProgressHandler;
}
#endregion
#region Methods
/// <summary>
/// This can be overridden in specific classes if necessary
/// </summary>
public virtual void Close()
{
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the cached extent variable. The public Extent is the virtual accessor,
/// and should not be used from a constructor. MyExtent is protected, not virtual,
/// and is only visible to inheriting classes, and can be safely set in the constructor.
/// </summary>
protected Extent MyExtent { get; set; }
/// <summary>
/// This is an internal place holder to make it easier to pass around a single progress meter
/// between methods. This will use lazy instantiation if it is requested before one has
/// been created.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
protected ProgressMeter ProgressMeter
{
get { return _progressMeter ?? (_progressMeter = new ProgressMeter(ProgressHandler)); }
set { _progressMeter = value; }
}
/// <summary>
/// Gets or sets the raw projection string for this dataset. This handles both the
/// case where projection is unavailable but a projection string needs to
/// be passed around, and the case when a string is not recognized by the
/// DotSpatial.Projections library. This is not format restricted, but should match
/// the original data source as closely as possible. Setting this will also set
/// the Projection if the Projection library is available and the format successfully
/// defines a transform by either treating it as an Esri string or a proj4 string.
/// </summary>
public string ProjectionString
{
get
{
if (!String.IsNullOrEmpty(_proj4String)) return _proj4String;
if (CanReproject) return Projection.ToProj4String();
return _proj4String;
}
set
{
if (_proj4String == value) return;
_proj4String = value;
var test = ProjectionInfo.FromProj4String(value);
if (test.Transform == null)
{
// regardless of the result, the "Transform" will be null if this fails.
test.TryParseEsriString(value);
}
if (test.Transform != null)
{
Projection = test;
}
}
}
/// <summary>
/// Gets a value indicating whether the DotSpatial.Projections assembly is loaded
/// </summary>
/// <returns>Boolean, true if the value can reproject.</returns>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool CanReproject
{
get { return ProjectionSupported() && Projection != null && Projection.IsValid; }
}
/// <summary>
/// Reprojects all of the in-ram vertices of featuresets, or else this
/// simply updates the "Bounds" of the image object.
/// This will also update the projection to be the specified projection.
/// </summary>
/// <param name="targetProjection">
/// The projection information to reproject the coordinates to.
/// </param>
public virtual void Reproject(ProjectionInfo targetProjection)
{
}
/// <summary>
/// Gets or sets the string name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the extent for the dataset. Usages to Envelope were replaced
/// as they required an explicit using to DotSpatial.Topology which is not
/// as intuitive. Extent.ToEnvelope() and new Extent(myEnvelope) convert them.
/// This is designed to be a virtual member to be overridden by subclasses,
/// and should not be called directly by the constructor of inheriting classes.
/// </summary>
public virtual Extent Extent
{
get
{
return MyExtent;
}
set
{
MyExtent = value;
}
}
/// <summary>
/// Gets or set the projection string
/// </summary>
public ProjectionInfo Projection { get; set; }
/// <summary>
/// Gets an enumeration specifying if this data supports time, space, both or neither.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public SpaceTimeSupport SpaceTimeSupport { get; set; }
/// <summary>
/// Gets or sets the string type name that identifies this dataset
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string TypeName { get; set; }
/// <summary>
/// Gets or sets the progress handler to use for internal actions taken by this dataset.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual IProgressHandler ProgressHandler
{
get
{
return _progressHandler;
}
set
{
_progressHandler = value;
if (_progressMeter == null && value != null)
{
_progressMeter = new ProgressMeter(_progressHandler);
}
}
}
/// <summary>
/// Allows overriding the dispose behavior to handle any resources in addition to what are handled in the
/// image data class.
/// </summary>
/// <param name="disposeManagedResources">A Boolean value that indicates whether the overriding method
/// should dispose managed resources, or just the unmanaged ones.</param>
protected override void Dispose(bool disposeManagedResources)
{
if (disposeManagedResources)
{
Name = null;
Projection = null;
TypeName = null;
_progressHandler = null;
_progressMeter = null;
}
base.Dispose(disposeManagedResources);
}
#endregion
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
using csscript;
using CSScripting.CodeDom;
using CSScriptLib;
namespace CSScripting
{
/// <summary>
/// The configuration and methods of the global context.
/// </summary>
public partial class Globals
{
static internal string DynamicWrapperClassName = "DynamicClass";
static internal string RootClassName = "css_root";
// Roslyn still does not support anything else but `Submission#0` (17 Jul 2019) [update]
// Roslyn now does support alternative class names (1 Jan 2020)
static internal void StartBuildServer(bool report = false)
{
if (Globals.BuildServerIsDeployed)
"dotnet".RunAsync($"\"{Globals.build_server}\" -start -csc:\"{Globals.csc}\"");
if (report)
PrintBuildServerInfo();
}
static internal void RestartBuildServer(bool report = false)
{
StopBuildServer();
StartBuildServer(report);
}
static internal void ResetBuildServer(bool report = false)
{
StopBuildServer();
while (BuildServer.IsServerAlive(null))
Thread.Sleep(500);
RemoveBuildServer();
DeployBuildServer();
StartBuildServer(report);
}
static internal void PrintBuildServerInfo()
{
if (Globals.BuildServerIsDeployed)
{ // CSScriptLib.CoreExtensions.RunAsync(
var alive = BuildServer.IsServerAlive(null);
Console.WriteLine($"Build server: {Globals.build_server.GetFullPath()}");
var pingResponse = BuildServer.PingRemoteInstance(null).Split('\n');
var pid = alive ?
$" ({pingResponse.FirstOrDefault()})"
: "";
Console.WriteLine($"Build server compiler: {(alive ? pingResponse[2] : "")}");
Console.WriteLine($"Build server is {(alive ? "" : "not ")}running{pid}.");
}
else
{
Console.WriteLine("Build server is not deployed.");
Console.WriteLine($"Expected deployment: {Globals.build_server.GetFullPath()}");
}
}
static internal void Install(bool installRequest)
{
if (Globals.BuildServerIsDeployed)
{ // CSScriptLib.CoreExtensions.RunAsync(
Console.WriteLine($"Build server: {Globals.build_server.GetFullPath()}");
Console.WriteLine($"Build server compiler: {Globals.csc.GetFullPath()}");
Console.WriteLine($"Build server is {(BuildServer.IsServerAlive(null) ? "" : "not ")}running.");
}
else
{
Console.WriteLine("Build server is not deployed.");
Console.WriteLine($"Expected deployment: {Globals.build_server.GetFullPath()}");
}
}
static internal void StopBuildServer()
{
if (Globals.BuildServerIsDeployed)
"dotnet".RunAsync($"\"{Globals.build_server}\" -stop");
}
static internal string build_server
{
get
{
var path = Environment.SpecialFolder.CommonApplicationData.GetPath().PathJoin("cs-script",
"bin",
"compiler",
Assembly.GetExecutingAssembly().GetName().Version,
"build.dll");
if (Runtime.IsLinux)
{
path = path.Replace("/usr/share/cs-script", "/usr/local/share/cs-script");
}
return path;
}
}
/// <summary>
/// Removes the build server from the target system.
/// </summary>
/// <returns><c>true</c> if success; otherwise <c>false</c></returns>
static public bool RemoveBuildServer()
{
try
{
File.Delete(build_server);
File.Delete(build_server.ChangeExtension(".deps.json"));
File.Delete(build_server.ChangeExtension(".runtimeconfig.json"));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return !File.Exists(build_server);
}
/// <summary>
/// Deploys the build server on the target system.
/// </summary>
static public bool DeployBuildServer()
{
try
{
Directory.CreateDirectory(build_server.GetDirName());
File.WriteAllBytes(build_server, Resources.build);
File.WriteAllBytes(build_server.ChangeExtension(".deps.json"), Resources.build_deps);
File.WriteAllBytes(build_server.ChangeExtension(".runtimeconfig.json"), Resources.build_runtimeconfig);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return File.Exists(build_server);
}
/// <summary>
/// Pings the running instance of the build server.
/// </summary>
static public void Ping()
{
Console.WriteLine(BuildServer.PingRemoteInstance(null));
}
// static internal bool IsRemoteInstanceRunning() { try { using (var clientSocket = new
// TcpClient()) { return clientSocket .ConnectAsync(IPAddress.Loopback, port ?? serverPort)
// .Wait(TimeSpan.FromMilliseconds(20)); } } catch { return false; } }
/// <summary>
/// Gets a value indicating whether build server is deployed.
/// </summary>
/// <value><c>true</c> if build server is deployed; otherwise, <c>false</c>.</value>
static public bool BuildServerIsDeployed
{
get
{
#if !DEBUG
if (!build_server.FileExists())
#endif
try
{
Directory.CreateDirectory(build_server.GetDirName());
File.WriteAllBytes(build_server, Resources.build);
File.WriteAllBytes(build_server.ChangeExtension(".deps.json"), Resources.build_deps);
File.WriteAllBytes(build_server.ChangeExtension(".runtimeconfig.json"), Resources.build_runtimeconfig);
}
catch { }
return build_server.FileExists();
}
}
static string csc_file = Environment.GetEnvironmentVariable("css_csc_file");
static internal string LibDir => Assembly.GetExecutingAssembly().Location.GetDirName().PathJoin("lib");
/// <summary>
/// Gets the path to the assembly implementing Roslyn compiler.
/// </summary>
static public string roslyn => typeof(Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript).Assembly.Location;
/// <summary>
/// Gets the path to the dotnet executable.
/// </summary>
/// <value>The dotnet executable path.</value>
static public string dotnet
{
get
{
var dotnetExeName = Runtime.IsLinux ? "dotnet" : "dotnet.exe";
var file = "".GetType().Assembly.Location
.Split(Path.DirectorySeparatorChar)
.TakeWhile(x => x != "dotnet")
.JoinBy(Path.DirectorySeparatorChar.ToString())
.PathJoin("dotnet", dotnetExeName);
return File.Exists(file) ? file : dotnetExeName;
}
}
static internal string GetCompilerFor(string file)
=> file.GetExtension().SameAs(".cs") ? csc : csc.ChangeFileName("vbc.dll");
static internal string CheckAndGenerateSdkWarning()
{
if (!csc.FileExists())
{
return $"WARNING: .NET {Environment.Version.Major} SDK cannot be found. It's required for `csc` and `dotnet` compiler engines.";
}
return null;
}
/// <summary>
/// Gets or sets the path to the C# compiler executable (e.g. csc.exe or csc.dll)
/// </summary>
/// <value>The CSC.</value>
static public string csc
{
set
{
csc_file = value;
}
get
{
if (csc_file == null)
{
#if class_lib
if (!Runtime.IsCore)
{
csc_file = Path.Combine(Path.GetDirectoryName("".GetType().Assembly.Location), "csc.exe");
}
else
#endif
{
// Win: C:\Program Files\dotnet\sdk\6.0.100-rc.2.21505.57\Roslyn\bincore\csc.dll
// C:\Program Files (x86)\dotnet\sdk\5.0.402\Roslyn\bincore\csc.dll
// Linux: ~dotnet/.../3.0.100-preview5-011568/Roslyn/... (cannot find SDK in preview)
// win: program_files/dotnet/sdk/<version>/Roslyn/csc.exe
var dotnet_root = "".GetType().Assembly.Location;
// find first "dotnet" parent dir by trimming till the last "dotnet" token
dotnet_root = dotnet_root.Split(Path.DirectorySeparatorChar)
.Reverse()
.SkipWhile(x => x != "dotnet")
.Reverse()
.JoinBy(Path.DirectorySeparatorChar.ToString());
if (dotnet_root.PathJoin("sdk").DirExists()) // need to check as otherwise it will throw
{
var dirs = dotnet_root.PathJoin("sdk")
.PathGetDirs($"{Environment.Version.Major}*")
.Where(dir => char.IsDigit(dir.GetFileName()[0]))
.OrderBy(x => System.Version.Parse(x.GetFileName().Split('-').First()))
.SelectMany(dir => dir.PathGetDirs("Roslyn"))
.ToArray();
csc_file = dirs.Select(dir => dir.PathJoin("bincore", "csc.dll"))
.LastOrDefault(File.Exists);
}
}
}
return csc_file;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: A base implementation of the IFormatterConverter
** interface that uses the Convert class and the
** IConvertible interface.
**
**
============================================================*/
using System;
using System.Globalization;
using System.Diagnostics.Contracts;
namespace System.Runtime.Serialization
{
internal class FormatterConverter : IFormatterConverter
{
public FormatterConverter()
{
}
public Object Convert(Object value, Type type)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
}
public Object Convert(Object value, TypeCode typeCode)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ChangeType(value, typeCode, CultureInfo.InvariantCulture);
}
public bool ToBoolean(Object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToBoolean(value, CultureInfo.InvariantCulture);
}
public char ToChar(Object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToChar(value, CultureInfo.InvariantCulture);
}
[CLSCompliant(false)]
public sbyte ToSByte(Object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToSByte(value, CultureInfo.InvariantCulture);
}
public byte ToByte(Object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToByte(value, CultureInfo.InvariantCulture);
}
public short ToInt16(Object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToInt16(value, CultureInfo.InvariantCulture);
}
[CLSCompliant(false)]
public ushort ToUInt16(Object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToUInt16(value, CultureInfo.InvariantCulture);
}
public int ToInt32(Object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToInt32(value, CultureInfo.InvariantCulture);
}
[CLSCompliant(false)]
public uint ToUInt32(Object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToUInt32(value, CultureInfo.InvariantCulture);
}
public long ToInt64(Object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToInt64(value, CultureInfo.InvariantCulture);
}
[CLSCompliant(false)]
public ulong ToUInt64(Object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToUInt64(value, CultureInfo.InvariantCulture);
}
public float ToSingle(Object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToSingle(value, CultureInfo.InvariantCulture);
}
public double ToDouble(Object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToDouble(value, CultureInfo.InvariantCulture);
}
public Decimal ToDecimal(Object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToDecimal(value, CultureInfo.InvariantCulture);
}
public DateTime ToDateTime(Object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToDateTime(value, CultureInfo.InvariantCulture);
}
public String ToString(Object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToString(value, CultureInfo.InvariantCulture);
}
}
}
| |
/*
* 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 copyrightD
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using OpenSim.Framework;
using OMV = OpenMetaverse;
namespace OpenSim.Region.Physics.BulletSPlugin
{
// When a child is linked, the relationship position of the child to the parent
// is remembered so the child's world position can be recomputed when it is
// removed from the linkset.
sealed class BSLinksetCompoundInfo : BSLinksetInfo
{
public int Index;
public OMV.Vector3 OffsetFromRoot;
public OMV.Vector3 OffsetFromCenterOfMass;
public OMV.Quaternion OffsetRot;
public BSLinksetCompoundInfo(int indx, OMV.Vector3 p, OMV.Quaternion r)
{
Index = indx;
OffsetFromRoot = p;
OffsetFromCenterOfMass = p;
OffsetRot = r;
}
// 'centerDisplacement' is the distance from the root the the center-of-mass (Bullet 'zero' of the shape)
public BSLinksetCompoundInfo(int indx, BSPrimLinkable root, BSPrimLinkable child, OMV.Vector3 centerDisplacement)
{
// Each child position and rotation is given relative to the center-of-mass.
OMV.Quaternion invRootOrientation = OMV.Quaternion.Inverse(root.RawOrientation);
OMV.Vector3 displacementFromRoot = (child.RawPosition - root.RawPosition) * invRootOrientation;
OMV.Vector3 displacementFromCOM = displacementFromRoot - centerDisplacement;
OMV.Quaternion displacementRot = child.RawOrientation * invRootOrientation;
// Save relative position for recomputing child's world position after moving linkset.
Index = indx;
OffsetFromRoot = displacementFromRoot;
OffsetFromCenterOfMass = displacementFromCOM;
OffsetRot = displacementRot;
}
public override void Clear()
{
Index = 0;
OffsetFromRoot = OMV.Vector3.Zero;
OffsetFromCenterOfMass = OMV.Vector3.Zero;
OffsetRot = OMV.Quaternion.Identity;
}
public override string ToString()
{
StringBuilder buff = new StringBuilder();
buff.Append("<i=");
buff.Append(Index.ToString());
buff.Append(",p=");
buff.Append(OffsetFromRoot.ToString());
buff.Append(",m=");
buff.Append(OffsetFromCenterOfMass.ToString());
buff.Append(",r=");
buff.Append(OffsetRot.ToString());
buff.Append(">");
return buff.ToString();
}
};
public sealed class BSLinksetCompound : BSLinkset
{
private static string LogHeader = "[BULLETSIM LINKSET COMPOUND]";
public BSLinksetCompound(BSScene scene, BSPrimLinkable parent)
: base(scene, parent)
{
}
// For compound implimented linksets, if there are children, use compound shape for the root.
public override BSPhysicsShapeType PreferredPhysicalShape(BSPrimLinkable requestor)
{
// Returning 'unknown' means we don't have a preference.
BSPhysicsShapeType ret = BSPhysicsShapeType.SHAPE_UNKNOWN;
if (IsRoot(requestor) && HasAnyChildren)
{
ret = BSPhysicsShapeType.SHAPE_COMPOUND;
}
// DetailLog("{0},BSLinksetCompound.PreferredPhysicalShape,call,shape={1}", LinksetRoot.LocalID, ret);
return ret;
}
// When physical properties are changed the linkset needs to recalculate
// its internal properties.
public override void Refresh(BSPrimLinkable requestor)
{
base.Refresh(requestor);
// Something changed so do the rebuilding thing
// ScheduleRebuild();
}
// Schedule a refresh to happen after all the other taint processing.
private void ScheduleRebuild(BSPrimLinkable requestor)
{
DetailLog("{0},BSLinksetCompound.ScheduleRebuild,,rebuilding={1},hasChildren={2},actuallyScheduling={3}",
requestor.LocalID, Rebuilding, HasAnyChildren, (!Rebuilding && HasAnyChildren));
// When rebuilding, it is possible to set properties that would normally require a rebuild.
// If already rebuilding, don't request another rebuild.
// If a linkset with just a root prim (simple non-linked prim) don't bother rebuilding.
if (!Rebuilding && HasAnyChildren)
{
PhysicsScene.PostTaintObject("BSLinksetCompound.ScheduleRebuild", LinksetRoot.LocalID, delegate()
{
if (HasAnyChildren)
RecomputeLinksetCompound();
});
}
}
// The object is going dynamic (physical). Do any setup necessary for a dynamic linkset.
// Only the state of the passed object can be modified. The rest of the linkset
// has not yet been fully constructed.
// Return 'true' if any properties updated on the passed object.
// Called at taint-time!
public override bool MakeDynamic(BSPrimLinkable child)
{
bool ret = false;
DetailLog("{0},BSLinksetCompound.MakeDynamic,call,IsRoot={1}", child.LocalID, IsRoot(child));
if (IsRoot(child))
{
// The root is going dynamic. Rebuild the linkset so parts and mass get computed properly.
ScheduleRebuild(LinksetRoot);
}
else
{
// The origional prims are removed from the world as the shape of the root compound
// shape takes over.
PhysicsScene.PE.AddToCollisionFlags(child.PhysBody, CollisionFlags.CF_NO_CONTACT_RESPONSE);
PhysicsScene.PE.ForceActivationState(child.PhysBody, ActivationState.DISABLE_SIMULATION);
// We don't want collisions from the old linkset children.
PhysicsScene.PE.RemoveFromCollisionFlags(child.PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS);
child.PhysBody.collisionType = CollisionType.LinksetChild;
ret = true;
}
return ret;
}
// The object is going static (non-physical). Do any setup necessary for a static linkset.
// Return 'true' if any properties updated on the passed object.
// This doesn't normally happen -- OpenSim removes the objects from the physical
// world if it is a static linkset.
// Called at taint-time!
public override bool MakeStatic(BSPrimLinkable child)
{
bool ret = false;
DetailLog("{0},BSLinksetCompound.MakeStatic,call,IsRoot={1}", child.LocalID, IsRoot(child));
if (IsRoot(child))
{
ScheduleRebuild(LinksetRoot);
}
else
{
// The non-physical children can come back to life.
PhysicsScene.PE.RemoveFromCollisionFlags(child.PhysBody, CollisionFlags.CF_NO_CONTACT_RESPONSE);
child.PhysBody.collisionType = CollisionType.LinksetChild;
// Don't force activation so setting of DISABLE_SIMULATION can stay if used.
PhysicsScene.PE.Activate(child.PhysBody, false);
ret = true;
}
return ret;
}
// 'physicalUpdate' is true if these changes came directly from the physics engine. Don't need to rebuild then.
// Called at taint-time.
public override void UpdateProperties(UpdatedProperties whichUpdated, BSPrimLinkable updated)
{
// The user moving a child around requires the rebuilding of the linkset compound shape
// One problem is this happens when a border is crossed -- the simulator implementation
// stores the position into the group which causes the move of the object
// but it also means all the child positions get updated.
// What would cause an unnecessary rebuild so we make sure the linkset is in a
// region before bothering to do a rebuild.
if (!IsRoot(updated) && PhysicsScene.TerrainManager.IsWithinKnownTerrain(LinksetRoot.RawPosition))
{
// If a child of the linkset is updating only the position or rotation, that can be done
// without rebuilding the linkset.
// If a handle for the child can be fetch, we update the child here. If a rebuild was
// scheduled by someone else, the rebuild will just replace this setting.
bool updatedChild = false;
// Anything other than updating position or orientation usually means a physical update
// and that is caused by us updating the object.
if ((whichUpdated & ~(UpdatedProperties.Position | UpdatedProperties.Orientation)) == 0)
{
// Find the physical instance of the child
if (LinksetRoot.PhysShape.HasPhysicalShape && PhysicsScene.PE.IsCompound(LinksetRoot.PhysShape))
{
// It is possible that the linkset is still under construction and the child is not yet
// inserted into the compound shape. A rebuild of the linkset in a pre-step action will
// build the whole thing with the new position or rotation.
// The index must be checked because Bullet references the child array but does no validity
// checking of the child index passed.
int numLinksetChildren = PhysicsScene.PE.GetNumberOfCompoundChildren(LinksetRoot.PhysShape);
if (updated.LinksetChildIndex < numLinksetChildren)
{
BulletShape linksetChildShape = PhysicsScene.PE.GetChildShapeFromCompoundShapeIndex(LinksetRoot.PhysShape, updated.LinksetChildIndex);
if (linksetChildShape.HasPhysicalShape)
{
// Found the child shape within the compound shape
PhysicsScene.PE.UpdateChildTransform(LinksetRoot.PhysShape, updated.LinksetChildIndex,
updated.RawPosition - LinksetRoot.RawPosition,
updated.RawOrientation * OMV.Quaternion.Inverse(LinksetRoot.RawOrientation),
true /* shouldRecalculateLocalAabb */);
updatedChild = true;
DetailLog("{0},BSLinksetCompound.UpdateProperties,changeChildPosRot,whichUpdated={1},pos={2},rot={3}",
updated.LocalID, whichUpdated, updated.RawPosition, updated.RawOrientation);
}
else // DEBUG DEBUG
{ // DEBUG DEBUG
DetailLog("{0},BSLinksetCompound.UpdateProperties,couldNotUpdateChild,noChildShape,shape={1}",
updated.LocalID, linksetChildShape);
} // DEBUG DEBUG
}
else // DEBUG DEBUG
{ // DEBUG DEBUG
// the child is not yet in the compound shape. This is non-fatal.
DetailLog("{0},BSLinksetCompound.UpdateProperties,couldNotUpdateChild,childNotInCompoundShape,numChildren={1},index={2}",
updated.LocalID, numLinksetChildren, updated.LinksetChildIndex);
} // DEBUG DEBUG
}
else // DEBUG DEBUG
{ // DEBUG DEBUG
DetailLog("{0},BSLinksetCompound.UpdateProperties,couldNotUpdateChild,noBodyOrNotCompound", updated.LocalID);
} // DEBUG DEBUG
if (!updatedChild)
{
// If couldn't do the individual child, the linkset needs a rebuild to incorporate the new child info.
// Note: there are several ways through this code that will not update the child if
// the linkset is being rebuilt. In this case, scheduling a rebuild is a NOOP since
// there will already be a rebuild scheduled.
DetailLog("{0},BSLinksetCompound.UpdateProperties,couldNotUpdateChild.schedulingRebuild,whichUpdated={1}",
updated.LocalID, whichUpdated);
updated.LinksetInfo = null; // setting to 'null' causes relative position to be recomputed.
ScheduleRebuild(updated);
}
}
}
}
// Routine called when rebuilding the body of some member of the linkset.
// Since we don't keep in world relationships, do nothing unless it's a child changing.
// Returns 'true' of something was actually removed and would need restoring
// Called at taint-time!!
public override bool RemoveBodyDependencies(BSPrimLinkable child)
{
bool ret = false;
DetailLog("{0},BSLinksetCompound.RemoveBodyDependencies,refreshIfChild,rID={1},rBody={2},isRoot={3}",
child.LocalID, LinksetRoot.LocalID, LinksetRoot.PhysBody, IsRoot(child));
if (!IsRoot(child))
{
// Because it is a convenient time, recompute child world position and rotation based on
// its position in the linkset.
RecomputeChildWorldPosition(child, true /* inTaintTime */);
child.LinksetInfo = null;
}
// Cannot schedule a refresh/rebuild here because this routine is called when
// the linkset is being rebuilt.
// InternalRefresh(LinksetRoot);
return ret;
}
// When the linkset is built, the child shape is added to the compound shape relative to the
// root shape. The linkset then moves around but this does not move the actual child
// prim. The child prim's location must be recomputed based on the location of the root shape.
private void RecomputeChildWorldPosition(BSPrimLinkable child, bool inTaintTime)
{
// For the moment (20130201), disable this computation (converting the child physical addr back to
// a region address) until we have a good handle on center-of-mass offsets and what the physics
// engine moving a child actually means.
// The simulator keeps track of where children should be as the linkset moves. Setting
// the pos/rot here does not effect that knowledge as there is no good way for the
// physics engine to send the simulator an update for a child.
/*
BSLinksetCompoundInfo lci = child.LinksetInfo as BSLinksetCompoundInfo;
if (lci != null)
{
if (inTaintTime)
{
OMV.Vector3 oldPos = child.RawPosition;
child.ForcePosition = LinksetRoot.RawPosition + lci.OffsetFromRoot;
child.ForceOrientation = LinksetRoot.RawOrientation * lci.OffsetRot;
DetailLog("{0},BSLinksetCompound.RecomputeChildWorldPosition,oldPos={1},lci={2},newPos={3}",
child.LocalID, oldPos, lci, child.RawPosition);
}
else
{
// TaintedObject is not used here so the raw position is set now and not at taint-time.
child.Position = LinksetRoot.RawPosition + lci.OffsetFromRoot;
child.Orientation = LinksetRoot.RawOrientation * lci.OffsetRot;
}
}
else
{
// This happens when children have been added to the linkset but the linkset
// has not been constructed yet. So like, at taint time, adding children to a linkset
// and then changing properties of the children (makePhysical, for instance)
// but the post-print action of actually rebuilding the linkset has not yet happened.
// PhysicsScene.Logger.WarnFormat("{0} Restoring linkset child position failed because of no relative position computed. ID={1}",
// LogHeader, child.LocalID);
DetailLog("{0},BSLinksetCompound.recomputeChildWorldPosition,noRelativePositonInfo", child.LocalID);
}
*/
}
// ================================================================
// Add a new child to the linkset.
// Called while LinkActivity is locked.
protected override void AddChildToLinkset(BSPrimLinkable child)
{
if (!HasChild(child))
{
m_children.Add(child);
DetailLog("{0},BSLinksetCompound.AddChildToLinkset,call,child={1}", LinksetRoot.LocalID, child.LocalID);
// Rebuild the compound shape with the new child shape included
ScheduleRebuild(child);
}
return;
}
// Remove the specified child from the linkset.
// Safe to call even if the child is not really in the linkset.
protected override void RemoveChildFromLinkset(BSPrimLinkable child)
{
child.ClearDisplacement();
if (m_children.Remove(child))
{
DetailLog("{0},BSLinksetCompound.RemoveChildFromLinkset,call,rID={1},rBody={2},cID={3},cBody={4}",
child.LocalID,
LinksetRoot.LocalID, LinksetRoot.PhysBody.AddrString,
child.LocalID, child.PhysBody.AddrString);
// Cause the child's body to be rebuilt and thus restored to normal operation
RecomputeChildWorldPosition(child, false);
child.LinksetInfo = null;
child.ForceBodyShapeRebuild(false);
if (!HasAnyChildren)
{
// The linkset is now empty. The root needs rebuilding.
LinksetRoot.ForceBodyShapeRebuild(false);
}
else
{
// Rebuild the compound shape with the child removed
ScheduleRebuild(LinksetRoot);
}
}
return;
}
// Called before the simulation step to make sure the compound based linkset
// is all initialized.
// Constraint linksets are rebuilt every time.
// Note that this works for rebuilding just the root after a linkset is taken apart.
// Called at taint time!!
private bool disableCOM = true; // DEBUG DEBUG: disable until we get this debugged
private void RecomputeLinksetCompound()
{
try
{
// Suppress rebuilding while rebuilding. (We know rebuilding is on only one thread.)
Rebuilding = true;
// Cause the root shape to be rebuilt as a compound object with just the root in it
LinksetRoot.ForceBodyShapeRebuild(true /* inTaintTime */);
// The center of mass for the linkset is the geometric center of the group.
// Compute a displacement for each component so it is relative to the center-of-mass.
// Bullet presumes an object's origin (relative <0,0,0>) is its center-of-mass
OMV.Vector3 centerOfMassW = LinksetRoot.RawPosition;
if (!disableCOM) // DEBUG DEBUG
{
// Compute a center-of-mass in world coordinates.
centerOfMassW = ComputeLinksetCenterOfMass();
}
OMV.Quaternion invRootOrientation = OMV.Quaternion.Inverse(LinksetRoot.RawOrientation);
// 'centerDisplacement' is the value to subtract from children to give physical offset position
OMV.Vector3 centerDisplacement = (centerOfMassW - LinksetRoot.RawPosition) * invRootOrientation;
LinksetRoot.SetEffectiveCenterOfMassW(centerDisplacement);
// This causes the physical position of the root prim to be offset to accomodate for the displacements
LinksetRoot.ForcePosition = LinksetRoot.RawPosition;
// Update the local transform for the root child shape so it is offset from the <0,0,0> which is COM
PhysicsScene.PE.UpdateChildTransform(LinksetRoot.PhysShape, 0 /* childIndex */,
-centerDisplacement,
OMV.Quaternion.Identity, // LinksetRoot.RawOrientation,
false /* shouldRecalculateLocalAabb (is done later after linkset built) */);
DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,COM,com={1},rootPos={2},centerDisp={3}",
LinksetRoot.LocalID, centerOfMassW, LinksetRoot.RawPosition, centerDisplacement);
DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,start,rBody={1},rShape={2},numChildren={3}",
LinksetRoot.LocalID, LinksetRoot.PhysBody, LinksetRoot.PhysShape, NumberOfChildren);
// Add a shape for each of the other children in the linkset
int memberIndex = 1;
ForEachMember(delegate(BSPrimLinkable cPrim)
{
if (IsRoot(cPrim))
{
cPrim.LinksetChildIndex = 0;
}
else
{
cPrim.LinksetChildIndex = memberIndex;
if (cPrim.PhysShape.isNativeShape)
{
// A native shape is turned into a hull collision shape because native
// shapes are not shared so we have to hullify it so it will be tracked
// and freed at the correct time. This also solves the scaling problem
// (native shapes scale but hull/meshes are assumed to not be).
// TODO: decide of the native shape can just be used in the compound shape.
// Use call to CreateGeomNonSpecial().
BulletShape saveShape = cPrim.PhysShape;
cPrim.PhysShape.Clear(); // Don't let the create free the child's shape
PhysicsScene.Shapes.CreateGeomMeshOrHull(cPrim, null);
BulletShape newShape = cPrim.PhysShape;
cPrim.PhysShape = saveShape;
OMV.Vector3 offsetPos = (cPrim.RawPosition - LinksetRoot.RawPosition) * invRootOrientation - centerDisplacement;
OMV.Quaternion offsetRot = cPrim.RawOrientation * invRootOrientation;
PhysicsScene.PE.AddChildShapeToCompoundShape(LinksetRoot.PhysShape, newShape, offsetPos, offsetRot);
DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,addNative,indx={1},rShape={2},cShape={3},offPos={4},offRot={5}",
LinksetRoot.LocalID, memberIndex, LinksetRoot.PhysShape, newShape, offsetPos, offsetRot);
}
else
{
// For the shared shapes (meshes and hulls), just use the shape in the child.
// The reference count added here will be decremented when the compound shape
// is destroyed in BSShapeCollection (the child shapes are looped over and dereferenced).
if (PhysicsScene.Shapes.ReferenceShape(cPrim.PhysShape))
{
PhysicsScene.Logger.ErrorFormat("{0} Rebuilt sharable shape when building linkset! Region={1}, primID={2}, shape={3}",
LogHeader, PhysicsScene.RegionName, cPrim.LocalID, cPrim.PhysShape);
}
OMV.Vector3 offsetPos = (cPrim.RawPosition - LinksetRoot.RawPosition) * invRootOrientation - centerDisplacement;
OMV.Quaternion offsetRot = cPrim.RawOrientation * invRootOrientation;
PhysicsScene.PE.AddChildShapeToCompoundShape(LinksetRoot.PhysShape, cPrim.PhysShape, offsetPos, offsetRot);
DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,addNonNative,indx={1},rShape={2},cShape={3},offPos={4},offRot={5}",
LinksetRoot.LocalID, memberIndex, LinksetRoot.PhysShape, cPrim.PhysShape, offsetPos, offsetRot);
}
memberIndex++;
}
return false; // 'false' says to move onto the next child in the list
});
// With all of the linkset packed into the root prim, it has the mass of everyone.
LinksetMass = ComputeLinksetMass();
LinksetRoot.UpdatePhysicalMassProperties(LinksetMass, true);
// Enable the physical position updator to return the position and rotation of the root shape
PhysicsScene.PE.AddToCollisionFlags(LinksetRoot.PhysBody, CollisionFlags.BS_RETURN_ROOT_COMPOUND_SHAPE);
}
finally
{
Rebuilding = false;
}
// See that the Aabb surrounds the new shape
PhysicsScene.PE.RecalculateCompoundShapeLocalAabb(LinksetRoot.PhysShape);
}
}
}
| |
/*
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 java.lang;
using java.util;
using stab.query;
using stab.reflection;
using cnatural.syntaxtree;
namespace cnatural.compiler {
class StatementScope {
StatementScope next;
StatementNode statement;
private HashMap<String, StatementNode> labels;
StatementScope(StatementNode statement, StatementScope next) {
this.statement = statement;
this.next = next;
}
void declareLabel(String name, StatementNode statement) {
if (labels == null) {
labels = new HashMap<String, StatementNode>();
}
labels[name] = statement;
}
StatementNode getLabeledStatement(String name) {
var s = this;
do {
if (s.labels != null) {
var ls = s.labels[name];
if (ls != null) {
return ls;
}
}
} while ((s = s.next) != null);
return null;
}
}
class InitializedLocalInfo {
LocalMemberInfo local;
LocalDeclarationStatementNode declaration;
InitializedLocalInfo(LocalMemberInfo local, LocalDeclarationStatementNode declaration) {
this.local = local;
this.declaration = declaration;
}
}
class UninitializedLocalInfo {
LocalMemberInfo local;
LocalDeclarationStatementNode declaration;
int referenceCount;
int assignmentCount;
UninitializedLocalInfo(LocalMemberInfo local, LocalDeclarationStatementNode declaration) {
this.local = local;
this.declaration = declaration;
}
}
class ReachabilityChecker : StatementHandler<Void, StatementInfo> {
private CompilerContext context;
private ExpressionChecker expressionChecker;
private UnreachableStatementsHandler unreachableStatementsHandler;
private HashMap<LocalMemberInfo, UninitializedLocalInfo> uninitializedLocals;
private HashMap<LocalMemberInfo, InitializedLocalInfo> initializedLocals;
ReachabilityChecker(CompilerContext context)
: super(true) {
this.context = context;
this.expressionChecker = new ExpressionChecker(this, context);
this.unreachableStatementsHandler = new UnreachableStatementsHandler(context);
}
Iterable<UninitializedLocalInfo> checkMethod(MethodInfo method, BlockStatementNode body, bool insertReturn) {
uninitializedLocals = new HashMap<LocalMemberInfo, UninitializedLocalInfo>();
initializedLocals = new HashMap<LocalMemberInfo, InitializedLocalInfo>();
var info = handleStatement(body, null);
if (insertReturn && info.IsEndPointReachable) {
if (method.ReturnType == context.TypeSystem.VoidType) {
var returnStatement = new ReturnStatementNode();
returnStatement.addUserData(new StatementInfo());
body.Statements.add(returnStatement);
} else if (context.Iterables[method] != null) {
var yieldStatement = new YieldStatementNode();
yieldStatement.addUserData(new StatementInfo());
body.Statements.add(yieldStatement);
} else {
context.addError(CompileErrorId.MissingReturn, method.getUserData(typeof(SyntaxNode)));
}
}
info.YieldCount = context.CodeValidationContext.YieldCount;
context.CodeValidationContext.YieldCount = 0;
foreach (var local in initializedLocals.values()) {
context.addWarning(CompileErrorId.VariableNeverUsed, local.declaration, local.local.Name);
}
unreachableStatementsHandler.handleStatement(body, null);
return uninitializedLocals.values();
}
static bool isEndPointReachable(StatementNode statement) {
var info = statement.getUserData(typeof(StatementInfo));
return (info == null) ? false : info.IsEndPointReachable;
}
protected override StatementInfo handleBlock(BlockStatementNode block, Void source) {
var scope = new StatementScope(block, block.getUserData(typeof(StatementScope)));
var info = new StatementInfo();
block.addOrReplaceUserData(info);
int size = block.Statements.size();
if (size > 0) {
visitStatements(block.Statements, scope);
var reachable = isEndPointReachable(block.Statements[size - 1]);
info.IsEndPointReachable = reachable;
if (!reachable) {
block.removeUserData(typeof(StatementNode));
}
} else {
info.IsEndPointReachable = true;
}
return info;
}
protected override StatementInfo handleBreak(BreakStatementNode breakStatement, Void source) {
var info = new StatementInfo();
breakStatement.addOrReplaceUserData(info);
var done = false;
var enclosingStatements = breakStatement.getUserData(typeof(StatementScope));
while (enclosingStatements != null && !done) {
var node = enclosingStatements.statement;
switch (node.StatementKind) {
case Do:
case For:
case Foreach:
case Switch:
case While:
done = true;
info.Target = node.getUserData(typeof(StatementNode));
breakStatement.removeUserData(typeof(StatementNode));
var sinfo = node.getUserData(typeof(StatementInfo));
sinfo.IsEndPointReachable = true;
if (info.Target != null) {
visitStatement(info.Target);
var tinfo = info.Target.getUserData(typeof(StatementInfo));
tinfo.IsTargeted = true;
} else {
node.getUserData(typeof(StatementInfo)).IsTargeted = true;
}
break;
}
enclosingStatements = enclosingStatements.next;
}
if (!done) {
throw context.error(CompileErrorId.BreakOutsideLoop, breakStatement);
}
return info;
}
protected override StatementInfo handleContinue(ContinueStatementNode continueStatement, Void source) {
var info = new StatementInfo();
continueStatement.addOrReplaceUserData(info);
var done = false;
var enclosingStatements = continueStatement.getUserData(typeof(StatementScope));
while (enclosingStatements != null && !done) {
var node = enclosingStatements.statement;
switch (node.StatementKind) {
case Do:
case For:
case Foreach:
case While:
done = true;
info.Target = node;
continueStatement.removeUserData(typeof(StatementNode));
var sinfo = node.getUserData(typeof(StatementInfo));
sinfo.IsTargeted = true;
break;
}
enclosingStatements = enclosingStatements.next;
}
if (!done) {
throw context.error(CompileErrorId.ContinueOutsideLoop, continueStatement);
}
return info;
}
protected override StatementInfo handleDo(DoStatementNode doStatement, Void source) {
var enclosingStatements = new StatementScope(doStatement, doStatement.getUserData(typeof(StatementScope)));
var info = new StatementInfo();
doStatement.addOrReplaceUserData(info);
doStatement.Statement.addOrReplaceUserData(enclosingStatements);
var cinfo = doStatement.Condition.getUserData(typeof(ExpressionInfo));
if (cinfo.IsConstant) {
var value = (Boolean)cinfo.getValue();
info.IsEndPointReachable = !value;
doStatement.Statement.addOrReplaceUserData(enclosingStatements);
handleStatement(doStatement.Statement, null);
} else {
doStatement.Statement.addOrReplaceUserData(enclosingStatements);
handleStatement(doStatement.Statement, null);
if (!info.IsEndPointReachable) {
info.IsEndPointReachable = isEndPointReachable(doStatement.Statement);
}
}
if (!info.IsEndPointReachable) {
doStatement.removeUserData(typeof(StatementNode));
}
expressionChecker.handleExpression(doStatement.Condition, null, true);
return info;
}
protected override StatementInfo handleEmpty(EmptyStatementNode empty, Void source) {
var info = new StatementInfo();
empty.addOrReplaceUserData(info);
info.IsEndPointReachable = true;
return info;
}
protected override StatementInfo handleExpression(ExpressionStatementNode expression, Void source) {
var info = new StatementInfo();
expression.addOrReplaceUserData(info);
info.IsEndPointReachable = true;
expressionChecker.handleExpression(expression.Expression, null, false);
return info;
}
protected override StatementInfo handleFor(ForStatementNode forStatement, Void source) {
var enclosingStatements = new StatementScope(forStatement, forStatement.getUserData(typeof(StatementScope)));
var info = new StatementInfo();
forStatement.addOrReplaceUserData(info);
foreach (var s in forStatement.Initializer) {
handleStatement(s, null);
}
if (forStatement.Iterator.any()) {
linkStatements(Collections.singletonList<StatementNode>(forStatement.Statement).concat(forStatement.Iterator), enclosingStatements);
}
if (forStatement.Condition != null) {
var cinfo = forStatement.Condition.getUserData(typeof(ExpressionInfo));
if (cinfo.IsConstant) {
var value = (Boolean)cinfo.Value;
info.IsEndPointReachable = !value;
if (value) {
forStatement.Statement.addOrReplaceUserData(enclosingStatements);
visitStatement(forStatement.Statement);
}
} else {
expressionChecker.handleExpression(forStatement.Condition, null, true);
info.IsEndPointReachable = true;
forStatement.Statement.addOrReplaceUserData(enclosingStatements);
visitStatement(forStatement.Statement);
}
} else {
info.IsEndPointReachable = false;
forStatement.Statement.addOrReplaceUserData(enclosingStatements);
visitStatement(forStatement.Statement);
}
return info;
}
protected override StatementInfo handleForeach(ForeachStatementNode foreachStatement, Void source) {
var enclosingStatements = new StatementScope(foreachStatement, foreachStatement.getUserData(typeof(StatementScope)));
var info = new StatementInfo();
foreachStatement.addOrReplaceUserData(info);
foreachStatement.Statement.addOrReplaceUserData(enclosingStatements);
info.IsEndPointReachable = true;
expressionChecker.handleExpression(foreachStatement.Source, null, true);
handleStatement(foreachStatement.Statement, null);
return info;
}
protected override StatementInfo handleGoto(GotoStatementNode gotoStatement, Void source) {
var info = new StatementInfo();
gotoStatement.addOrReplaceUserData(info);
gotoStatement.removeUserData(typeof(StatementNode));
var enclosingStatements = gotoStatement.getUserData(typeof(StatementScope));
var label = context.getIdentifier(gotoStatement.LabelOffset, gotoStatement.LabelLength);
// TODO: check label redefinition
var target = enclosingStatements.getLabeledStatement(label);
if (target == null) {
throw context.error(CompileErrorId.UnresolvedLabel, gotoStatement, label);
}
visitStatement(target);
info.Target = target;
var tinfo = target.getUserData(typeof(StatementInfo));
tinfo.IsTargeted = true;
return info;
}
protected override StatementInfo handleGotoCase(GotoCaseStatementNode gotoCase, Void source) {
var info = new StatementInfo();
gotoCase.addOrReplaceUserData(info);
gotoCase.removeUserData(typeof(StatementNode));
var done = false;
List<StatementNode> target = null;
var enclosingStatements = gotoCase.getUserData(typeof(StatementScope));
while (enclosingStatements != null && !done) {
var node = enclosingStatements.statement;
if (node.StatementKind == StatementKind.Switch) {
done = true;
var addNext = false;
var gotoDefault = gotoCase.Expression == null;
var sinfo = (gotoDefault) ? null : gotoCase.Expression.getUserData(typeof(ExpressionInfo));
String enumField = null;
if (!gotoDefault && sinfo == null) {
var name = (SimpleNameExpressionNode)gotoCase.Expression;
enumField = context.getIdentifier(name.NameOffset, name.NameLength);
}
foreach (var section in ((SwitchStatementNode)node).Sections) {
if (addNext) {
if (!section.Statements.isEmpty()) {
target = section.Statements;
break;
}
} else {
if (section.CaseExpression == null) {
if (gotoDefault) {
if (section.Statements.isEmpty()) {
addNext = true;
} else {
target = section.Statements;
break;
}
}
} else if (gotoCase.Expression != null) {
var ordinalValue = section.CaseExpression.getUserData(typeof(Integer));
if (ordinalValue != null) {
var name = (SimpleNameExpressionNode)section.CaseExpression;
var label = context.getIdentifier(name.NameOffset, name.NameLength);
if (label.equals(enumField)) {
if (section.Statements.isEmpty()) {
addNext = true;
} else {
target = section.Statements;
break;
}
}
} else {
var cinfo = section.CaseExpression.getUserData(typeof(ExpressionInfo));
if (sinfo == null) {
if (cinfo == null) {
if (section.Statements.isEmpty()) {
addNext = true;
} else {
target = section.Statements;
break;
}
}
} else if (cinfo != null) {
if (sinfo.Type.IsNumeric) {
int svalue;
if (sinfo.Value instanceof Character) {
svalue = ((Character)sinfo.Value).charValue();
} else {
svalue = ((Number)sinfo.Value).intValue();
}
int cvalue;
if (cinfo.Value instanceof Character) {
cvalue = ((Character)cinfo.Value).charValue();
} else {
cvalue = ((Number)cinfo.Value).intValue();
}
if (svalue == cvalue) {
if (section.Statements.isEmpty()) {
addNext = true;
} else {
target = section.Statements;
break;
}
}
} else if (sinfo.Value.equals(cinfo.Value)) {
if (section.Statements.isEmpty()) {
addNext = true;
} else {
target = section.Statements;
break;
}
}
}
}
}
}
}
}
enclosingStatements = enclosingStatements.next;
}
if (!done) {
throw context.error(CompileErrorId.InvalidGotoCase, gotoCase);
}
if (target == null) {
throw context.error(CompileErrorId.UnknownGotoLabel, gotoCase);
}
visitStatement(target[0]);
info.Target = target[0];
var tinfo = target[0].getUserData(typeof(StatementInfo));
tinfo.IsTargeted = true;
return info;
}
protected override StatementInfo handleIf(IfStatementNode ifStatement, Void source) {
var scope = new StatementScope(ifStatement, ifStatement.getUserData(typeof(StatementScope)));
var info = new StatementInfo();
var condition = ifStatement.Condition;
var ifTrue = ifStatement.IfTrue;
var ifFalse = ifStatement.IfFalse;
var cinfo = condition.getUserData(typeof(ExpressionInfo));
ifStatement.addOrReplaceUserData(info);
ifTrue.addOrReplaceUserData(scope);
if (ifFalse != null) {
ifFalse.addOrReplaceUserData(scope);
}
if (cinfo.IsConstant) {
if ((Boolean)cinfo.Value) {
var tinfo = handleStatement(ifTrue, null);
info.IsEndPointReachable = tinfo.IsEndPointReachable;
} else {
if (ifFalse != null) {
var finfo = handleStatement(ifFalse, null);
info.IsEndPointReachable = finfo.IsEndPointReachable;
} else {
info.IsEndPointReachable = true;
}
}
} else {
expressionChecker.handleExpression(condition, null, true);
var tinfo = handleStatement(ifTrue, null);
if (ifFalse != null) {
var finfo = handleStatement(ifFalse, null);
info.IsEndPointReachable = tinfo.IsEndPointReachable || finfo.IsEndPointReachable;
} else {
info.IsEndPointReachable = true;
}
}
return info;
}
protected override StatementInfo handleLabeled(LabeledStatementNode labeled, Void source) {
var info = new StatementInfo();
labeled.addOrReplaceUserData(info);
var statement = labeled.Statement;
statement.addOrReplaceUserData(labeled.getUserData(typeof(StatementScope)));
handleStatement(statement, null);
info.IsEndPointReachable = statement.getUserData(typeof(StatementInfo)).IsEndPointReachable;
return info;
}
protected override StatementInfo handleLocalDeclaration(LocalDeclarationStatementNode localDeclaration, Void source) {
var info = new StatementInfo();
localDeclaration.addOrReplaceUserData(info);
info.IsEndPointReachable = true;
foreach (var decl in localDeclaration.Declarators) {
var local = decl.getUserData(typeof(LocalMemberInfo));
if (decl.Value != null) {
initializedLocals[local] = new InitializedLocalInfo(local, localDeclaration);
expressionChecker.handleExpression(decl.Value, null, true);
} else {
uninitializedLocals[local] = new UninitializedLocalInfo(local, localDeclaration);
}
}
return info;
}
protected override StatementInfo handleReturn(ReturnStatementNode returnStatement, Void source) {
if (context.Iterables[context.CodeValidationContext.CurrentMethod] != null) {
context.addError(CompileErrorId.ReturnInsideIterator, returnStatement);
}
returnStatement.removeUserData(typeof(StatementNode));
var info = new StatementInfo();
returnStatement.addOrReplaceUserData(info);
if (returnStatement.Value != null) {
expressionChecker.handleExpression(returnStatement.Value, null, true);
}
return info;
}
protected override StatementInfo handleSwitch(SwitchStatementNode switchStatement, Void source) {
var enclosingStatements = new StatementScope(switchStatement, switchStatement.getUserData(typeof(StatementScope)));
var info = new StatementInfo();
switchStatement.addOrReplaceUserData(info);
expressionChecker.handleExpression(switchStatement.Selector, null, true);
if (switchStatement.Sections.isEmpty()) {
info.IsEndPointReachable = true;
} else {
var sinfo = switchStatement.Selector.getUserData(typeof(ExpressionInfo));
var isConstant = sinfo.IsConstant;
var reachableStatements = new ArrayList<List<StatementNode>>();
List<StatementNode> defaultStatements = null;
var hasReachableCase = false;
var addNext = false;
foreach (var section in switchStatement.Sections) {
if (section.Statements.isEmpty()) {
continue;
}
linkStatements(section.Statements, enclosingStatements);
if (section.CaseExpression == null) {
defaultStatements = section.Statements;
addNext = section.Statements.isEmpty();
} else if (isConstant && !addNext) {
var einfo = section.CaseExpression.getUserData(typeof(ExpressionInfo));
if (einfo.Value.equals(sinfo.Value)) {
reachableStatements.add(section.Statements);
hasReachableCase = true;
addNext = section.Statements.isEmpty();
}
} else {
hasReachableCase = true;
reachableStatements.add(section.Statements);
addNext = section.Statements.isEmpty();
}
}
if ((!isConstant || !hasReachableCase) && defaultStatements != null && defaultStatements.size() > 0) {
reachableStatements.add(defaultStatements);
}
foreach (var stmts in reachableStatements) {
visitStatement(stmts[0]);
if (isEndPointReachable(stmts[stmts.size() - 1])) {
throw context.error(CompileErrorId.CaseFallThrough, stmts[stmts.size() - 1]);
}
}
if (!info.IsEndPointReachable && !isConstant) {
if (defaultStatements == null) {
info.IsEndPointReachable = true;
}
}
if (hasReachableCase) {
if (sinfo.Type.IsNumeric) {
var sections = new ArrayList<SwitchSectionNode>();
var cases = new ArrayList<Number>();
foreach (var section in switchStatement.Sections) {
if (section.CaseExpression == null) {
continue;
}
if (section.Statements.isEmpty() || section.Statements[0].getUserData(typeof(StatementInfo)) != null) {
sections.add(section);
var si = section.CaseExpression.getUserData(typeof(ExpressionInfo));
Object caseValue = si.Value;
if (caseValue instanceof Character) {
var nb = Integer.valueOf(((Character)caseValue).charValue());
si.Value = nb;
cases.add(nb);
} else {
cases.add((Number)caseValue);
}
}
}
for (int i = 0; i < cases.size(); i++) {
int value = cases[i].intValue();
for (int j = i + 1; j < cases.size(); j++) {
if (value == cases[j].intValue()) {
throw context.error(CompileErrorId.DuplicateCase, sections[j]);
}
}
}
} else if (!sinfo.Type.IsEnum) {
var sections = new ArrayList<SwitchSectionNode>();
var cases = new ArrayList<String>();
foreach (var section in switchStatement.Sections) {
if (section.CaseExpression == null) {
continue;
}
if (section.Statements.isEmpty() || section.Statements[0].getUserData(typeof(StatementInfo)) != null) {
sections.add(section);
var cinfo = section.CaseExpression.getUserData(typeof(ExpressionInfo));
if (cinfo == null) {
cases.add(null);
} else {
cases.add((String)cinfo.Value);
}
}
}
for (int i = 0; i < cases.size(); i++) {
String value = cases[i];
for (int j = i + 1; j < cases.size(); j++) {
if ((value == null && cases[j] == null) || (value != null && value.equals(cases[j]))) {
throw context.error(CompileErrorId.DuplicateCase, sections[j]);
}
}
}
}
}
}
return info;
}
protected override StatementInfo handleSynchronized(SynchronizedStatementNode synchronizedStatement, Void source) {
var enclosingStatements = new StatementScope(synchronizedStatement, synchronizedStatement.getUserData(typeof(StatementScope)));
var info = new StatementInfo();
synchronizedStatement.addOrReplaceUserData(info);
expressionChecker.handleExpression(synchronizedStatement.Lock, null, true);
synchronizedStatement.Statement.addOrReplaceUserData(enclosingStatements);
handleStatement(synchronizedStatement.Statement, null);
info.IsEndPointReachable = synchronizedStatement.Statement.getUserData(typeof(StatementInfo)).IsEndPointReachable;
return info;
}
protected override StatementInfo handleThrow(ThrowStatementNode throwStatement, Void source) {
var info = new StatementInfo();
throwStatement.addOrReplaceUserData(info);
if (throwStatement.Exception != null) {
expressionChecker.handleExpression(throwStatement.Exception, null, true);
}
throwStatement.removeUserData(typeof(StatementNode));
return info;
}
protected override StatementInfo handleTry(TryStatementNode tryStatement, Void source) {
var enclosingStatements = new StatementScope(tryStatement, tryStatement.getUserData(typeof(StatementScope)));
var info = new StatementInfo();
tryStatement.addOrReplaceUserData(info);
tryStatement.Block.addOrReplaceUserData(enclosingStatements);
handleStatement(tryStatement.Block, null);
bool isEndPointReachable = tryStatement.Block.getUserData(typeof(StatementInfo)).IsEndPointReachable;
foreach (var node in tryStatement.CatchClauses) {
var stmts = node.Block.Statements;
if (stmts.size() > 0) {
visitStatements(stmts, enclosingStatements);
if (!isEndPointReachable) {
isEndPointReachable = stmts[stmts.size() - 1].getUserData(typeof(StatementInfo)).IsEndPointReachable;
}
}
}
if (tryStatement.Finally != null) {
handleStatement(tryStatement.Finally, source);
tryStatement.Finally.getUserData(typeof(StatementInfo)).IsEndPointReachable = false;
}
info.IsEndPointReachable = isEndPointReachable;
return info;
}
protected override StatementInfo handleUsing(UsingStatementNode usingStatement, Void source) {
var enclosingStatements = new StatementScope(usingStatement, usingStatement.getUserData(typeof(StatementScope)));
var info = new StatementInfo();
usingStatement.addOrReplaceUserData(info);
usingStatement.ResourceAcquisition.addOrReplaceUserData(enclosingStatements);
usingStatement.Statement.addOrReplaceUserData(enclosingStatements);
handleStatement(usingStatement.ResourceAcquisition, null);
handleStatement(usingStatement.Statement, null);
info.IsEndPointReachable = usingStatement.Statement.getUserData(typeof(StatementInfo)).IsEndPointReachable;
return info;
}
protected override StatementInfo handleWhile(WhileStatementNode whileStatement, Void source) {
var enclosingStatements = new StatementScope(whileStatement, whileStatement.getUserData(typeof(StatementScope)));
var info = new StatementInfo();
whileStatement.addOrReplaceUserData(info);
whileStatement.Statement.addOrReplaceUserData(enclosingStatements);
var cinfo = whileStatement.Condition.getUserData(typeof(ExpressionInfo));
if (cinfo.IsConstant) {
var value = (Boolean)cinfo.Value;
info.IsEndPointReachable = !value;
if (value) {
whileStatement.Statement.addOrReplaceUserData(enclosingStatements);
handleStatement(whileStatement.Statement, null);
}
} else {
expressionChecker.handleExpression(whileStatement.Condition, null, true);
info.IsEndPointReachable = true;
whileStatement.Statement.addOrReplaceUserData(enclosingStatements);
handleStatement(whileStatement.Statement, null);
}
return info;
}
protected override StatementInfo handleYield(YieldStatementNode yieldStatement, Void source) {
var info = new StatementInfo();
info.IsEndPointReachable = yieldStatement.Value != null;
yieldStatement.addOrReplaceUserData(info);
if (yieldStatement.Value != null) {
expressionChecker.handleExpression(yieldStatement.Value, null, true);
context.CodeValidationContext.YieldCount++;
} else {
yieldStatement.removeUserData(typeof(StatementNode));
}
return info;
}
private void visitStatements(List<StatementNode> statements, StatementScope scope) {
if (!statements.isEmpty()) {
linkStatements(statements, scope);
visitStatement(statements[0]);
}
}
private void linkStatements(Iterable<StatementNode> statements, StatementScope scope) {
StatementNode previous = null;
foreach (var s in statements) {
if (s.StatementKind == StatementKind.Labeled) {
var ls = (LabeledStatementNode)s;
scope.declareLabel(context.getIdentifier(ls.NameOffset, ls.NameLength), ls);
}
s.addOrReplaceUserData(scope);
if (previous != null) {
previous.addOrReplaceUserData(s);
}
previous = s;
}
}
private void visitStatement(StatementNode statement) {
while (statement != null && statement.getUserData(typeof(StatementInfo)) == null) {
var info = handleStatement(statement, null);
if (info.IsEndPointReachable) {
statement = statement.getUserData(typeof(StatementNode));
}
}
}
private class ExpressionChecker : ExpressionHandler<Void, Void> {
private ReachabilityChecker statementChecker;
private CompilerContext context;
ExpressionChecker(ReachabilityChecker statementChecker, CompilerContext context)
: super(true) {
this.statementChecker = statementChecker;
this.context = context;
}
protected override Void handleAnonymousObjectCreation(AnonymousObjectCreationExpressionNode anonymousObject,
Void source, bool nested) {
foreach (var decl in anonymousObject.MemberDeclarators) {
handleExpression(decl.Value, null, true);
}
return null;
}
protected override Void handleArrayCreation(ArrayCreationExpressionNode arrayCreation, Void source, bool nested) {
foreach (var e in arrayCreation.DimensionExpressions) {
handleExpression(e, null, true);
}
if (arrayCreation.Initializer != null) {
handleExpression(arrayCreation.Initializer, null, true);
}
return null;
}
protected override Void handleArrayInitializer(ArrayInitializerExpressionNode arrayInitializer, Void source, bool nested) {
foreach (var e in arrayInitializer.Values) {
handleExpression(e, null, true);
}
return null;
}
protected override Void handleAssign(AssignExpressionNode assign, Void source, bool nested) {
if (assign.Left.ExpressionKind == ExpressionKind.SimpleName) {
var linfo = assign.Left.getUserData(typeof(ExpressionInfo));
var member = linfo.Member;
if (member.MemberKind == MemberKind.Local) {
var minfo = statementChecker.uninitializedLocals[member];
if (minfo != null) {
minfo.assignmentCount++;
if (assign.Operator != AssignOperator.Assign) {
minfo.referenceCount++;
}
}
if (statementChecker.initializedLocals.containsKey(member)) {
statementChecker.initializedLocals.remove(member);
}
}
} else {
handleExpression(assign.Left, null, true);
}
handleExpression(assign.Right, null, true);
return null;
}
protected override Void handleBinary(BinaryExpressionNode binary, Void source, bool nested) {
handleExpression(binary.LeftOperand, null, true);
handleExpression(binary.RightOperand, null, true);
return null;
}
protected override Void handleCast(CastExpressionNode cast, Void source, bool nested) {
handleExpression(cast.Expression, null, true);
return null;
}
protected override Void handleConditional(ConditionalExpressionNode conditional, Void source, bool nested) {
handleExpression(conditional.Condition, null, true);
handleExpression(conditional.IfTrue, null, true);
handleExpression(conditional.IfFalse, null, true);
return null;
}
protected override Void handleElementAccess(ElementAccessExpressionNode elementAccess, Void source, bool nested) {
handleExpression(elementAccess.TargetObject, null, true);
foreach (var arg in elementAccess.Indexes) {
handleExpression(arg, null, true);
}
return null;
}
protected override Void handleInvocation(InvocationExpressionNode invocation, Void source, bool nested) {
handleExpression(invocation.TargetObject, null, true);
foreach (var arg in invocation.Arguments) {
handleExpression(arg, null, true);
}
return null;
}
protected override Void handleLambda(LambdaExpressionNode lambda, Void source, bool nested) {
var methodBuilder = lambda.getUserData(typeof(MethodBuilder));
if (lambda.Body instanceof BlockStatementNode) {
var body = (BlockStatementNode)lambda.Body;
var info = statementChecker.handleStatement(body, null);
if (info.IsEndPointReachable) {
if (methodBuilder.ReturnType == context.TypeSystem.VoidType) {
var returnStatement = new ReturnStatementNode();
returnStatement.addOrReplaceUserData(new StatementInfo());
body.Statements.add(returnStatement);
} else if (context.Iterables[methodBuilder] != null) {
var yieldStatement = new YieldStatementNode();
yieldStatement.addOrReplaceUserData(new StatementInfo());
body.Statements.add(yieldStatement);
} else {
context.addError(CompileErrorId.MissingReturn, lambda);
}
}
} else {
handleExpression(((ExpressionStatementNode)lambda.Body).Expression, null, true);
lambda.Body.addOrReplaceUserData(new StatementInfo());
}
return null;
}
protected override Void handleLiteral(LiteralExpressionNode literal, Void source, bool nested) {
return null;
}
protected override Void handleMemberAccess(MemberAccessExpressionNode memberAccess, Void source, bool nested) {
handleExpression(memberAccess.TargetObject, null, true);
return null;
}
protected override Void handleObjectCreation(ObjectCreationExpressionNode objectCreation, Void source, bool nested) {
foreach (var arg in objectCreation.Arguments) {
handleExpression(arg, null, true);
}
var init = objectCreation.Initializer;
if (init != null) {
if (init.ExpressionKind == ExpressionKind.ObjectInitializer) {
var initializer = (ObjectInitializerExpressionNode)init;
foreach (var mi in initializer.MemberInitializers) {
handleExpression(mi.Value, null, true);
}
} else {
var initializer = (CollectionInitializerExpressionNode)init;
foreach (var args in initializer.Values) {
foreach (var e in args) {
handleExpression(e, null, true);
}
}
}
}
return null;
}
protected override Void handleSimpleName(SimpleNameExpressionNode simpleName, Void source, bool nested) {
var info = simpleName.getUserData(typeof(ExpressionInfo));
var minfo = statementChecker.uninitializedLocals[info.Member];
if (minfo != null) {
minfo.referenceCount++;
}
if (statementChecker.initializedLocals.containsKey(info.Member)) {
statementChecker.initializedLocals.remove(info.Member);
}
return null;
}
protected override Void handleSizeof(SizeofExpressionNode sizeofExpression, Void source, bool nested) {
handleExpression(sizeofExpression.Expression, null, true);
return null;
}
protected override Void handleSuperAccess(SuperAccessExpressionNode superAccess, Void source, bool nested) {
return null;
}
protected override Void handleThisAccess(ThisAccessExpressionNode thisAccess, Void source, bool nested) {
return null;
}
protected override Void handleType(TypeExpressionNode type, Void source, bool nested) {
return null;
}
protected override Void handleTypeof(TypeofExpressionNode typeofExpression, Void source, bool nested) {
return null;
}
protected override Void handleUnary(UnaryExpressionNode unary, Void source, bool nested) {
handleExpression(unary.Operand, null, true);
return null;
}
}
private class UnreachableStatementsHandler : StatementHandler<Void, Void> {
private CompilerContext context;
private ExpressionChecker expressionChecker;
UnreachableStatementsHandler(CompilerContext context)
: super(true) {
this.context = context;
this.expressionChecker = new ExpressionChecker(this, context);
}
protected override Void handleBlock(BlockStatementNode block, Void source) {
var info = block.getUserData(typeof(StatementInfo));
if (info == null) {
context.addWarning(CompileErrorId.UnreachableStatement, block);
} else {
foreach (var s in block.Statements) {
handleStatement(s, null);
}
}
return null;
}
protected override Void handleBreak(BreakStatementNode breakStatement, Void source) {
var info = breakStatement.getUserData(typeof(StatementInfo));
if (info == null) {
context.addWarning(CompileErrorId.UnreachableStatement, breakStatement);
}
return null;
}
protected override Void handleContinue(ContinueStatementNode continueStatement, Void source) {
var info = continueStatement.getUserData(typeof(StatementInfo));
if (info == null) {
context.addWarning(CompileErrorId.UnreachableStatement, continueStatement);
}
return null;
}
protected override Void handleDo(DoStatementNode doStatement, Void source) {
var info = doStatement.getUserData(typeof(StatementInfo));
if (info == null) {
context.addWarning(CompileErrorId.UnreachableStatement, doStatement);
} else {
handleStatement(doStatement.Statement, null);
expressionChecker.handleExpression(doStatement.Condition, null, true);
}
return null;
}
protected override Void handleEmpty(EmptyStatementNode empty, Void source) {
var info = empty.getUserData(typeof(StatementInfo));
if (info == null) {
context.addWarning(CompileErrorId.UnreachableStatement, empty);
}
return null;
}
protected override Void handleExpression(ExpressionStatementNode expression, Void source) {
var info = expression.getUserData(typeof(StatementInfo));
if (info == null) {
context.addWarning(CompileErrorId.UnreachableStatement, expression);
} else {
expressionChecker.handleExpression(expression.Expression, null, true);
}
return null;
}
protected override Void handleFor(ForStatementNode forStatement, Void source) {
var info = forStatement.getUserData(typeof(StatementInfo));
if (info == null) {
context.addWarning(CompileErrorId.UnreachableStatement, forStatement);
} else {
foreach (var s in forStatement.Initializer) {
handleStatement(s, null);
}
if (forStatement.Condition != null) {
expressionChecker.handleExpression(forStatement.Condition, null, true);
}
//foreach (var s in forStatement.Iterator) {
// handleStatement(s, null);
//}
handleStatement(forStatement.Statement, null);
}
return null;
}
protected override Void handleForeach(ForeachStatementNode foreachStatement, Void source) {
var info = foreachStatement.getUserData(typeof(StatementInfo));
if (info == null) {
context.addWarning(CompileErrorId.UnreachableStatement, foreachStatement);
} else {
expressionChecker.handleExpression(foreachStatement.Source, null, true);
handleStatement(foreachStatement.Statement, null);
}
return null;
}
protected override Void handleGoto(GotoStatementNode gotoStatement, Void source) {
var info = gotoStatement.getUserData(typeof(StatementInfo));
if (info == null) {
context.addWarning(CompileErrorId.UnreachableStatement, gotoStatement);
}
return null;
}
protected override Void handleGotoCase(GotoCaseStatementNode gotoCase, Void source) {
var info = gotoCase.getUserData(typeof(StatementInfo));
if (info == null) {
context.addWarning(CompileErrorId.UnreachableStatement, gotoCase);
}
return null;
}
protected override Void handleIf(IfStatementNode ifStatement, Void source) {
var info = ifStatement.getUserData(typeof(StatementInfo));
if (info == null) {
context.addWarning(CompileErrorId.UnreachableStatement, ifStatement);
} else {
expressionChecker.handleExpression(ifStatement.Condition, null, true);
handleStatement(ifStatement.IfTrue, null);
if (ifStatement.IfFalse != null) {
handleStatement(ifStatement.IfFalse, null);
}
}
return null;
}
protected override Void handleLabeled(LabeledStatementNode labeled, Void source) {
var info = labeled.getUserData(typeof(StatementInfo));
if (info == null) {
context.addWarning(CompileErrorId.UnreachableStatement, labeled);
} else {
handleStatement(labeled.Statement, source);
}
return null;
}
protected override Void handleLocalDeclaration(LocalDeclarationStatementNode localDeclaration, Void source) {
var info = localDeclaration.getUserData(typeof(StatementInfo));
if (info == null) {
context.addWarning(CompileErrorId.UnreachableStatement, localDeclaration);
} else {
foreach (var decl in localDeclaration.Declarators) {
if (decl.Value != null) {
expressionChecker.handleExpression(decl.Value, null, true);
}
}
}
return null;
}
protected override Void handleReturn(ReturnStatementNode returnStatement, Void source) {
var info = returnStatement.getUserData(typeof(StatementInfo));
if (info == null) {
context.addWarning(CompileErrorId.UnreachableStatement, returnStatement);
} else {
if (returnStatement.Value != null) {
expressionChecker.handleExpression(returnStatement.Value, null, true);
}
}
return null;
}
protected override Void handleSwitch(SwitchStatementNode switchStatement, Void source) {
var info = switchStatement.getUserData(typeof(StatementInfo));
if (info == null) {
context.addWarning(CompileErrorId.UnreachableStatement, switchStatement);
} else {
expressionChecker.handleExpression(switchStatement.Selector, null, true);
foreach (var section in switchStatement.Sections) {
foreach (var s in section.Statements) {
handleStatement(s, null);
}
}
}
return null;
}
protected override Void handleSynchronized(SynchronizedStatementNode synchronizedStatement, Void source) {
var info = synchronizedStatement.getUserData(typeof(StatementInfo));
if (info == null) {
context.addWarning(CompileErrorId.UnreachableStatement, synchronizedStatement);
} else {
expressionChecker.handleExpression(synchronizedStatement.Lock, null, true);
handleStatement(synchronizedStatement.Statement, null);
}
return null;
}
protected override Void handleThrow(ThrowStatementNode throwStatement, Void source) {
var info = throwStatement.getUserData(typeof(StatementInfo));
if (info == null) {
context.addWarning(CompileErrorId.UnreachableStatement, throwStatement);
} else {
if (throwStatement.Exception != null) {
expressionChecker.handleExpression(throwStatement.Exception, null, true);
}
}
return null;
}
protected override Void handleTry(TryStatementNode tryStatement, Void source) {
var info = tryStatement.getUserData(typeof(StatementInfo));
if (info == null) {
context.addWarning(CompileErrorId.UnreachableStatement, tryStatement);
} else {
handleStatement(tryStatement.Block, source);
foreach (var clause in tryStatement.getCatchClauses()) {
var stmts = clause.Block.Statements;
foreach (var s in stmts) {
handleStatement(s, null);
}
}
if (tryStatement.Finally != null) {
handleStatement(tryStatement.Finally, null);
}
}
return null;
}
protected override Void handleUsing(UsingStatementNode usingStatement, Void source) {
var info = usingStatement.getUserData(typeof(StatementInfo));
if (info == null) {
context.addWarning(CompileErrorId.UnreachableStatement, usingStatement);
} else {
handleStatement(usingStatement.ResourceAcquisition, null);
handleStatement(usingStatement.Statement, null);
}
return null;
}
protected override Void handleWhile(WhileStatementNode whileStatement, Void source) {
var info = whileStatement.getUserData(typeof(StatementInfo));
if (info == null) {
context.addWarning(CompileErrorId.UnreachableStatement, whileStatement);
} else {
expressionChecker.handleExpression(whileStatement.Condition, null, true);
handleStatement(whileStatement.Statement, null);
}
return null;
}
protected override Void handleYield(YieldStatementNode yield, Void source) {
var info = yield.getUserData(typeof(StatementInfo));
if (info == null) {
context.addWarning(CompileErrorId.UnreachableStatement, yield);
} else {
if (yield.Value != null) {
expressionChecker.handleExpression(yield.Value, null, true);
}
}
return null;
}
private class ExpressionChecker : ExpressionHandler<Void, Void> {
private UnreachableStatementsHandler statementHandler;
private CompilerContext context;
ExpressionChecker(UnreachableStatementsHandler statementHandler, CompilerContext context)
: super(true) {
this.statementHandler = statementHandler;
this.context = context;
}
protected override Void handleAnonymousObjectCreation(AnonymousObjectCreationExpressionNode anonymousObject,
Void source, bool nested) {
foreach (var decl in anonymousObject.MemberDeclarators) {
handleExpression(decl.Value, null, true);
}
return null;
}
protected override Void handleArrayCreation(ArrayCreationExpressionNode arrayCreation, Void source, bool nested) {
foreach (var e in arrayCreation.DimensionExpressions) {
handleExpression(e, null, true);
}
if (arrayCreation.Initializer != null) {
handleExpression(arrayCreation.Initializer, null, true);
}
return null;
}
protected override Void handleArrayInitializer(ArrayInitializerExpressionNode arrayInitializer, Void source, bool nested) {
foreach (var e in arrayInitializer.Values) {
handleExpression(e, null, true);
}
return null;
}
protected override Void handleAssign(AssignExpressionNode assign, Void source, bool nested) {
handleExpression(assign.Left, null, true);
handleExpression(assign.Right, null, true);
return null;
}
protected override Void handleBinary(BinaryExpressionNode binary, Void source, bool nested) {
handleExpression(binary.LeftOperand, null, true);
handleExpression(binary.RightOperand, null, true);
return null;
}
protected override Void handleCast(CastExpressionNode cast, Void source, bool nested) {
handleExpression(cast.Expression, null, true);
return null;
}
protected override Void handleConditional(ConditionalExpressionNode conditional, Void source, bool nested) {
handleExpression(conditional.Condition, null, true);
handleExpression(conditional.IfTrue, null, true);
handleExpression(conditional.IfFalse, null, true);
return null;
}
protected override Void handleElementAccess(ElementAccessExpressionNode elementAccess, Void source, bool nested) {
handleExpression(elementAccess.TargetObject, null, true);
foreach (var arg in elementAccess.Indexes) {
handleExpression(arg, null, true);
}
return null;
}
protected override Void handleInvocation(InvocationExpressionNode invocation, Void source, bool nested) {
handleExpression(invocation.TargetObject, null, true);
foreach (var arg in invocation.Arguments) {
handleExpression(arg, null, true);
}
return null;
}
protected override Void handleLambda(LambdaExpressionNode lambda, Void source, bool nested) {
statementHandler.handleStatement(lambda.Body, null);
return null;
}
protected override Void handleLiteral(LiteralExpressionNode literal, Void source, bool nested) {
return null;
}
protected override Void handleMemberAccess(MemberAccessExpressionNode memberAccess, Void source, bool nested) {
handleExpression(memberAccess.TargetObject, null, true);
return null;
}
protected override Void handleObjectCreation(ObjectCreationExpressionNode objectCreation, Void source, bool nested) {
foreach (var arg in objectCreation.Arguments) {
handleExpression(arg, null, true);
}
var init = objectCreation.Initializer;
if (init != null) {
if (init.ExpressionKind == ExpressionKind.ObjectInitializer) {
var initializer = (ObjectInitializerExpressionNode)init;
foreach (var mi in initializer.MemberInitializers) {
handleExpression(mi.Value, null, true);
}
} else {
var initializer = (CollectionInitializerExpressionNode)init;
foreach (var args in initializer.Values) {
foreach (var e in args) {
handleExpression(e, null, true);
}
}
}
}
return null;
}
protected override Void handleSimpleName(SimpleNameExpressionNode simpleName, Void source, bool nested) {
return null;
}
protected override Void handleSizeof(SizeofExpressionNode sizeofExpression, Void source, bool nested) {
handleExpression(sizeofExpression.Expression, null, true);
return null;
}
protected override Void handleSuperAccess(SuperAccessExpressionNode superAccess, Void source, bool nested) {
return null;
}
protected override Void handleThisAccess(ThisAccessExpressionNode thisAccess, Void source, bool nested) {
return null;
}
protected override Void handleType(TypeExpressionNode type, Void source, bool nested) {
return null;
}
protected override Void handleTypeof(TypeofExpressionNode typeofExpression, Void source, bool nested) {
return null;
}
protected override Void handleUnary(UnaryExpressionNode unary, Void source, bool nested) {
handleExpression(unary.Operand, null, true);
return null;
}
}
}
}
}
| |
using System;
using ToolKit.Data;
using Xunit;
namespace UnitTests.Data
{
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"StyleCop.CSharp.DocumentationRules",
"SA1600:ElementsMustBeDocumented",
Justification = "Test Suites do not need XML Documentation.")]
public class EntityWithTypedIdTests
{
[Fact]
public void CompareTo_Should_ReturnEqual_When_OtherEntityIdIsSameAsThisEntity()
{
// Arrange
var entity1 = new Patient();
var entity2 = new Patient();
// Act
entity1.Id = "patient/-1";
entity2.Id = "patient/-1";
// Assert
Assert.True(entity1.CompareTo(entity2) == 0);
}
[Fact]
public void CompareTo_Should_ReturnEqual_When_OtherEntityTransientAndThisEntityIsTransient()
{
// Arrange
var entity1 = new Patient();
var entity2 = new Patient();
// Act
// Assert
Assert.True(entity1.CompareTo(entity2) == 0);
}
[Fact]
public void CompareTo_Should_ReturnGreaterThan_When_OtherEntityIsNull()
{
// Arrange
var entity1 = new Patient();
Patient entity2 = null;
// Act
// Assert
Assert.True(entity1.CompareTo(entity2) == 1);
}
[Fact]
public void CompareTo_Should_ReturnGreaterThan_When_OtherEntityTransientAndThisEntityIsNot()
{
// Arrange
var entity1 = new Patient();
var entity2 = new Patient();
// Act
entity1.Id = "patient/-1";
// Assert
Assert.True(entity1.CompareTo(entity2) == 1);
}
[Fact]
public void CompareTo_Should_ReturnLessThan_When_ThisEntityIdIsLessThanOtherEntityId()
{
// Arrange
var entity1 = new Patient();
var entity2 = new Patient();
// Act
entity1.Id = "patient/-1";
entity2.Id = "patient/-2";
// Assert
Assert.True(entity1.CompareTo(entity2) == -1);
}
[Fact]
public void CompareTo_Should_ReturnLessThan_When_ThisEntityTransientAndOtherEntityIsNot()
{
// Arrange
var entity1 = new Patient();
var entity2 = new Patient();
// Act
entity2.Id = "patient/-2";
// Assert
Assert.True(entity1.CompareTo(entity2) == -1);
}
[Fact]
public void Entity_Should_BeTransientByDefault()
{
// Arrange
var entity = new Patient();
// Act
// Assert
Assert.True(entity.IsTransient());
}
[Fact]
public void Entity_Should_NotBeTransientAfterIdHasValue()
{
// Arrange
var entity = new Patient();
// Act
entity.Id = "patient/-1";
// Assert
Assert.False(entity.IsTransient());
}
[Fact]
public void EntityIdType_Should_BeNull_When_TypedAsStringAndBeforeIdHasValue()
{
// Arrange
var entity = new Patient();
// Act
// Assert
Assert.Null(entity.Id);
}
[Fact]
public void EntityIdType_Should_BeString_When_TypedAsStringAndAfterIdHasValue()
{
// Arrange
var entity = new Patient();
// Act
entity.Id = "patient/-1";
// Assert
Assert.IsType<string>(entity.Id);
}
[Fact]
public void EqualOperand_Should_BeFalse_When_EntityIdIsDifferent()
{
// Arrange
var entity1 = new Patient();
var entity2 = new Patient();
// Act
entity1.Id = "patient/-1";
entity2.Id = "patient/-2";
// Assert
Assert.True(entity1 != entity2);
}
[Fact]
public void EqualOperand_Should_BeTrue_When_EntityIdIsSame()
{
// Arrange
var entity1 = new Patient();
var entity2 = new Patient();
// Act
entity1.Id = "patient/-1";
entity2.Id = "patient/-1";
// Assert
Assert.True(entity1 == entity2);
}
[Fact]
public void EqualOperand_Should_BeTrue_When_EntityIsSameInstance()
{
// Arrange
var entity1 = new Patient();
Patient entity2 = null;
// Act
entity1.Id = "patient/-1";
entity2 = entity1;
// Assert
Assert.True(entity1 == entity2);
}
[Fact]
public void Equals_Should_BeFalse_When_EntityIdIsDifferent()
{
// Arrange
var entity1 = new Patient();
var entity2 = new Patient();
// Act
entity1.Id = "patient/-1";
entity2.Id = "patient/-2";
// Assert
Assert.NotEqual(entity1, entity2);
}
[Fact]
public void Equals_Should_BeFalse_When_OtherEntityIsNull()
{
// Arrange
var entity1 = new Patient();
// Act
entity1.Id = "patient/-1";
// Assert
Assert.False(entity1.Equals(null));
}
[Fact]
public void Equals_Should_BeTrue_When_EntityIdIsSame()
{
// Arrange
var entity1 = new Patient();
var entity2 = new Patient();
// Act
entity1.Id = "patient/-1";
entity2.Id = "patient/-1";
// Assert
Assert.Equal(entity1, entity2);
}
[Fact]
public void Equals_Should_BeTrue_When_OtherEntityIsSameInstance()
{
// Arrange
var entity1 = new Patient
{
Id = "patient/-1"
};
// Act
var entity2 = entity1;
// Assert
Assert.True(entity1.Equals(entity2));
}
[Fact]
public void GetHashCode_Should_GenerateDifferentHashCodes_When_EntitiesIdIsDifferent()
{
// Arrange
var entity1 = new Patient();
var entity2 = new Patient();
// Act
entity1.Id = "patient/-1";
entity2.Id = "patient/-2";
// Assert
Assert.NotEqual(entity1.GetHashCode(), entity2.GetHashCode());
}
[Fact]
public void GetHashCode_Should_GenerateSameHashCode_When_EntitiesAreTransient()
{
// Arrange
var entity1 = new Patient();
var entity2 = new Patient();
// Act
// Assert
Assert.Equal(entity1.GetHashCode(), entity2.GetHashCode());
}
[Fact]
public void GetHashCode_Should_GenerateSameHashCode_When_EntitiesIdIsTheSame()
{
// Arrange
var entity1 = new Patient();
var entity2 = new Patient();
// Act
entity1.Id = "patient/-1";
entity2.Id = "patient/-1";
// Assert
Assert.Equal(entity1.GetHashCode(), entity2.GetHashCode());
}
[Fact]
public void GetHashCode_Should_GenerateSameHashCode_When_EntityIsCopied()
{
// Arrange
var entity1 = new Patient();
var entity2 = entity1;
// Act
var hash1 = entity1.GetHashCode();
var hash2 = entity2.GetHashCode();
// Assert
Assert.Equal(hash1, hash2);
}
[Fact]
public void GetHashCode_Should_ReturnHashCodeBasedOnId_When_NotTransient()
{
// Arrange
var entity = new Patient();
// Act
entity.Id = "patient/-1";
var hash1 = entity.GetHashCode();
var hash2 = entity.Id.GetHashCode();
// Assert
Assert.Equal(hash1, hash2);
}
internal class Patient : EntityWithTypedId<string>
{
public string Name { get; set; }
}
}
}
| |
#region File Information
//-----------------------------------------------------------------------------
// LayoutSample.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.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
#endregion
namespace LayoutSample
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class LayoutSample : Microsoft.Xna.Framework.Game
{
#region Fields
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D directions;
SpriteFont font;
// Is the orientation locked?
bool orientationLocked = false;
// Do we allow dynamically locking/unlocking the orientation?
bool enableOrientationLocking = false;
#endregion
#region Initialization
public LayoutSample()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
// Frame rate is 30 fps by default for Windows Phone.
TargetElapsedTime = TimeSpan.FromTicks(333333);
// DISCLAMER:
// Four different scenarios for initializing orientation support are presented below.
// The first two scenarios are the most common and are recommended for use in most
// cases; the third scenario is a special case to show the hardware scalar work
// result; the fourth scenario is for special cases where games want to dynamically
// support both the landscape and portrait orientations
// Scenario #1 (default):
// SupportedOrientations not changed, so the game will support Landscape orientation only
// Scenario #2:
// SupportedOrientations changed to support the Portrait mode only
// (Uncomment the following two lines)
// graphics.PreferredBackBufferWidth = 480;
// graphics.PreferredBackBufferHeight = 800;
// Scenario #3:
// SupportedOrientations not changed (default), thus game will support the Landscape
// orientations only, but resolution set to half. This makes the hardware scalar work and
// automatically scales the presentation to the device's physical resolution
// (Uncomment the following two lines):
// graphics.PreferredBackBufferWidth = 400;
// graphics.PreferredBackBufferHeight = 240;
// Scenario #4:
// Game supports all possible orientations and enablyes dynamically locking/unlocking the
// orientation.
// (Uncomment the following lines):
// graphics.SupportedOrientations = DisplayOrientation.Portrait |
// DisplayOrientation.LandscapeLeft |
// DisplayOrientation.LandscapeRight;
// enableOrientationLocking = true;
// Switch to full screen mode
graphics.IsFullScreen = true;
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// For scenario #4, we handle locking/unlocking the orientation by detecting the tap gesture.
TouchPanel.EnabledGestures = GestureType.Tap;
base.Initialize();
}
#endregion
#region Load and Unload
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
directions = Content.Load<Texture2D>("directions");
font = Content.Load<SpriteFont>("Font");
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// Nothing to unload in this sample
}
#endregion
#region Update and Render
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// If we enable locking/unlocking the orientation...
if (enableOrientationLocking)
{
// Read the gestures from the touch panel
while (TouchPanel.IsGestureAvailable)
{
GestureSample gesture = TouchPanel.ReadGesture();
// If the user tapped on the screen...
if (gesture.GestureType == GestureType.Tap)
{
// Toggle the orientation locked state
orientationLocked = !orientationLocked;
if (orientationLocked)
{
// If we're locking the orientation, we want to store the current
// orientation as well as the current viewport size. we have to
// store the viewport size because when we call ApplyChanges(),
// our back buffer may change and we want to make sure that it
// remains at the current size, rather than any previously set
// preferred size.
graphics.SupportedOrientations = Window.CurrentOrientation;
graphics.PreferredBackBufferWidth = GraphicsDevice.Viewport.Width;
graphics.PreferredBackBufferHeight = GraphicsDevice.Viewport.Height;
}
else
{
// If we're unlocking the orientation, we simply set our
// supported orientations back to all orientations
graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft |
DisplayOrientation.LandscapeRight |
DisplayOrientation.Portrait;
}
// ApplyChanges needs to be called if SupportedOrientations was changed
graphics.ApplyChanges();
}
}
}
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
// Draw the directions texture centered on the screen
Vector2 position = new Vector2(
GraphicsDevice.Viewport.Width / 2 - directions.Width / 2,
GraphicsDevice.Viewport.Height / 2 - directions.Height / 2);
spriteBatch.Draw(directions, position, Color.White);
// If we allow locking/unlocking of the orientation, draw the instructions to
// the screen.
if (enableOrientationLocking)
{
// Create a string of our current state
string currentState = orientationLocked
? "Orientation: Locked"
: "Orientation: Unlocked";
// Create a string for the instructions
string instructions = orientationLocked
? "Tap to unlock orientation."
: "Tap to lock orientation.";
// Draw the text to the screen
spriteBatch.DrawString(font, currentState, new Vector2(10, 10), Color.White);
spriteBatch.DrawString(font, instructions, new Vector2(10, 25), Color.White);
}
spriteBatch.End();
base.Draw(gameTime);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.GrainDirectory;
using Orleans.Internal;
using Orleans.Metadata;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.Messaging;
using Orleans.Runtime.Placement;
using Orleans.Runtime.Scheduler;
using Orleans.Runtime.Versions;
using Orleans.Runtime.Versions.Compatibility;
using Orleans.Serialization;
namespace Orleans.Runtime
{
internal class Catalog : SystemTarget, ICatalog, IPlacementRuntime, IHealthCheckParticipant
{
public SiloAddress LocalSilo { get; private set; }
internal ISiloStatusOracle SiloStatusOracle { get; set; }
private readonly ActivationCollector activationCollector;
private static readonly TimeSpan UnregisterTimeout = TimeSpan.FromSeconds(1);
private readonly GrainLocator grainLocator;
private readonly GrainDirectoryResolver grainDirectoryResolver;
private readonly ILocalGrainDirectory directory;
private readonly OrleansTaskScheduler scheduler;
private readonly ActivationDirectory activations;
private readonly LRU<ActivationAddress, ExceptionDispatchInfo> failedActivations = new(1000, TimeSpan.FromSeconds(5));
private IServiceProvider serviceProvider;
private readonly ILogger logger;
private int collectionNumber;
private IAsyncTimer gcTimer;
private Task gcTimerTask;
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 GrainContextActivator grainCreator;
private readonly TimeSpan maxRequestProcessingTime;
private readonly TimeSpan maxWarningRequestProcessingTime;
private readonly SerializationManager serializationManager;
private readonly CachedVersionSelectorManager versionSelectorManager;
private readonly ILoggerFactory loggerFactory;
private readonly IOptions<GrainCollectionOptions> collectionOptions;
private readonly IOptionsMonitor<SiloMessagingOptions> messagingOptions;
private readonly RuntimeMessagingTrace messagingTrace;
private readonly PlacementStrategyResolver placementStrategyResolver;
private readonly GrainContextActivator grainActivator;
private readonly GrainVersionManifest grainInterfaceVersions;
private readonly GrainPropertiesResolver grainPropertiesResolver;
public Catalog(
ILocalSiloDetails localSiloDetails,
GrainLocator grainLocator,
GrainDirectoryResolver grainDirectoryResolver,
ILocalGrainDirectory grainDirectory,
OrleansTaskScheduler scheduler,
ActivationDirectory activationDirectory,
ActivationCollector activationCollector,
GrainContextActivator grainCreator,
MessageCenter messageCenter,
MessageFactory messageFactory,
SerializationManager serializationManager,
IServiceProvider serviceProvider,
CachedVersionSelectorManager versionSelectorManager,
ILoggerFactory loggerFactory,
IOptions<GrainCollectionOptions> collectionOptions,
IOptionsMonitor<SiloMessagingOptions> messagingOptions,
RuntimeMessagingTrace messagingTrace,
IAsyncTimerFactory timerFactory,
PlacementStrategyResolver placementStrategyResolver,
PlacementService placementService,
GrainContextActivator grainActivator,
GrainVersionManifest grainInterfaceVersions,
CompatibilityDirectorManager compatibilityDirectorManager,
GrainPropertiesResolver grainPropertiesResolver,
IncomingRequestMonitor incomingRequestMonitor)
: base(Constants.CatalogType, messageCenter.MyAddress, loggerFactory)
{
this.LocalSilo = localSiloDetails.SiloAddress;
this.localSiloName = localSiloDetails.Name;
this.grainLocator = grainLocator;
this.grainDirectoryResolver = grainDirectoryResolver;
this.directory = grainDirectory;
this.activations = activationDirectory;
this.scheduler = scheduler;
this.loggerFactory = loggerFactory;
this.collectionNumber = 0;
this.grainCreator = grainCreator;
this.serializationManager = serializationManager;
this.versionSelectorManager = versionSelectorManager;
this.serviceProvider = serviceProvider;
this.collectionOptions = collectionOptions;
this.messagingOptions = messagingOptions;
this.messagingTrace = messagingTrace;
this.placementStrategyResolver = placementStrategyResolver;
this.grainActivator = grainActivator;
this.grainInterfaceVersions = grainInterfaceVersions;
this.grainPropertiesResolver = grainPropertiesResolver;
this.logger = loggerFactory.CreateLogger<Catalog>();
this.activationCollector = activationCollector;
this.Dispatcher = new Dispatcher(
scheduler,
messageCenter,
this,
messagingOptions,
placementService,
grainDirectory,
messageFactory,
loggerFactory,
activationDirectory,
messagingTrace);
this.ActivationMessageScheduler = new ActivationMessageScheduler(this, this.Dispatcher, grainInterfaceVersions, messagingTrace, activationCollector, scheduler, compatibilityDirectorManager, incomingRequestMonitor);
GC.GetTotalMemory(true); // need to call once w/true to ensure false returns OK value
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;
});
maxWarningRequestProcessingTime = this.messagingOptions.CurrentValue.ResponseTimeout.Multiply(5);
maxRequestProcessingTime = this.messagingOptions.CurrentValue.MaxRequestProcessingTime;
grainDirectory.SetSiloRemovedCatalogCallback(this.OnSiloStatusChange);
this.gcTimer = timerFactory.Create(this.activationCollector.Quantum, "Catalog.GCTimer");
this.RuntimeClient = serviceProvider.GetRequiredService<InsideRuntimeClient>();
}
/// <summary>
/// Gets the dispatcher used by this instance.
/// </summary>
public Dispatcher Dispatcher { get; }
public ActivationMessageScheduler ActivationMessageScheduler { get; }
public SiloAddress[] GetCompatibleSilos(PlacementTarget target)
{
// For test only: if we have silos that are not yet in the Cluster TypeMap, we assume that they are compatible
// with the current silo
if (this.messagingOptions.CurrentValue.AssumeHomogenousSilosForTesting)
return AllActiveSilos;
var grainType = target.GrainIdentity.Type;
var silos = target.InterfaceVersion > 0
? versionSelectorManager.GetSuitableSilos(grainType, target.InterfaceType, target.InterfaceVersion).SuitableSilos
: grainInterfaceVersions.GetSupportedSilos(grainType).Result;
var compatibleSilos = silos.Intersect(AllActiveSilos).ToArray();
if (compatibleSilos.Length == 0)
{
var allWithType = grainInterfaceVersions.GetSupportedSilos(grainType).Result;
var versions = grainInterfaceVersions.GetSupportedSilos(target.InterfaceType, target.InterfaceVersion).Result;
var allWithTypeString = string.Join(", ", allWithType.Select(s => s.ToString())) is string withGrain && !string.IsNullOrWhiteSpace(withGrain) ? withGrain : "none";
var allWithInterfaceString = string.Join(", ", versions.Select(s => s.ToString())) is string withIface && !string.IsNullOrWhiteSpace(withIface) ? withIface : "none";
throw new OrleansException(
$"No active nodes are compatible with grain {grainType} and interface {target.InterfaceType} version {target.InterfaceVersion}. "
+ $"Known nodes with grain type: {allWithTypeString}. "
+ $"All known nodes compatible with interface version: {allWithTypeString}");
}
return compatibleSilos;
}
public IReadOnlyDictionary<ushort, SiloAddress[]> GetCompatibleSilosWithVersions(PlacementTarget target)
{
if (target.InterfaceVersion == 0)
{
throw new ArgumentException("Interface version not provided", nameof(target));
}
var grainType = target.GrainIdentity.Type;
var silos = versionSelectorManager
.GetSuitableSilos(grainType, target.InterfaceType, target.InterfaceVersion)
.SuitableSilosByVersion;
return silos;
}
internal void Start()
{
this.gcTimerTask = this.RunActivationCollectionLoop();
}
internal async Task Stop()
{
this.gcTimer?.Dispose();
if (this.gcTimerTask is Task task) await task;
}
private async Task RunActivationCollectionLoop()
{
while (await this.gcTimer.NextTick())
{
try
{
await this.CollectActivationsImpl(true);
}
catch (Exception exception)
{
this.logger.LogError(exception, "Exception while collecting activations");
}
}
}
public Task CollectActivations(TimeSpan ageLimit)
{
return CollectActivationsImpl(false, ageLimit);
}
private async Task CollectActivationsImpl(bool scanStale, TimeSpan ageLimit = default(TimeSpan))
{
var watch = ValueStopwatch.StartNew();
var number = Interlocked.Increment(ref collectionNumber);
long memBefore = GC.GetTotalMemory(false) / (1024 * 1024);
failedActivations.RemoveExpired();
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug(
(int)ErrorCode.Catalog_BeforeCollection,
"Before collection #{CollectionNumber}: memory: {MemoryBefore}MB, #activations: {ActivationCount}, collector: {CollectorStatus}",
number,
memBefore,
activations.Count,
this.activationCollector.ToString());
}
List<ActivationData> list = scanStale ? this.activationCollector.ScanStale() : this.activationCollector.ScanAll(ageLimit);
collectionCounter.Increment();
var count = 0;
if (list != null && list.Count > 0)
{
count = list.Count;
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("CollectActivations{0}", list.ToStrings(d => d.GrainId.ToString() + d.ActivationId));
await DeactivateActivationsFromCollector(list);
}
long memAfter = GC.GetTotalMemory(false) / (1024 * 1024);
watch.Stop();
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug(
(int)ErrorCode.Catalog_AfterCollection,
"After collection #{CollectionNumber} memory: {MemoryAfter}MB, #activations: {ActivationCount}, collected {CollectedCount} activations, collector: {CollectorStatus}, collection time: {CollectionTime}",
number,
memAfter,
activations.Count,
count,
this.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.GrainInstance.GetType());
Dictionary<GrainId, int> grains;
int n;
if (!counts.TryGetValue(grainTypeName, out grains))
{
counts.Add(grainTypeName, new Dictionary<GrainId, int> { { data.GrainId, 1 } });
}
else if (!grains.TryGetValue(data.GrainId, out n))
grains[data.GrainId] = 1;
else
grains[data.GrainId] = 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;
var grainType = TypeUtils.GetFullName(data.GrainInstance.GetType());
if (types==null || types.Contains(grainType))
{
stats.Add(new DetailedGrainStatistic()
{
GrainType = grainType,
GrainId = data.GrainId,
SiloAddress = data.Silo
});
}
}
}
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
{
var properties = this.grainPropertiesResolver.GetGrainProperties(grain.Type);
if (properties.Properties.TryGetValue(WellKnownGrainTypeProperties.TypeName, out var grainClassName))
{
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;
}
/// <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)
{
scheduler.RegisterWorkContext(activation);
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.
this.activationCollector.TryCancelCollection(activation);
activationsDestroyed.Increment();
scheduler.UnregisterWorkContext(activation);
if (activation.GrainInstance is object grainInstance)
{
var grainTypeName = TypeUtils.GetFullName(grainInstance.GetType());
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;
}
public void RegisterSystemTarget(ISystemTarget target)
{
var systemTarget = target as SystemTarget;
if (systemTarget == null) throw new ArgumentException($"Parameter must be of type {typeof(SystemTarget)}", nameof(target));
systemTarget.RuntimeClient = this.RuntimeClient;
scheduler.RegisterWorkContext(systemTarget);
activations.RecordNewSystemTarget(systemTarget);
}
public void UnregisterSystemTarget(ISystemTarget target)
{
var systemTarget = target as SystemTarget;
if (systemTarget == null) throw new ArgumentException($"Parameter must be of type {typeof(SystemTarget)}", nameof(target));
activations.RemoveSystemTarget(systemTarget);
scheduler.UnregisterWorkContext(systemTarget);
}
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="requestContextData">Request context data.</param>
/// <returns></returns>
public ActivationData GetOrCreateActivation(
ActivationAddress address,
bool newPlacement,
Dictionary<string, object> requestContextData)
{
if (TryGetActivationData(address.Activation, out var result))
{
return result;
}
// Lock over all activations to try to prevent multiple instances of the same activation being created concurrently.
lock (activations)
{
if (TryGetActivationData(address.Activation, out result))
{
return result;
}
if (newPlacement && !SiloStatusOracle.CurrentStatus.IsTerminating())
{
result = (ActivationData)this.grainActivator.CreateInstance(address);
if (result.PlacedUsing is StatelessWorkerPlacement st)
{
// Check if there is already enough StatelessWorker created
if (LocalLookup(address.Grain, out var local) && local.Count > st.MaxLocal)
{
// Redirect directly to an already created StatelessWorker
// It's a bit hacky since we will return an activation with a different
// ActivationId than the one requested, but StatelessWorker are local only,
// so no need to clear the cache. This will avoid unecessary and costly redirects.
var redirect = StatelessWorkerDirector.PickRandom(local);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug(
(int)ErrorCode.Catalog_DuplicateActivation,
"Trying to create too many {GrainType} activations on this silo. Redirecting to activation {RedirectActivation}",
result.Name,
redirect.ActivationId);
}
return redirect;
}
// The newly created StatelessWorker will be registered in RegisterMessageTarget()
}
if (result.GrainInstance is object grainInstance)
{
var grainTypeName = TypeUtils.GetFullName(grainInstance.GetType());
activations.IncrementGrainCounter(grainTypeName);
}
RegisterMessageTarget(result);
}
} // End lock
if (result is null)
{
if (failedActivations.TryGetValue(address, out var ex))
{
logger.Warn(ErrorCode.Catalog_ActivationException, "Call to an activation that failed during OnActivateAsync()");
ex.Throw();
}
// Did not find and did not start placing new
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug((int)ErrorCode.CatalogNonExistingActivation2, "Non-existent activation {Activation}", address.ToFullString());
}
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_NON_EXISTENT_ACTIVATIONS).Increment();
this.directory.InvalidateCacheEntry(address);
// Unregister the target activation so we don't keep getting spurious messages.
// The time delay (one minute, as of this writing) is to handle the unlikely but possible race where
// this request snuck ahead of another request, with new placement requested, for the same activation.
// If the activation registration request from the new placement somehow sneaks ahead of this unregistration,
// we want to make sure that we don't unregister the activation we just created.
_ = this.UnregisterNonExistentActivation(address);
return null;
}
else
{
// Initialize the new activation asynchronously.
_ = InitActivation(result, requestContextData);
return result;
}
}
private enum ActivationInitializationStage
{
None,
Register,
SetupState,
InvokeActivate,
Completed
}
private async Task UnregisterNonExistentActivation(ActivationAddress address)
{
try
{
await this.grainLocator.Unregister(address, UnregistrationCause.NonexistentActivation);
}
catch (Exception exc)
{
logger.LogWarning(
(int)ErrorCode.Dispatcher_FailedToUnregisterNonExistingAct,
exc,
"Failed to unregister non-existent activation {Address}",
address);
}
}
private async Task InitActivation(ActivationData activation, 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
var initStage = ActivationInitializationStage.None;
// 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
{
try
{
initStage = ActivationInitializationStage.Register;
var registrationResult = await RegisterActivationInGrainDirectoryAndValidate(activation);
if (!registrationResult.IsSuccess)
{
// If registration failed, recover and bail out.
await RecoverFailedInitActivation(activation, initStage, registrationResult);
return;
}
initStage = ActivationInitializationStage.InvokeActivate;
await InvokeActivate(activation, requestContextData);
// Success!! Log the result, and start processing messages
initStage = ActivationInitializationStage.Completed;
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("InitActivation is done: {0}", activation.Address);
}
catch (Exception ex)
{
await RecoverFailedInitActivation(activation, initStage, exception: ex);
}
}
catch (Exception exception)
{
this.logger.LogWarning(exception, "Exception trying to initialize grain activation {Grain}", activation);
}
}
/// <summary>
/// Recover from a failed attempt to initialize a new activation.
/// </summary>
/// <param name="activation">The activation which failed to be initialized.</param>
/// <param name="initStage">The initialization stage at which initialization failed.</param>
/// <param name="registrationResult">The result of registering the activation with the grain directory.</param>
/// <param name="exception">The exception, if present, for logging purposes.</param>
private async Task RecoverFailedInitActivation(
ActivationData activation,
ActivationInitializationStage initStage,
ActivationRegistrationResult registrationResult = default(ActivationRegistrationResult),
Exception exception = null)
{
var address = activation.Address;
if (initStage == ActivationInitializationStage.Register && registrationResult.ExistingActivationAddress != null)
{
// Another activation is registered in the directory: let's forward everything
lock (activation)
{
activation.SetState(ActivationState.Invalid);
activation.ForwardingAddress = registrationResult.ExistingActivationAddress;
if (activation.ForwardingAddress != null)
{
CounterStatistic
.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_CONCURRENT_REGISTRATION_ATTEMPTS)
.Increment();
var primary = directory.GetPrimaryForGrain(activation.ForwardingAddress.Grain);
if (logger.IsEnabled(LogLevel.Debug))
{
// 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.
var logMsg =
$"Tried to create a duplicate activation {address}, but we'll use {activation.ForwardingAddress} instead. " +
$"GrainInstance Type is {activation.GrainInstance?.GetType()}. " +
$"{(primary != null ? "Primary Directory partition for this grain is " + primary + ". " : string.Empty)}" +
$"Full activation address is {address.ToFullString()}. We have {activation.WaitingCount} messages to forward.";
logger.Debug(ErrorCode.Catalog_DuplicateActivation, logMsg);
}
UnregisterMessageTarget(activation);
RerouteAllQueuedMessages(activation, activation.ForwardingAddress, "Duplicate activation", exception);
}
}
}
else
{
// Before anything let's unregister the activation from the directory, so other silo don't keep sending message to it
if (activation.IsUsingGrainDirectory)
{
try
{
await this.scheduler.RunOrQueueTask(
() => this.grainLocator.Unregister(address, UnregistrationCause.Force),
this).WithTimeout(UnregisterTimeout);
}
catch (Exception ex)
{
logger.Warn(
ErrorCode.Catalog_UnregisterAsync,
$"Failed to unregister activation {activation} after {initStage} stage failed",
ex);
}
}
lock (activation)
{
UnregisterMessageTarget(activation);
if (initStage == ActivationInitializationStage.InvokeActivate)
{
failedActivations.Add(activation.Address, ExceptionDispatchInfo.Capture(exception));
activation.SetState(ActivationState.FailedToActivate);
logger.Warn(ErrorCode.Catalog_Failed_InvokeActivate, string.Format("Failed to InvokeActivate for {0}.", activation), exception);
// Reject all of the messages queued for this activation.
var activationFailedMsg = nameof(Grain.OnActivateAsync) + " failed";
RejectAllQueuedMessages(activation, activationFailedMsg, exception);
}
else
{
activation.SetState(ActivationState.Invalid);
logger.Warn(ErrorCode.Runtime_Error_100064, $"Failed to RegisterActivationInGrainDirectory for {activation}.", exception);
RerouteAllQueuedMessages(activation, null, "Failed RegisterActivationInGrainDirectory", exception);
}
}
}
}
/// <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 = activations.FindTarget(activationId);
return data != null;
}
private async Task DeactivateActivationsFromCollector(List<ActivationData> list)
{
var cts = new CancellationTokenSource(this.collectionOptions.Value.DeactivationTimeout);
var mtcs = new MultiTaskCompletionSource(list.Count);
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);
for (var i = 0; i < list.Count; i++)
{
var activationData = list[i];
lock (activationData)
{
// Continue deactivation when ready
activationData.AddOnInactive(async () =>
{
try
{
await DestroyActivation(activationData, cts.Token);
}
finally
{
mtcs.SetOneResult();
}
});
}
}
await mtcs.Task;
}
// 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)
{
DeactivateActivationImpl(data, StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_DEACTIVATE_ON_IDLE);
}
// To be called from within Activation context.
// To be used only if an activation is stuck for a long time, since it can lead to a duplicate activation
internal async Task DeactivateStuckActivation(ActivationData activationData)
{
// The unregistration is normally done in the regular deactivation process, but since this activation seems
// stuck (it might never run the deactivation process), we remove it from the directory directly
await this.grainLocator.Unregister(activationData.Address, UnregistrationCause.Force);
DeactivateActivationImpl(activationData, StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_DEACTIVATE_STUCK_ACTIVATION);
}
private void DeactivateActivationImpl(ActivationData data, StatisticName statisticName)
{
var cts = new CancellationTokenSource(this.collectionOptions.Value.DeactivationTimeout);
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
this.activationCollector.TryCancelCollection(data);
if (!data.IsCurrentlyExecuting)
{
promptly = true;
}
else // busy, so destroy later.
{
data.AddOnInactive(() => _ = DestroyActivation(data, cts.Token));
}
}
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(statisticName).Increment();
if (promptly)
{
_ = DestroyActivation(data, cts.Token); // Don't await or Ignore, since we are in this activation context and it may have alraedy been destroyed!
}
}
internal async Task DeactivateActivation(ActivationData activationData)
{
TaskCompletionSource<object> tcs;
var cts = new CancellationTokenSource(this.collectionOptions.Value.DeactivationTimeout);
lock (activationData)
{
if (activationData.State != ActivationState.Valid)
return; // Nothing to do
tcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
// Don't accept any new messages
activationData.PrepareForDeactivation();
this.activationCollector.TryCancelCollection(activationData);
// Continue deactivation when ready
activationData.AddOnInactive(async () =>
{
try
{
await DestroyActivation(activationData, cts.Token);
}
finally
{
tcs.SetResult(null);
}
});
}
await tcs.Task.WithCancellation(cts.Token);
}
private async Task DestroyActivation(ActivationData activationData, CancellationToken ct)
{
try
{
// Wait timers and call OnDeactivateAsync()
await activationData.WaitForAllTimersToFinish();
await this.scheduler.RunOrQueueTask(() => CallGrainDeactivateAndCleanupStreams(activationData, ct), activationData);
// Unregister from directory
await this.grainLocator.Unregister(activationData.Address, UnregistrationCause.Force);
}
catch (Exception ex)
{
this.logger.Warn(ErrorCode.Catalog_DeactivateActivation_Exception, $"Exception when trying to deactivation {activationData}", ex);
}
finally
{
lock (activationData)
{
activationData.SetState(ActivationState.Invalid);
}
// Capture grainInstance since UnregisterMessageTarget will set it to null...
var grainInstance = activationData.GrainInstance;
UnregisterMessageTarget(activationData);
RerouteAllQueuedMessages(activationData, null, "Finished Destroy Activation");
await activationData.DisposeAsync();
}
}
/// <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.IsEnabled(LogLevel.Debug)) logger.Debug("DeactivateActivations: {0} activations.", list.Count);
await Task.WhenAll(list.Select(DeactivateActivation));
}
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);
}
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.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.Catalog_RerouteAllQueuedMessages, String.Format("RerouteAllQueuedMessages: {0} msgs from Invalid activation {1}.", msgs.Count, activation));
this.directory.InvalidateCacheEntry(activation.Address);
this.Dispatcher.ProcessRequestsToInvalidActivation(msgs, activation.Address, forwardingAddress, failedOperation, exc);
}
}
/// <summary>
/// Rejects all messages enqueued for the provided activation.
/// </summary>
/// <param name="activation">The activation.</param>
/// <param name="failedOperation">The operation which failed, resulting in this rejection.</param>
/// <param name="exception">The rejection exception.</param>
private void RejectAllQueuedMessages(
ActivationData activation,
string failedOperation,
Exception exception = null)
{
lock (activation)
{
List<Message> msgs = activation.DequeueAllWaitingMessages();
if (msgs == null || msgs.Count <= 0) return;
if (logger.IsEnabled(LogLevel.Debug))
logger.Debug(
ErrorCode.Catalog_RerouteAllQueuedMessages,
string.Format("RejectAllQueuedMessages: {0} msgs from Invalid activation {1}.", msgs.Count, activation));
this.directory.InvalidateCacheEntry(activation.Address);
this.Dispatcher.ProcessRequestsToInvalidActivation(
msgs,
activation.Address,
forwardingAddress: null,
failedOperation: failedOperation,
exc: exception,
rejectMessages: true);
}
}
private async Task CallGrainActivate(ActivationData activation, Dictionary<string, object> requestContextData)
{
var grainTypeName = activation.GrainInstance?.GetType().FullName;
// Note: This call is being made from within Scheduler.Queue wrapper, so we are already executing on worker thread
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.Catalog_BeforeCallingActivate, "About to call {1} grain's OnActivateAsync() method {0}", activation, grainTypeName);
// Start grain lifecycle within try-catch wrapper to safely capture any exceptions thrown from called function
try
{
RequestContextExtensions.Import(requestContextData);
await activation.ActivateAsync(CancellationToken.None);
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.Catalog_AfterCallingActivate, "Returned from calling {1} grain's OnActivateAsync() method {0}", activation, grainTypeName);
}
catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_ErrorCallingActivate,
string.Format("Error calling grain's OnActivateAsync() method - Grain type = {1} Activation = {0}", activation, grainTypeName), exc);
activationsFailedToActivate.Increment();
// TODO: During lifecycle refactor discuss with team whether activation failure should have a well defined exception, or throw whatever
// exception caused activation to fail, with no indication that it occured durring activation
// rather than the grain call.
var canceledException = exc as OrleansLifecycleCanceledException;
if (canceledException?.InnerException != null)
{
ExceptionDispatchInfo.Capture(canceledException.InnerException).Throw();
}
throw;
}
finally
{
RequestContext.Clear();
}
}
private async Task<ActivationData> CallGrainDeactivateAndCleanupStreams(ActivationData activation, CancellationToken ct)
{
try
{
var grainTypeName = activation.GrainInstance?.GetType().FullName;
// Note: This call is being made from within Scheduler.Queue wrapper, so we are already executing on worker thread
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(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.Lifecycle.OnStop().WithCancellation(ct);
}
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(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);
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_FinishGrainDeactivateAndCleanupStreams_Exception, String.Format("CallGrainDeactivateAndCleanupStreams Activation = {0} failed.", activation), exc);
}
return activation;
}
/// <summary>
/// Represents the results of an attempt to register an activation.
/// </summary>
private struct ActivationRegistrationResult
{
/// <summary>
/// Represents a successful activation.
/// </summary>
public static readonly ActivationRegistrationResult Success = new ActivationRegistrationResult
{
IsSuccess = true
};
public ActivationRegistrationResult(ActivationAddress existingActivationAddress)
{
ValidateExistingActivationAddress(existingActivationAddress);
ExistingActivationAddress = existingActivationAddress;
IsSuccess = false;
}
/// <summary>
/// Returns true if this instance represents a successful registration, false otherwise.
/// </summary>
public bool IsSuccess { get; private set; }
/// <summary>
/// The existing activation address if this instance represents a duplicate activation.
/// </summary>
public ActivationAddress ExistingActivationAddress { get; }
private static void ValidateExistingActivationAddress(ActivationAddress existingActivationAddress)
{
if (existingActivationAddress == null)
throw new ArgumentNullException(nameof(existingActivationAddress));
}
}
private async Task<ActivationRegistrationResult> RegisterActivationInGrainDirectoryAndValidate(ActivationData activation)
{
var 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(() => this.grainLocator.Register(address), this);
if (address.Equals(result)) return ActivationRegistrationResult.Success;
return new ActivationRegistrationResult(existingActivationAddress: result);
}
else if (activation.PlacedUsing is StatelessWorkerPlacement stPlacement)
{
// Stateless workers are not registered in the directory and can have multiple local activations.
// We already checked earlier that we didn't created too many instances of this worker
return ActivationRegistrationResult.Success;
}
else
{
// Some other non-directory, single-activation placement.
lock (activations)
{
var exists = LocalLookup(address.Grain, out var local);
if (exists && local.Count == 1 && local[0].ActivationId.Equals(activation.ActivationId))
{
return ActivationRegistrationResult.Success;
}
return new ActivationRegistrationResult(existingActivationAddress: local[0].Address);
}
}
// We currently don't have any other case for multiple activations except for StatelessWorker.
}
/// <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), activation); // Target grain);
// ActivationData will transition out of ActivationState.Activating via Dispatcher.OnActivationCompletedRequest
}
public bool FastLookup(GrainId grain, out List<ActivationAddress> addresses)
{
return this.grainLocator.TryLocalLookup(grain, out addresses) && addresses != null && 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<List<ActivationAddress>> FullLookup(GrainId grain)
{
return scheduler.RunOrQueueTask(() => this.grainLocator.Lookup(grain), this);
}
public bool LocalLookup(GrainId grain, out List<ActivationData> addresses)
{
addresses = activations.FindTargets(grain);
return addresses != null;
}
public SiloAddress[] AllActiveSilos
{
get
{
var result = SiloStatusOracle.GetApproximateSiloStatuses(true).Keys.ToArray();
if (result.Length > 0) return result;
logger.Warn(ErrorCode.Catalog_GetApproximateSiloStatuses, "AllActiveSilos SiloStatusOracle.GetApproximateSiloStatuses empty");
return new SiloAddress[] { LocalSilo };
}
}
public SiloStatus LocalSiloStatus
{
get
{
return SiloStatusOracle.CurrentStatus;
}
}
public Task DeleteActivations(List<ActivationAddress> addresses)
{
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;
}
var timeoutTokenSource = new CancellationTokenSource(this.collectionOptions.Value.DeactivationTimeout);
var tasks = new List<Task>(addresses.Count);
foreach (var activationData in TryGetActivationDatas(addresses))
{
var capture = activationData;
tasks.Add(DestroyActivation(capture, timeoutTokenSource.Token));
}
return Task.WhenAll(tasks);
}
// TODO move this logic in the LocalGrainDirectory
private void OnSiloStatusChange(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 behavior 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)
{
this.RuntimeClient.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 || grainDirectoryResolver.HasNonDefaultDirectory(activationData.GrainId.Type)) continue;
if (!updatedSilo.Equals(directory.GetPrimaryForGrain(activationData.GrainId))) continue;
lock (activationData)
{
// adapted from InsideGrainClient.DeactivateOnIdle().
activationData.ResetKeepAliveRequest();
activationsToShutdown.Add(activationData);
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_SiloStatusChangeNotification_Exception,
String.Format("Catalog has thrown an exception while executing OnSiloStatusChange 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 partition to these grain ids.",
activationsToShutdown.Count, updatedSilo.ToStringWithHashCode()));
}
finally
{
// outside the lock.
if (activationsToShutdown.Count > 0)
{
DeactivateActivations(activationsToShutdown).Ignore();
}
}
}
public bool CheckHealth(DateTime lastCheckTime, out string reason)
{
if (this.gcTimer is IAsyncTimer timer)
{
return timer.CheckHealth(lastCheckTime, out reason);
}
reason = default;
return 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.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Security;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
/// <summary>Provides a pool of connections to the same endpoint.</summary>
internal sealed class HttpConnectionPool : IDisposable
{
private readonly HttpConnectionPoolManager _poolManager;
private readonly string _host;
private readonly int _port;
private readonly Uri _proxyUri;
/// <summary>List of idle connections stored in the pool.</summary>
private readonly List<CachedConnection> _idleConnections = new List<CachedConnection>();
/// <summary>The maximum number of connections allowed to be associated with the pool.</summary>
private readonly int _maxConnections;
/// <summary>For non-proxy connection pools, this is the host name in bytes; for proxies, null.</summary>
private readonly byte[] _idnHostAsciiBytes;
/// <summary>Options specialized and cached for this pool and its <see cref="_key"/>.</summary>
private readonly SslClientAuthenticationOptions _sslOptions;
/// <summary>The head of a list of waiters waiting for a connection. Null if no one's waiting.</summary>
private ConnectionWaiter _waitersHead;
/// <summary>The tail of a list of waiters waiting for a connection. Null if no one's waiting.</summary>
private ConnectionWaiter _waitersTail;
/// <summary>The number of connections associated with the pool. Some of these may be in <see cref="_idleConnections"/>, others may be in use.</summary>
private int _associatedConnectionCount;
/// <summary>Whether the pool has been used since the last time a cleanup occurred.</summary>
private bool _usedSinceLastCleanup = true;
/// <summary>Whether the pool has been disposed.</summary>
private bool _disposed;
/// <summary>Initializes the pool.</summary>
/// <param name="maxConnections">The maximum number of connections allowed to be associated with the pool at any given time.</param>
///
public HttpConnectionPool(HttpConnectionPoolManager poolManager, string host, int port, string sslHostName, Uri proxyUri, int maxConnections)
{
Debug.Assert(proxyUri == null ?
host != null && port != 0 : // direct http or https connection
(sslHostName == null ?
host == null && port == 0 : // proxy connection
host != null && port != 0)); // SSL proxy tunnel
_poolManager = poolManager;
_host = host;
_port = port;
_proxyUri = proxyUri;
_maxConnections = maxConnections;
if (sslHostName != null)
{
// Precalculate cached SSL options to use for all connections.
_sslOptions = _poolManager.Settings._sslOptions?.ShallowClone() ?? new SslClientAuthenticationOptions();
_sslOptions.ApplicationProtocols = null; // explicitly ignore any ApplicationProtocols set
_sslOptions.TargetHost = sslHostName; // always use the key's name rather than whatever was specified
}
if (_host != null)
{
// Precalculate ASCII bytes for header name
// Note that if _host is null, this is a (non-tunneled) proxy connection, and we can't cache the hostname.
// CONSIDER: Cache more than just host name -- port, header name, etc
// Note the IDN hostname should always be ASCII, since it's already been IDNA encoded.
_idnHostAsciiBytes = Encoding.ASCII.GetBytes(_host);
Debug.Assert(Encoding.ASCII.GetString(_idnHostAsciiBytes) == _host);
}
}
public HttpConnectionSettings Settings => _poolManager.Settings;
public bool IsSecure => _sslOptions != null;
public bool UsingProxy => (_proxyUri != null && !IsSecure); // Tunnel doesn't count, only direct proxy usage
public byte[] IdnHostAsciiBytes => _idnHostAsciiBytes;
/// <summary>Object used to synchronize access to state in the pool.</summary>
private object SyncObj => _idleConnections;
private ValueTask<HttpConnection> GetConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return new ValueTask<HttpConnection>(Task.FromCanceled<HttpConnection>(cancellationToken));
}
TimeSpan pooledConnectionLifetime = _poolManager.Settings._pooledConnectionLifetime;
TimeSpan pooledConnectionIdleTimeout = _poolManager.Settings._pooledConnectionIdleTimeout;
DateTimeOffset now = DateTimeOffset.UtcNow;
List<CachedConnection> list = _idleConnections;
lock (SyncObj)
{
// Try to return a cached connection. We need to loop in case the connection
// we get from the list is unusable.
while (list.Count > 0)
{
CachedConnection cachedConnection = list[list.Count - 1];
HttpConnection conn = cachedConnection._connection;
Debug.Assert(!conn.IsNewConnection);
list.RemoveAt(list.Count - 1);
if (cachedConnection.IsUsable(now, pooledConnectionLifetime, pooledConnectionIdleTimeout))
{
// We found a valid collection. Return it.
if (NetEventSource.IsEnabled) conn.Trace("Found usable connection in pool.");
return new ValueTask<HttpConnection>(conn);
}
// We got a connection, but it was already closed by the server or the
// server sent unexpected data or the connection is too old. In any case,
// we can't use the connection, so get rid of it and try again.
if (NetEventSource.IsEnabled) conn.Trace("Found invalid connection in pool.");
conn.Dispose();
}
// No valid cached connections, so we need to create a new one. If
// there's no limit on the number of connections associated with this
// pool, or if we haven't reached such a limit, simply create a new
// connection.
if (_associatedConnectionCount < _maxConnections)
{
if (NetEventSource.IsEnabled) Trace("Creating new connection for pool.");
IncrementConnectionCountNoLock();
return WaitForCreatedConnectionAsync(CreateConnectionAsync(request, cancellationToken));
}
else
{
// There is a limit, and we've reached it, which means we need to
// wait for a connection to be returned to the pool or for a connection
// associated with the pool to be dropped before we can create a
// new one. Create a waiter object and register it with the pool; it'll
// be signaled with the created connection when one is returned or
// space is available and the provided creation func has successfully
// created the connection to be used.
if (NetEventSource.IsEnabled) Trace("Limit reached. Waiting to create new connection.");
var waiter = new ConnectionWaiter(this, request, cancellationToken);
EnqueueWaiter(waiter);
if (cancellationToken.CanBeCanceled)
{
// If cancellation could be requested, register a callback for it that'll cancel
// the waiter and remove the waiter from the queue. Note that this registration needs
// to happen under the reentrant lock and after enqueueing the waiter.
waiter._cancellationTokenRegistration = cancellationToken.Register(s =>
{
var innerWaiter = (ConnectionWaiter)s;
lock (innerWaiter._pool.SyncObj)
{
// If it's in the list, remove it and cancel it.
if (innerWaiter._pool.RemoveWaiterForCancellation(innerWaiter))
{
bool canceled = innerWaiter.TrySetCanceled(innerWaiter._cancellationToken);
Debug.Assert(canceled);
}
}
}, waiter);
}
return new ValueTask<HttpConnection>(waiter.Task);
}
// Note that we don't check for _disposed. We may end up disposing the
// created connection when it's returned, but we don't want to block use
// of the pool if it's already been disposed, as there's a race condition
// between getting a pool and someone disposing of it, and we don't want
// to complicate the logic about trying to get a different pool when the
// retrieved one has been disposed of. In the future we could alternatively
// try returning such connections to whatever pool is currently considered
// current for that endpoint, if there is one.
}
}
public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
while (true)
{
// Loop on connection failures and retry if possible.
HttpConnection connection = await GetConnectionAsync(request, cancellationToken).ConfigureAwait(false);
if (connection.IsNewConnection)
{
return await connection.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
try
{
return await connection.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
catch (HttpRequestException e) when (e.InnerException is IOException && connection.CanRetry)
{
// Eat exception and try again.
}
}
}
private async ValueTask<HttpConnection> CreateConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// If a non-infinite connect timeout has been set, create and use a new CancellationToken that'll be canceled
// when either the original token is canceled or a connect timeout occurs.
CancellationTokenSource cancellationWithConnectTimeout = null;
if (Settings._connectTimeout != Timeout.InfiniteTimeSpan)
{
cancellationWithConnectTimeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, default);
cancellationWithConnectTimeout.CancelAfter(Settings._connectTimeout);
cancellationToken = cancellationWithConnectTimeout.Token;
}
try
{
Stream stream = await
(_proxyUri == null ?
ConnectHelper.ConnectAsync(_host, _port, cancellationToken) :
(_sslOptions == null ?
ConnectHelper.ConnectAsync(_proxyUri.IdnHost, _proxyUri.Port, cancellationToken) :
EstablishProxyTunnel(cancellationToken))).ConfigureAwait(false);
TransportContext transportContext = null;
if (_sslOptions != null)
{
// TODO #25206 and #24430: Register/IsCancellationRequested should be removable once SslStream auth and sockets respect cancellation.
CancellationTokenRegistration ctr = cancellationToken.Register(s => ((Stream)s).Dispose(), stream);
try
{
SslStream sslStream = await ConnectHelper.EstablishSslConnectionAsync(_sslOptions, request, stream, cancellationToken).ConfigureAwait(false);
stream = sslStream;
transportContext = sslStream.TransportContext;
cancellationToken.ThrowIfCancellationRequested(); // to handle race condition where stream is dispose of by cancellation after auth
}
catch (Exception exc)
{
stream.Dispose(); // in case cancellation occurs after successful SSL auth
if (HttpConnection.ShouldWrapInOperationCanceledException(exc, cancellationToken))
{
throw HttpConnection.CreateOperationCanceledException(exc, cancellationToken);
}
throw;
}
finally
{
ctr.Dispose();
}
}
return _maxConnections == int.MaxValue ?
new HttpConnection(this, stream, transportContext) :
new HttpConnectionWithFinalizer(this, stream, transportContext); // finalizer needed to signal the pool when a connection is dropped
}
finally
{
cancellationWithConnectTimeout?.Dispose();
}
}
// TODO (#23136):
// CONNECT is not yet supported, so this code will not succeed currently.
private async ValueTask<Stream> EstablishProxyTunnel(CancellationToken cancellationToken)
{
// Send a CONNECT request to the proxy server to establish a tunnel.
HttpRequestMessage tunnelRequest = new HttpRequestMessage(HttpMethod.Connect, _proxyUri);
tunnelRequest.Headers.Host = $"{_host}:{_port}"; // This specifies destination host/port to connect to
// TODO: For now, we don't support proxy authentication in this scenario.
// This will get fixed when we refactor proxy auth handling.
HttpResponseMessage tunnelResponse = await _poolManager.SendAsync(tunnelRequest, null, cancellationToken).ConfigureAwait(false);
if (tunnelResponse.StatusCode != HttpStatusCode.OK)
{
throw new HttpRequestException(SR.Format(SR.net_http_proxy_tunnel_failed, _proxyUri, tunnelResponse.StatusCode));
}
return await tunnelResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
}
/// <summary>Enqueues a waiter to the waiters list.</summary>
/// <param name="waiter">The waiter to add.</param>
private void EnqueueWaiter(ConnectionWaiter waiter)
{
Debug.Assert(Monitor.IsEntered(SyncObj));
Debug.Assert(waiter != null);
Debug.Assert(waiter._next == null);
Debug.Assert(waiter._prev == null);
waiter._next = _waitersHead;
if (_waitersHead != null)
{
_waitersHead._prev = waiter;
}
else
{
Debug.Assert(_waitersTail == null);
_waitersTail = waiter;
}
_waitersHead = waiter;
}
/// <summary>Dequeues a waiter from the waiters list. The list must not be empty.</summary>
/// <returns>The dequeued waiter.</returns>
private ConnectionWaiter DequeueWaiter()
{
Debug.Assert(Monitor.IsEntered(SyncObj));
Debug.Assert(_waitersTail != null);
ConnectionWaiter waiter = _waitersTail;
_waitersTail = waiter._prev;
if (_waitersTail != null)
{
_waitersTail._next = null;
}
else
{
Debug.Assert(_waitersHead == waiter);
_waitersHead = null;
}
waiter._next = null;
waiter._prev = null;
return waiter;
}
/// <summary>Removes the specified waiter from the waiters list as part of a cancellation request.</summary>
/// <param name="waiter">The waiter to remove.</param>
/// <returns>true if the waiter was in the list; otherwise, false.</returns>
private bool RemoveWaiterForCancellation(ConnectionWaiter waiter)
{
Debug.Assert(Monitor.IsEntered(SyncObj));
Debug.Assert(waiter != null);
Debug.Assert(waiter._cancellationToken.IsCancellationRequested);
bool inList = waiter._next != null || waiter._prev != null || _waitersHead == waiter || _waitersTail == waiter;
if (waiter._next != null) waiter._next._prev = waiter._prev;
if (waiter._prev != null) waiter._prev._next = waiter._next;
if (_waitersHead == waiter && _waitersTail == waiter)
{
_waitersHead = _waitersTail = null;
}
else if (_waitersHead == waiter)
{
_waitersHead = waiter._next;
}
else if (_waitersTail == waiter)
{
_waitersTail = waiter._prev;
}
waiter._next = null;
waiter._prev = null;
return inList;
}
/// <summary>Waits for and returns the created connection, decrementing the associated connection count if it fails.</summary>
private async ValueTask<HttpConnection> WaitForCreatedConnectionAsync(ValueTask<HttpConnection> creationTask)
{
try
{
return await creationTask.ConfigureAwait(false);
}
catch
{
DecrementConnectionCount();
throw;
}
}
/// <summary>
/// Increments the count of connections associated with the pool. This is invoked
/// any time a new connection is created for the pool.
/// </summary>
public void IncrementConnectionCount()
{
lock (SyncObj) IncrementConnectionCountNoLock();
}
private void IncrementConnectionCountNoLock()
{
Debug.Assert(Monitor.IsEntered(SyncObj), $"Expected to be holding {nameof(SyncObj)}");
if (NetEventSource.IsEnabled) Trace(null);
_usedSinceLastCleanup = true;
Debug.Assert(
_associatedConnectionCount >= 0 && _associatedConnectionCount < _maxConnections,
$"Expected 0 <= {_associatedConnectionCount} < {_maxConnections}");
_associatedConnectionCount++;
}
/// <summary>
/// Decrements the number of connections associated with the pool.
/// If there are waiters on the pool due to having reached the maximum,
/// this will instead try to transfer the count to one of them.
/// </summary>
public void DecrementConnectionCount()
{
if (NetEventSource.IsEnabled) Trace(null);
lock (SyncObj)
{
Debug.Assert(_associatedConnectionCount > 0 && _associatedConnectionCount <= _maxConnections,
$"Expected 0 < {_associatedConnectionCount} <= {_maxConnections}");
// Mark the pool as not being stale.
_usedSinceLastCleanup = true;
if (_waitersHead == null)
{
// There are no waiters to which the count should logically be transferred,
// so simply decrement the count.
_associatedConnectionCount--;
}
else
{
// There's at least one waiter to which we should try to logically transfer
// the associated count. Get the waiter.
Debug.Assert(_idleConnections.Count == 0, $"With {_idleConnections} connections, we shouldn't have a waiter.");
ConnectionWaiter waiter = DequeueWaiter();
Debug.Assert(waiter != null, "Expected non-null waiter");
Debug.Assert(waiter.Task.Status == TaskStatus.WaitingForActivation, $"Expected {waiter.Task.Status} == {nameof(TaskStatus.WaitingForActivation)}");
waiter._cancellationTokenRegistration.Dispose();
// Having a waiter means there must not be any idle connections, so we need to create
// one, and we do so using the logic associated with the waiter.
ValueTask<HttpConnection> connectionTask = waiter.CreateConnectionAsync();
if (connectionTask.IsCompletedSuccessfully)
{
// We synchronously and successfully created a connection (this is rare).
// Transfer the connection to the waiter. Since we already have a count
// that's inflated due to the connection being disassociated, we don't
// need to change the count here.
waiter.SetResult(connectionTask.Result);
}
else
{
// We initiated a connection creation. When it completes, transfer the result to the waiter.
connectionTask.AsTask().ContinueWith((innerConnectionTask, state) =>
{
var innerWaiter = (ConnectionWaiter)state;
try
{
// Get the resulting connection.
HttpConnection result = innerConnectionTask.GetAwaiter().GetResult();
// Store the resulting connection into the waiter. As in the synchronous case,
// since we already have a count that's inflated due to the connection being
// disassociated, we don't need to change the count here.
innerWaiter.SetResult(innerConnectionTask.Result);
}
catch (Exception e)
{
// The creation operation failed. Store the exception into the waiter.
innerWaiter.SetException(e);
// At this point, a connection was dropped and we failed to replace it,
// which means our connection count still needs to be decremented.
innerWaiter._pool.DecrementConnectionCount();
}
}, waiter, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
}
}
}
/// <summary>Returns the connection to the pool for subsequent reuse.</summary>
/// <param name="connection">The connection to return.</param>
public void ReturnConnection(HttpConnection connection)
{
List<CachedConnection> list = _idleConnections;
lock (SyncObj)
{
Debug.Assert(list.Count <= _maxConnections, $"Expected {list.Count} <= {_maxConnections}");
// Mark the pool as still being active.
_usedSinceLastCleanup = true;
// If there's someone waiting for a connection, simply
// transfer this one to them rather than pooling it.
if (_waitersTail != null)
{
ConnectionWaiter waiter = DequeueWaiter();
waiter._cancellationTokenRegistration.Dispose();
if (NetEventSource.IsEnabled) connection.Trace("Transferring connection returned to pool.");
waiter.SetResult(connection);
return;
}
// If the pool has been disposed of, dispose the connection being returned,
// as the pool is being deactivated. We do this after the above in order to
// use pooled connections to satisfy any requests that pended before the
// the pool was disposed of.
if (_disposed)
{
if (NetEventSource.IsEnabled) connection.Trace("Disposing connection returned to disposed pool.");
connection.Dispose();
return;
}
// Pool the connection by adding it to the list.
list.Add(new CachedConnection(connection));
if (NetEventSource.IsEnabled) connection.Trace("Stored connection in pool.");
}
}
/// <summary>Disposes the </summary>
public void Dispose()
{
List<CachedConnection> list = _idleConnections;
lock (SyncObj)
{
if (!_disposed)
{
if (NetEventSource.IsEnabled) Trace("Disposing pool.");
_disposed = true;
list.ForEach(c => c._connection.Dispose());
list.Clear();
}
Debug.Assert(list.Count == 0, $"Expected {nameof(list)}.{nameof(list.Count)} == 0");
}
}
/// <summary>
/// Removes any unusable connections from the pool, and if the pool
/// is then empty and stale, disposes of it.
/// </summary>
/// <returns>
/// true if the pool disposes of itself; otherwise, false.
/// </returns>
public bool CleanCacheAndDisposeIfUnused()
{
TimeSpan pooledConnectionLifetime = _poolManager.Settings._pooledConnectionLifetime;
TimeSpan pooledConnectionIdleTimeout = _poolManager.Settings._pooledConnectionIdleTimeout;
List<CachedConnection> list = _idleConnections;
List<HttpConnection> toDispose = null;
bool tookLock = false;
try
{
if (NetEventSource.IsEnabled) Trace("Cleaning pool.");
Monitor.Enter(SyncObj, ref tookLock);
// Get the current time. This is compared against each connection's last returned
// time to determine whether a connection is too old and should be closed.
DateTimeOffset now = DateTimeOffset.Now;
// Find the first item which needs to be removed.
int freeIndex = 0;
while (freeIndex < list.Count && list[freeIndex].IsUsable(now, pooledConnectionLifetime, pooledConnectionIdleTimeout))
{
freeIndex++;
}
// If freeIndex == list.Count, nothing needs to be removed.
// But if it's < list.Count, at least one connection needs to be purged.
if (freeIndex < list.Count)
{
// We know the connection at freeIndex is unusable, so dispose of it.
toDispose = new List<HttpConnection> { list[freeIndex]._connection };
// Find the first item after the one to be removed that should be kept.
int current = freeIndex + 1;
while (current < list.Count)
{
// Look for the first item to be kept. Along the way, any
// that shouldn't be kept are disposed of.
while (current < list.Count && !list[current].IsUsable(now, pooledConnectionLifetime, pooledConnectionIdleTimeout))
{
toDispose.Add(list[current]._connection);
current++;
}
// If we found something to keep, copy it down to the known free slot.
if (current < list.Count)
{
// copy item to the free slot
list[freeIndex++] = list[current++];
}
// Keep going until there are no more good items.
}
// At this point, good connections have been moved below freeIndex, and garbage connections have
// been added to the dispose list, so clear the end of the list past freeIndex.
list.RemoveRange(freeIndex, list.Count - freeIndex);
// If there are now no connections associated with this pool, we can dispose of it. We
// avoid aggressively cleaning up pools that have recently been used but currently aren't;
// if a pool was used since the last time we cleaned up, give it another chance. New pools
// start out saying they've recently been used, to give them a bit of breathing room and time
// for the initial collection to be added to it.
if (_associatedConnectionCount == 0 && !_usedSinceLastCleanup)
{
Debug.Assert(list.Count == 0, $"Expected {nameof(list)}.{nameof(list.Count)} == 0");
_disposed = true;
return true; // Pool is disposed of. It should be removed.
}
}
// Reset the cleanup flag. Any pools that are empty and not used since the last cleanup
// will be purged next time around.
_usedSinceLastCleanup = false;
}
finally
{
if (tookLock)
{
Monitor.Exit(SyncObj);
}
// Dispose the stale connections outside the pool lock.
toDispose?.ForEach(c => c.Dispose());
}
// Pool is active. Should not be removed.
return false;
}
// For diagnostic purposes
public override string ToString() =>
$"{nameof(HttpConnectionPool)}" +
(_proxyUri == null ?
(_sslOptions == null ?
$"http://{_host}:{_port}" :
$"https://{_host}:{_port}" + (_sslOptions.TargetHost != _host ? $", SSL TargetHost={_sslOptions.TargetHost}" : null)) :
(_sslOptions == null ?
$"Proxy {_proxyUri}" :
$"https://{_host}:{_port}/ tunnelled via Proxy {_proxyUri}" + (_sslOptions.TargetHost != _host ? $", SSL TargetHost={_sslOptions.TargetHost}" : null)));
private void Trace(string message, [CallerMemberName] string memberName = null) =>
NetEventSource.Log.HandlerMessage(
GetHashCode(), // pool ID
0, // connection ID
0, // request ID
memberName, // method name
ToString() + ":" + message); // message
/// <summary>A cached idle connection and metadata about it.</summary>
[StructLayout(LayoutKind.Auto)]
private readonly struct CachedConnection : IEquatable<CachedConnection>
{
/// <summary>The cached connection.</summary>
internal readonly HttpConnection _connection;
/// <summary>The last time the connection was used.</summary>
internal readonly DateTimeOffset _returnedTime;
/// <summary>Initializes the cached connection and its associated metadata.</summary>
/// <param name="connection">The connection.</param>
public CachedConnection(HttpConnection connection)
{
Debug.Assert(connection != null);
_connection = connection;
_returnedTime = DateTimeOffset.UtcNow;
}
/// <summary>Gets whether the connection is currently usable.</summary>
/// <param name="now">The current time. Passed in to amortize the cost of calling DateTime.UtcNow.</param>
/// <param name="pooledConnectionLifetime">How long a connection can be open to be considered reusable.</param>
/// <param name="pooledConnectionIdleTimeout">How long a connection can have been idle in the pool to be considered reusable.</param>
/// <returns>
/// true if we believe the connection can be reused; otherwise, false. There is an inherent race condition here,
/// in that the server could terminate the connection or otherwise make it unusable immediately after we check it,
/// but there's not much difference between that and starting to use the connection and then having the server
/// terminate it, which would be considered a failure, so this race condition is largely benign and inherent to
/// the nature of connection pooling.
/// </returns>
public bool IsUsable(
DateTimeOffset now,
TimeSpan pooledConnectionLifetime,
TimeSpan pooledConnectionIdleTimeout)
{
// Validate that the connection hasn't been idle in the pool for longer than is allowed.
if ((pooledConnectionIdleTimeout != Timeout.InfiniteTimeSpan) && (now - _returnedTime > pooledConnectionIdleTimeout))
{
if (NetEventSource.IsEnabled) _connection.Trace($"Connection no longer usable. Idle {now - _returnedTime} > {pooledConnectionIdleTimeout}.");
return false;
}
// Validate that the connection hasn't been alive for longer than is allowed.
if ((pooledConnectionLifetime != Timeout.InfiniteTimeSpan) && (now - _connection.CreationTime > pooledConnectionLifetime))
{
if (NetEventSource.IsEnabled) _connection.Trace($"Connection no longer usable. Alive {now - _connection.CreationTime} > {pooledConnectionLifetime}.");
return false;
}
// Validate that the connection hasn't received any stray data while in the pool.
if (_connection.ReadAheadCompleted)
{
if (NetEventSource.IsEnabled) _connection.Trace($"Connection no longer usable. Unexpected data received.");
return false;
}
// The connection is usable.
return true;
}
public bool Equals(CachedConnection other) => ReferenceEquals(other._connection, _connection);
public override bool Equals(object obj) => obj is CachedConnection && Equals((CachedConnection)obj);
public override int GetHashCode() => _connection?.GetHashCode() ?? 0;
}
/// <summary>
/// Provides a waiter object that's used when we've reached the limit on connections
/// associated with the pool. When a connection is available or created, it's stored
/// into the waiter as a result, and if no connection is available from the pool,
/// this waiter's logic is used to create the connection.
/// </summary>
private class ConnectionWaiter : TaskCompletionSource<HttpConnection>
{
/// <summary>The pool with which this waiter is associated.</summary>
internal readonly HttpConnectionPool _pool;
/// <summary>Request to use to create the connection.</summary>
private readonly HttpRequestMessage _request;
/// <summary>Cancellation token for the waiter.</summary>
internal readonly CancellationToken _cancellationToken;
/// <summary>Registration that removes the waiter from the registration list.</summary>
internal CancellationTokenRegistration _cancellationTokenRegistration;
/// <summary>Next waiter in the list.</summary>
internal ConnectionWaiter _next;
/// <summary>Previous waiter in the list.</summary>
internal ConnectionWaiter _prev;
/// <summary>Initializes the waiter.</summary>
public ConnectionWaiter(HttpConnectionPool pool, HttpRequestMessage request, CancellationToken cancellationToken) : base(TaskCreationOptions.RunContinuationsAsynchronously)
{
Debug.Assert(pool != null, "Expected non-null pool");
_pool = pool;
_request = request;
_cancellationToken = cancellationToken;
}
/// <summary>Creates a connection.</summary>
public ValueTask<HttpConnection> CreateConnectionAsync()
{
try
{
return _pool.CreateConnectionAsync(_request, _cancellationToken);
}
catch (Exception e)
{
return new ValueTask<HttpConnection>(Threading.Tasks.Task.FromException<HttpConnection>(e));
}
}
}
}
}
| |
// 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.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.SignatureHelp;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class ElementAccessExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
public ElementAccessExpressionSignatureHelpProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture)
{
}
internal override ISignatureHelpProvider CreateSignatureHelpProvider()
{
return new ElementAccessExpressionSignatureHelpProvider();
}
#region "Regular tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersOn1()
{
var markup = @"
class C
{
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
var c = new C();
var x = [|c[$$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(636117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636117")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnExpression()
{
var markup = @"
class C
{
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
C[] c = new C[1];
c[0][$$
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersXmlCommentsOn1()
{
var markup = @"
class C
{
/// <summary>
/// Summary for this.
/// </summary>
/// <param name=""a"">Param a</param>
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
var c = new C();
var x = [|c[$$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", "Summary for this.", "Param a", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersOn2()
{
var markup = @"
class C
{
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
var c = new C();
var x = [|c[22, $$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersXmlComentsOn2()
{
var markup = @"
class C
{
/// <summary>
/// Summary for this.
/// </summary>
/// <param name=""a"">Param a</param>
/// <param name=""b"">Param b</param>
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
var c = new C();
var x = [|c[22, $$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", "Summary for this.", "Param b", currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutClosingBracketWithParameters()
{
var markup =
@"class C
{
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
var c = new C();
var x = [|c[$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutClosingBracketWithParametersOn2()
{
var markup = @"
class C
{
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
var c = new C();
var x = [|c[22, $$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
#endregion
#region "Current Parameter Name"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestCurrentParameterName()
{
var markup = @"
class C
{
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
var c = new C();
var x = [|c[b: false, a: $$42|]];
}
}";
await VerifyCurrentParameterNameAsync(markup, "a");
}
#endregion
#region "Trigger tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerBracket()
{
var markup = @"
class C
{
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
var c = new C();
var x = [|c[$$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerComma()
{
var markup = @"
class C
{
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
var c = new C();
var x = [|c[42,$$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestNoInvocationOnSpace()
{
var markup = @"
class C
{
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
var c = new C();
var x = [|c[42, $$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestTriggerCharacters()
{
char[] expectedCharacters = { ',', '[' };
char[] unexpectedCharacters = { ' ', '(', '<' };
VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters);
}
#endregion
#region "EditorBrowsable tests"
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Indexer_PropertyAlways()
{
var markup = @"
class Program
{
void M()
{
new Foo()[$$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public int this[int x]
{
get { return 5; }
set { }
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int Foo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Indexer_PropertyNever()
{
var markup = @"
class Program
{
void M()
{
new Foo()[$$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public int this[int x]
{
get { return 5; }
set { }
}
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("int Foo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItemsMetadataReference,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Indexer_PropertyAdvanced()
{
var markup = @"
class Program
{
void M()
{
new Foo()[$$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public int this[int x]
{
get { return 5; }
set { }
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int Foo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Indexer_PropertyNeverOnOneOfTwoOverloads()
{
var markup = @"
class Program
{
void M()
{
new Foo()[$$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public int this[int x]
{
get { return 5; }
set { }
}
public int this[double d]
{
get { return 5; }
set { }
}
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("int Foo[double d]", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("int Foo[double d]", string.Empty, string.Empty, currentParameterIndex: 0),
new SignatureHelpTestItem("int Foo[int x]", string.Empty, string.Empty, currentParameterIndex: 0),
};
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Indexer_GetBrowsableNeverIgnored()
{
var markup = @"
class Program
{
void M()
{
new Foo()[$$
}
}";
var referencedCode = @"
public class Foo
{
public int this[int x]
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
get { return 5; }
set { }
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int Foo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Indexer_SetBrowsableNeverIgnored()
{
var markup = @"
class Program
{
void M()
{
new Foo()[$$
}
}";
var referencedCode = @"
public class Foo
{
public int this[int x]
{
get { return 5; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
set { }
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int Foo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Indexer_GetSetBrowsableNeverIgnored()
{
var markup = @"
class Program
{
void M()
{
new Foo()[$$
}
}";
var referencedCode = @"
public class Foo
{
public int this[int x]
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
get { return 5; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
set { }
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int Foo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
#endregion
#region Indexed Property tests
[WorkItem(530811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530811")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task IndexedProperty()
{
var markup = @"class Program
{
void M()
{
CCC c = new CCC();
c.IndexProp[$$
}
}";
// Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types.
var referencedCode = @"Imports System.Runtime.InteropServices
<ComImport()>
<GuidAttribute(CCC.ClassId)>
Public Class CCC
#Region ""COM GUIDs""
Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0""
Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6""
Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb""
# End Region
''' <summary>
''' An index property from VB
''' </summary>
''' <param name=""p1"">p1 is an integer index</param>
''' <returns>A string</returns>
Public Property IndexProp(ByVal p1 As Integer) As String
Get
Return Nothing
End Get
Set(ByVal value As String)
End Set
End Property
End Class";
var metadataItems = new List<SignatureHelpTestItem>();
metadataItems.Add(new SignatureHelpTestItem("string CCC.IndexProp[int p1]", string.Empty, string.Empty, currentParameterIndex: 0));
var projectReferenceItems = new List<SignatureHelpTestItem>();
projectReferenceItems.Add(new SignatureHelpTestItem("string CCC.IndexProp[int p1]", "An index property from VB", "p1 is an integer index", currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: metadataItems,
expectedOrderedItemsSameSolution: projectReferenceItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.VisualBasic);
}
#endregion
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
public int this[int z]
{
get
{
return 0;
}
}
#endif
void foo()
{
var x = this[$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"int C[int z]\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_context}", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
public int this[int z]
{
get
{
return 0;
}
}
#endif
#if BAR
void foo()
{
var x = this[$$
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" />
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"int C[int z]\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_context}", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
public class IncompleteElementAccessExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
public IncompleteElementAccessExpressionSignatureHelpProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture)
{
}
internal override ISignatureHelpProvider CreateSignatureHelpProvider()
{
return new ElementAccessExpressionSignatureHelpProvider();
}
[WorkItem(636117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636117")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocation()
{
var markup = @"
class C
{
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
var c = new C();
c[$$]
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(939417, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939417")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task ConditionalIndexer()
{
var markup = @"
public class P
{
public int this[int z]
{
get
{
return 0;
}
}
public void foo()
{
P p = null;
p?[$$]
}
}
";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int P[int z]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(32, "https://github.com/dotnet/roslyn/issues/32")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task NonIdentifierConditionalIndexer()
{
var expected = new[] { new SignatureHelpTestItem("char string[int index]") };
await TestAsync(
@"class C
{
void M()
{
""""?[$$ }
}", expected); // inline with a string literal
await TestAsync(
@"class C
{
void M()
{
""""?[/**/$$ }
}", expected); // inline with a string literal and multiline comment
await TestAsync(
@"class C
{
void M()
{
("""")?[$$ }
}", expected); // parenthesized expression
await TestAsync(
@"class C
{
void M()
{
new System.String(' ', 1)?[$$ }
}", expected); // new object expression
// more complicated parenthesized expression
await TestAsync(
@"class C
{
void M()
{
(null as System.Collections.Generic.List<int>)?[$$ }
}", new[] { new SignatureHelpTestItem("int System.Collections.Generic.List<int>[int index]") });
}
[WorkItem(1067933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvokedWithNoToken()
{
var markup = @"
// foo[$$";
await TestAsync(markup);
}
[WorkItem(2482, "https://github.com/dotnet/roslyn/issues/2482")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task WhereExpressionLooksLikeArrayTypeSyntaxOfQualifiedName()
{
var markup = @"
class WithIndexer
{
public int this[int index] { get { return 0; } }
}
class TestClass
{
public WithIndexer Item { get; set; }
public void Method(TestClass tc)
{
// `tc.Item[]` parses as ArrayTypeSyntax with an ElementType of QualifiedNameSyntax
tc.Item[$$]
}
}
";
await TestAsync(markup, new[] { new SignatureHelpTestItem("int WithIndexer[int index]") }, usePreviousCharAsTrigger: true);
}
}
}
}
| |
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Linq;
using System.Windows.Forms;
using System.Collections.Generic;
namespace command_console
{
public class CommandConsole : IConsole
{
public event OnCommandHandler OnCommand;
public bool IsAlive { get; private set; }
public int Width { get; private set; }
public int Height { get; private set; }
public ConsoleColor CommandColor { get; set; }
class ConsoleLine {
public ConsoleColor Color;
public string Line;
public ConsoleLine() :this(Console.ForegroundColor, string.Empty) {}
public ConsoleLine(string ln) : this(Console.ForegroundColor, ln) {}
public ConsoleLine(ConsoleColor clr, string ln)
{
Color = clr;
Line = ln;
}
public static readonly ConsoleLine Empty = new ConsoleLine();
}
private static readonly int BUF_SIZE = 1024;
private static readonly int HISTORY_SIZE = 100;
private ConsoleLine[] m_buffer = new ConsoleLine[BUF_SIZE];
private string[] m_history = new string[HISTORY_SIZE];
private int m_historyCursor = HISTORY_SIZE - 1;
private Thread m_inputThread;
private AutoResetEvent m_blockEvent;
private bool m_isNewLine = false;
private int m_bufPos = BUF_SIZE;
public void Init(ConsoleColor cmdColor)
{
Width = Console.WindowWidth;
Height = Console.WindowHeight;
Init(Width, Height, cmdColor);
}
public void Init(int width, int height, ConsoleColor cmdColor)
{
Width = width;
Height = height;
CommandColor = cmdColor;
Console.SetWindowSize (Width, Height);
Console.SetBufferSize (Width, Height);
for (int i = 0; i < BUF_SIZE; i++) {
m_buffer [i] = ConsoleLine.Empty;
}
for (int i = 0; i < HISTORY_SIZE; i++) {
m_history [i] = string.Empty;
}
IsAlive = true;
}
public void Run(bool isBlocking)
{
m_inputThread = new Thread (Input);
m_inputThread.SetApartmentState(ApartmentState.STA);
m_inputThread.Start ();
if (isBlocking) {
m_blockEvent = new AutoResetEvent (false);
m_blockEvent.WaitOne ();
}
}
public void Stop()
{
IsAlive = false;
if (m_blockEvent != null)
m_blockEvent.Set ();
try {
if (m_inputThread.IsAlive)
m_inputThread.Abort();
}
catch (Exception) {}
}
public void Write(string line)
{
if (!IsAlive)
return;
AppendToBuffer (new ConsoleLine(line));
}
public void Write(string format, params object[] args)
{
if (!IsAlive)
return;
var line = string.Format (format, args);
AppendToBuffer (new ConsoleLine(line));
}
public void WriteLine(string line)
{
if (!IsAlive)
return;
AddToBuffer(new ConsoleLine(line));
}
public void WriteLine(string format, params object[] args)
{
if (!IsAlive)
return;
var line = string.Format (format, args);
AddToBuffer (new ConsoleLine(line));
}
public void Write (string line, ConsoleColor lineColor)
{
if (!IsAlive)
return;
AppendToBuffer (new ConsoleLine (lineColor, line));
}
public void Write (string format, ConsoleColor lineColor, params object[] args)
{
if (!IsAlive)
return;
var line = string.Format (format, args);
AppendToBuffer (new ConsoleLine (lineColor, line));
}
public void WriteLine (string line, ConsoleColor lineColor)
{
if (!IsAlive)
return;
AddToBuffer (new ConsoleLine (lineColor, line));
}
public void WriteLine (string format, ConsoleColor lineColor, params object[] args)
{
if (!IsAlive)
return;
var line = string.Format (format, args);
AddToBuffer (new ConsoleLine (lineColor, line));
}
private void Input()
{
while (true) {
var cmd = string.Empty;
DrawCmdBuffer (cmd);
while (true) {
var keyInfo = Console.ReadKey ();
if (keyInfo.Key == ConsoleKey.Enter)
break;
if (keyInfo.Key == ConsoleKey.Backspace)
cmd = cmd.Length > 0 ? cmd.Remove (Math.Max (0, cmd.Length - 1)) : cmd;
else if (keyInfo.Key == ConsoleKey.UpArrow)
cmd = GetNextHistoryCmd ();
else if (keyInfo.Key == ConsoleKey.DownArrow)
cmd = GetPrevHistoryCmd ();
else if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0 && keyInfo.Key == ConsoleKey.V)
cmd = Clipboard.GetText ();
else if (keyInfo.Key == ConsoleKey.PageUp)
ScrollBufferUp ();
else if (keyInfo.Key == ConsoleKey.PageDown)
ScrollBufferDown ();
else
cmd += keyInfo.KeyChar.ToString ();
DrawCmdBuffer (cmd);
}
cmd = cmd.Trim ();
if (string.IsNullOrEmpty (cmd))
continue;
ProcessCmd (cmd);
if (!IsAlive)
break;
}
}
private void ProcessCmd(string cmd)
{
if (OnCommand != null)
OnCommand (cmd);
AddToHistoryCmd(cmd);
}
private void DrawCmdBuffer(string cmd)
{
lock (m_buffer) {
Console.SetCursorPosition (0, Height - 1);
ApplyColorAspect (CommandColor, () => Console.Write (cmd.PadRight (Width - 1).Remove (Width - 2)));
}
}
private string GetNextHistoryCmd()
{
var cmd = m_history [m_historyCursor];
if (!string.IsNullOrEmpty(cmd))
m_historyCursor = Math.Max(0, m_historyCursor - 1);
return cmd;
}
private string GetPrevHistoryCmd()
{
var cmd = m_history [m_historyCursor];
m_historyCursor = Math.Min (HISTORY_SIZE - 1, m_historyCursor + 1);
return cmd;
}
private void AddToHistoryCmd(string cmd)
{
if (m_history.Any (e => e == cmd))
return;
for (int idx = 0; idx < HISTORY_SIZE - 1; idx++) {
m_history [idx] = m_history [idx + 1];
}
m_history [HISTORY_SIZE - 1] = cmd;
}
private void AppendToBuffer(ConsoleLine line)
{
lock (m_buffer) {
if (m_isNewLine) {
PushToBuffer (ConsoleLine.Empty);
m_isNewLine = false;
}
var merged = m_buffer [BUF_SIZE - 1].Line + line.Line;
var lines = SplitLine(merged);
m_buffer [BUF_SIZE - 1] = new ConsoleLine(line.Color, lines [0]);
m_isNewLine = lines.Length > 1;
for (int i = 1; i < lines.Length; i++) {
PushToBuffer (new ConsoleLine(line.Color, lines [i]));
}
DrawBuffer ();
}
}
private void AddToBuffer(ConsoleLine line)
{
lock (m_buffer) {
if (m_isNewLine) {
PushToBuffer (ConsoleLine.Empty);
m_isNewLine = false;
}
var merged = m_buffer [BUF_SIZE - 1].Line + line.Line;
var lines = SplitLine(merged);
m_buffer [BUF_SIZE - 1] = new ConsoleLine(line.Color, lines [0]);
m_isNewLine = true;
for (int i = 1; i < lines.Length; i++) {
PushToBuffer (new ConsoleLine(line.Color, lines [i]));
}
DrawBuffer ();
}
}
private string[] SplitLine(string line)
{
var lines = new List<string> ();
var rawlines = line.Replace("\r", "").Split ('\n');
foreach (var rl in rawlines) {
int idx = 0;
while (true) {
var ln = rl.Substring(idx, Math.Min(Width - 1, rl.Length - idx));
if (ln != string.Empty) {
lines.Add (ln);
idx += ln.Length;
} else
break;
}
}
return lines.ToArray ();
}
private void PushToBuffer(ConsoleLine line)
{
for (int idx = 0; idx < BUF_SIZE - 1; idx++) {
m_buffer [idx] = m_buffer [idx + 1];
}
m_buffer [BUF_SIZE - 1] = line;
}
private void ScrollBufferUp()
{
m_bufPos = Math.Max (Height - 1, m_bufPos - (Height - 1));
DrawBuffer ();
}
private void ScrollBufferDown()
{
m_bufPos = Math.Min (BUF_SIZE, m_bufPos + (Height - 1));
DrawBuffer ();
}
private void DrawBuffer()
{
lock (m_buffer) {
int bufOffset = m_bufPos - (Height - 1);
Console.SetCursorPosition (0, 0);
for (int idx = 0; idx < (Height - 1); idx++) {
var line = m_buffer [bufOffset + idx];
ApplyColorAspect (line.Color, () => Console.WriteLine (line.Line.PadRight(Width - 1)));
}
}
}
private void ApplyColorAspect(ConsoleColor clr, Action action)
{
var curClr = Console.ForegroundColor;
Console.ForegroundColor = clr;
action ();
Console.ForegroundColor = curClr;
}
}
}
| |
//---------------------------------------------------------------------------
//
// File: Journaling.cs
//
// Description: Contains various journaling related internal enums and classes
//
// History:
// 1/20/2005: [....] Branched off system/windows/navigation/JournalEntry.cs
//
// Copyright (C) 2006 by Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
using System;
using System.Security;
using System.Security.Permissions;
using System.Runtime.Serialization;
using System.Diagnostics;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Navigation;
using MS.Internal.Utility;
//In order to avoid generating warnings about unknown message numbers and
//unknown pragmas when compiling your C# source code with the actual C# compiler,
//you need to disable warnings 1634 and 1691. (Presharp Documentation)
#pragma warning disable 1634, 1691
namespace MS.Internal.AppModel
{
[Serializable]
internal enum JournalEntryType : byte
{
Navigable,
UiLess,
}
internal enum JournalReason
{
NewContentNavigation = 1, FragmentNavigation, AddBackEntry
};
/// <summary>
/// Encapsulates the custom journal state of an element implementing IJournalState.
/// </summary>
[Serializable]
internal abstract class CustomJournalStateInternal
{
/// <summary>
/// Called when the entire journal is about to be binary-serialized. Non-serializable objects
/// should be removed or replaced with serializable ones.
/// </summary>
internal virtual void PrepareForSerialization() { }
};
/// <summary>
/// Currently used in two contexts:
/// 1) Allows an element in the logical tree of INavigator.Content to implement "custom" journaling
/// of its state, beyond the DP journaling that DataStreams does.
/// [The public IProvideCustomContentState applies only to the root element.]
/// journalReason is always NewContentNavigation in this use.
/// Initially, the only actual use is for Frame to preserve its own journal.
/// 2) Root viewer journaling. See NavigationService.MakeJournalEntry()...
/// </summary>
internal interface IJournalState
{
CustomJournalStateInternal GetJournalState(JournalReason journalReason);
void RestoreJournalState(CustomJournalStateInternal state);
};
/// <summary>
/// Shared state for all journal entries associated with the same content object ("bind product").
/// Journal entries created for fragment navigations or CustomContentState navigations within the
/// current page share one JournalEntryGroupState object. This avoids duplication of state and
/// the problems described in bug 1216726.
/// </summary>
[Serializable]
internal class JournalEntryGroupState
{
internal JournalEntryGroupState() { }
internal JournalEntryGroupState(Guid navSvcId, uint contentId)
{
_navigationServiceId = navSvcId;
_contentId = contentId;
}
internal Guid NavigationServiceId
{
get { return _navigationServiceId; }
set { _navigationServiceId = value; }
}
/// <summary>
/// Unique identifier (within a NavigationService, not across the entire Journal) of the page
/// content ("bind product") this journal entry group is associated with.
/// One use of this property is to help us distinguish back/fwd navigations
/// within the same page from navigations to a different instance of the same page
/// (same URI, modulo #frament id). (Bugs 1187603 and 1187613).
/// Zero is not a valid id.
/// </summary>
internal uint ContentId
{
get { return _contentId; }
set
{
Debug.Assert(_contentId == 0 || _contentId == value,
"Once set, the ContentId for a JournalEntryGroup should not be changed.");
_contentId = value;
}
}
internal DataStreams JournalDataStreams
{
#if DEBUG
[DebuggerStepThrough]
#endif
get
{
// Do not make this getter create a new DataStreams object. Keep-alive journal entries
// don't need it.
return _journalDataStreams;
}
set
{
_journalDataStreams = value;
}
}
internal JournalEntry GroupExitEntry
{
get { return _groupExitEntry; }
set
{
Debug.Assert(value.JEGroupState == this);
Debug.Assert(_groupExitEntry == null || _groupExitEntry.ContentId == value.ContentId);
_groupExitEntry = value;
}
}
private Guid _navigationServiceId;
private uint _contentId;
private DataStreams _journalDataStreams;
private JournalEntry _groupExitEntry;
};
/// <summary>
/// The journal entry when journaling by URI. When navigating away, it will save the form state.
/// When navigating back/forwards to this entry, it will navigate back to the URI, and then
/// restore the form state.
/// </summary>
[Serializable]
internal class JournalEntryUri : JournalEntry, ISerializable
{
// Ctors
/////////////////////////////////////////////////////////////////////
#region Ctors
internal JournalEntryUri(JournalEntryGroupState jeGroupState, Uri uri)
: base(jeGroupState, uri)
{
}
/// <summary>
/// Serialization constructor. Marked Protected so derived classes can be deserialized correctly
/// </summary>
protected JournalEntryUri(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
#endregion
// Internal methods
/////////////////////////////////////////////////////////////////////
#region Internal methods
internal override void SaveState(object contentObject)
{
Invariant.Assert(this.Source != null, "Can't journal by Uri without a Uri.");
base.SaveState(contentObject); // Save controls state (JournalDataStreams).
}
#endregion
}
/// <summary>
/// This is the journal entry class for use when the entire tree is being kept alive. It will be
/// saved when navigated away from, and when restored, it navigates to the saved tree.
/// </summary>
// Not [Serializable], because keep-alive content should not be serialized into the TravelLog.
internal class JournalEntryKeepAlive : JournalEntry
{
// Ctors
/////////////////////////////////////////////////////////////////////
#region Ctors
internal JournalEntryKeepAlive(JournalEntryGroupState jeGroupState, Uri uri, object keepAliveRoot)
: base(jeGroupState, uri)
{
Invariant.Assert(keepAliveRoot != null);
_keepAliveRoot = keepAliveRoot;
}
#endregion
// Internal methods
/////////////////////////////////////////////////////////////////////
#region Internal methods
/// <summary>
/// This is how the JournalEntry holds on to the tree itself. There is no need to keep track of other
/// things c.f. AlivePageFunction.
/// </summary>
internal object KeepAliveRoot
{
get { return _keepAliveRoot; }
}
internal override bool IsAlive()
{
return this.KeepAliveRoot != null;
}
internal override void SaveState(object contentObject)
{
Debug.Assert(this.KeepAliveRoot == contentObject); // set by ctor; shouldn't change
this._keepAliveRoot = contentObject;
// No call to base.SaveState() since it saves controls state, and contentObject is KeepAlive.
}
internal override bool Navigate(INavigator navigator, NavigationMode navMode)
{
Debug.Assert(navMode == NavigationMode.Back || navMode == NavigationMode.Forward);
Debug.Assert(this.KeepAliveRoot != null);
return navigator.Navigate(this.KeepAliveRoot, new NavigateInfo(Source, navMode, this));
}
#endregion
#region Private fields
private object _keepAliveRoot; // the root of a tree being kept alive
#endregion
}
/// <summary>
/// The journal entry for page functions. Ideally, these would use the same journal method
/// that the other entries use, and derive from the other JournalEntry* classes to add the
/// small bit of functionality that the page functions require (the Finish handler, for one.)
/// </summary>
[Serializable]
internal abstract class JournalEntryPageFunction : JournalEntry, ISerializable
{
// Ctors
/////////////////////////////////////////////////////////////////////
#region Ctors
internal JournalEntryPageFunction(JournalEntryGroupState jeGroupState, PageFunctionBase pageFunction)
: base(jeGroupState, null)
{
PageFunctionId = pageFunction.PageFunctionId;
ParentPageFunctionId = pageFunction.ParentPageFunctionId;
}
/// <summary>
/// Serialization constructor. Marked Protected so derived classes can be deserialized correctly
/// The base implementation needs to be called if this class is overridden
/// </summary>
protected JournalEntryPageFunction(SerializationInfo info, StreamingContext context)
: base(info, context)
{
_pageFunctionId = (Guid)info.GetValue("_pageFunctionId", typeof(Guid));
_parentPageFunctionId = (Guid)info.GetValue("_parentPageFunctionId", typeof(Guid)); ;
}
//
// ISerializable implementation
//
/// <SecurityNote>
/// Critical: does object serialization
/// Public OK: has a LinkDemand
/// </SecurityNote>
[SecurityCritical]
[SecurityPermissionAttribute(SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("_pageFunctionId", _pageFunctionId);
info.AddValue("_parentPageFunctionId", _parentPageFunctionId);
}
#endregion
// Internal Properties
/////////////////////////////////////////////////////////////////////
/// <summary>
/// This is the GUID for this PageFunction. It will be used as its childrens'
/// ParentPageFunctionId.
/// </summary>
internal Guid PageFunctionId
{
get { return _pageFunctionId; }
set { _pageFunctionId = value; }
}
/// <summary>
/// If this PageFunction is a child PageFunction, this will be the GUID of its
/// parent PageFunction. If this is Guid.Empty, then the parent is NOT a
/// PageFunction.
/// </summary>
internal Guid ParentPageFunctionId
{
get { return _parentPageFunctionId; }
set { _parentPageFunctionId = value; }
}
// Internal methods
/////////////////////////////////////////////////////////////////////
#region Internal methods
internal override bool IsPageFunction()
{
return true;
}
internal override bool IsAlive()
{
return false;
}
/// <summary>
/// Reconstitutes the PageFunction associated with this journal entry so that it can be
/// re-navigated to. Happens when returning from a child PF or doing journal navigation.
/// </summary>
internal abstract PageFunctionBase ResumePageFunction();
#endregion
#region internal Static method
//
// This method is to get the journal entry index in the Journal List for the parent page
// of this PageFunction.
//
// The parent page could be a PageFunction or a Non-PageFunction.
// For the non PageFunction case, it could have a Uri or could not have a Uri.
//
// Case 1: The ParentPageFunction has been set, so just go back and look for it.
// Case 2: The ParentPageFunction has NOT been set, so the parent must be most recent non-PF entry.
//
internal static int GetParentPageJournalIndex(NavigationService NavigationService, Journal journal, PageFunctionBase endingPF)
{
JournalEntryPageFunction pageFunctionEntry;
JournalEntry journalEntry;
for (int index = journal.CurrentIndex - 1; index >= 0; --index)
{
journalEntry = journal[index];
// Be sure that the navigation containers match
if (journalEntry.NavigationServiceId != NavigationService.GuidId)
continue;
pageFunctionEntry = journalEntry as JournalEntryPageFunction;
if (endingPF.ParentPageFunctionId == Guid.Empty)
{
// We are looking for a non-PageFunction
if (pageFunctionEntry == null)
{
return index; // found!
}
}
else
{
// we are looking for a PageFunction
if ((pageFunctionEntry != null) && (pageFunctionEntry.PageFunctionId == endingPF.ParentPageFunctionId))
{
return index; // found!
}
}
}
Debug.Assert(endingPF.ParentPageFunctionId == Guid.Empty,
"Should have been able to find the parent if the ParentPageFunctionId was set. Are they in different NavigationServices? They shouldn't be.");
return _NoParentPage;
}
#endregion
// Private fields
//
// If you add any fields here, check if it needs to be serialized.
// If yes, then add it to the ISerializable implementation and make
// corresponding changes in the Serialization constructor.
//
/////////////////////////////////////////////////////////////////////
private Guid _pageFunctionId;
private Guid _parentPageFunctionId;
internal const int _NoParentPage = -1;
}
/// <summary>
/// This is the class for page functions that are being kept alive.
/// </summary>
// Not [Serializable], because keep-alive content should not be serialized into the TravelLog.
internal class JournalEntryPageFunctionKeepAlive : JournalEntryPageFunction
{
// Ctors
/////////////////////////////////////////////////////////////////////
#region Ctors
internal JournalEntryPageFunctionKeepAlive(JournalEntryGroupState jeGroupState, PageFunctionBase pageFunction)
: base(jeGroupState, pageFunction)
{
Debug.Assert(pageFunction != null && pageFunction.KeepAlive);
this._keepAlivePageFunction = pageFunction;
}
#endregion
// Internal methods
/////////////////////////////////////////////////////////////////////
#region Internal methods
internal override bool IsPageFunction()
{
return true;
}
internal override bool IsAlive()
{
return this.KeepAlivePageFunction != null;
}
internal PageFunctionBase KeepAlivePageFunction
{
get { return _keepAlivePageFunction; }
}
internal override PageFunctionBase ResumePageFunction()
{
PageFunctionBase pageFunction = this.KeepAlivePageFunction;
pageFunction._Resume = true;
return pageFunction;
}
internal override void SaveState(object contentObject)
{
Invariant.Assert(_keepAlivePageFunction == contentObject); // set by ctor
// No call to base.SaveState() since it saves controls state, and this PF is KeepAlive.
}
/// <summary>
/// This override is used when doing journal navigation to a PF, not when it is resumed after
/// a child PF finishes.
/// </summary>
internal override bool Navigate(INavigator navigator, NavigationMode navMode)
{
Debug.Assert(navMode == NavigationMode.Back || navMode == NavigationMode.Forward);
// When doing fragment navigation within the PF, it should not be marked as Resumed;
// otherwise, its Start() override may not be called.
PageFunctionBase pf = (navigator.Content == _keepAlivePageFunction) ?
_keepAlivePageFunction : ResumePageFunction();
Debug.Assert(pf != null);
return navigator.Navigate(pf, new NavigateInfo(this.Source, navMode, this));
}
#endregion
#region Private fields
PageFunctionBase _keepAlivePageFunction = null;
#endregion
}
/// <summary>
/// JournalEntryPageFunctionSaver
/// This is JournalEntry for PageFunction which is not set as KeepAlive. The PageFunction could be
/// navigated from a Uri or the instance created from a PageFunction type.
/// </summary>
[Serializable]
internal abstract class JournalEntryPageFunctionSaver : JournalEntryPageFunction, ISerializable
{
// Ctors
/////////////////////////////////////////////////////////////////////
#region Ctors
//
// Ctor of JournalEntryPageFunctionSaver
//
internal JournalEntryPageFunctionSaver(JournalEntryGroupState jeGroupState, PageFunctionBase pageFunction)
: base(jeGroupState, pageFunction)
{
Debug.Assert(!pageFunction.KeepAlive);
}
/// <summary>
/// Serialization constructor. Marked Protected so derived classes can be deserialized correctly
/// The base implementation needs to be called if this class is overridden
/// </summary>
protected JournalEntryPageFunctionSaver(SerializationInfo info, StreamingContext context)
: base(info, context)
{
_returnEventSaver = (ReturnEventSaver)info.GetValue("_returnEventSaver", typeof(ReturnEventSaver));
}
//
// ISerializable implementation
//
/// <SecurityNote>
/// Critical: does object serialization
/// Public OK: has a LinkDemand
/// </SecurityNote>
[SecurityCritical]
[SecurityPermissionAttribute(SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("_returnEventSaver", _returnEventSaver);
}
#endregion
// Internal methods
/////////////////////////////////////////////////////////////////////
#region Internal methods
internal override void SaveState(object contentObject)
{
PageFunctionBase pageFunction = (PageFunctionBase)contentObject;
_returnEventSaver = pageFunction._Saver;
base.SaveState(contentObject); // Save controls state (JournalDataStreams).
}
//
// Take the PageFunction specific setting, then call the RestoreState in base class
// to store previous state in a journal navigation.
//
internal override void RestoreState(object contentObject)
{
if (contentObject == null)
throw new ArgumentNullException("contentObject");
PageFunctionBase pageFunction = (PageFunctionBase)contentObject;
if (pageFunction == null)
{
throw new Exception(SR.Get(SRID.InvalidPageFunctionType, contentObject.GetType( )));
}
pageFunction.ParentPageFunctionId = ParentPageFunctionId;
pageFunction.PageFunctionId = PageFunctionId;
pageFunction._Saver = _returnEventSaver; // saved Return event delegate from the *parent* of this PF
pageFunction._Resume = true;
base.RestoreState(pageFunction);
}
/// <summary>
/// This override is used when doing journal navigation to a PF, not when it is resumed after
/// a child PF finishes.
/// </summary>
internal override bool Navigate(INavigator navigator, NavigationMode navMode)
{
Debug.Assert(navMode == NavigationMode.Back || navMode == NavigationMode.Forward);
// Resume the PF and navigate to it.
// Special case: doing fragment navigation or CustomContentState navigation
// within a PF. Then don't create a new PF object!
IDownloader idl = navigator as IDownloader;
NavigationService ns = idl != null ? idl.Downloader : null;
Debug.Assert(ns != null, "Fragment navigation won't work when the INavigator doesn't have a NavigationService.");
PageFunctionBase pageFunction =
(ns != null && ns.ContentId == this.ContentId) ?
(PageFunctionBase)ns.Content : ResumePageFunction();
Debug.Assert(pageFunction != null);
return navigator.Navigate(pageFunction, new NavigateInfo(this.Source, navMode, this));
}
#endregion
// Internal properties
/////////////////////////////////////////////////////////////////////
#region Internal properties
#endregion
// private methods
/////////////////////////////////////////////////////////////////////
// Private fields
//
// If you add any fields here, check if it needs to be serialized.
// If yes, then add it to the ISerializable implementation and make
// corresponding changes in the Serialization constructor.
//
/////////////////////////////////////////////////////////////////////
#region Private fields
private ReturnEventSaver _returnEventSaver;
#endregion
}
//
// When the PageFunction is implemented in a pure code file without Xaml file involved,
// and the instance of such PageFunction was passed to Navigiation method, JournalEntryPageFunctionType
// would be created to save journal data information.
//
[Serializable]
internal class JournalEntryPageFunctionType : JournalEntryPageFunctionSaver, ISerializable
{
// Ctors
/////////////////////////////////////////////////////////////////////
#region Ctors
/// <SecurityNote>
/// Critical: Sets the crtical _typeName.
/// Safe: The type is a subtype of PageFunctionBase, and the application has access to it.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal JournalEntryPageFunctionType(JournalEntryGroupState jeGroupState, PageFunctionBase pageFunction)
: base(jeGroupState, pageFunction)
{
string typeName = pageFunction.GetType().AssemblyQualifiedName;
this._typeName = new SecurityCriticalDataForSet<string>(typeName);
}
/// <summary>
/// Serialization constructor. Marked Protected so derived classes can be deserialized correctly
/// The base implementation needs to be called if this class is overridden
/// </summary>
/// <SecurityNote>
/// Critical: Sets the critical _typeName.
/// </SecurityNote>
[SecurityCritical]
protected JournalEntryPageFunctionType(SerializationInfo info, StreamingContext context)
: base(info, context)
{
_typeName = new SecurityCriticalDataForSet<string>(info.GetString("_typeName"));
}
//
// ISerializable implementation
//
/// <SecurityNote>
/// Critical: does object serialization
/// Public OK: has a LinkDemand
/// </SecurityNote>
[SecurityCritical]
[SecurityPermissionAttribute(SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("_typeName", _typeName.Value);
}
#endregion
// Internal methods
/////////////////////////////////////////////////////////////////////
#region Internal methods
internal override void SaveState(object contentObject)
{
Debug.Assert(contentObject.GetType().AssemblyQualifiedName == this._typeName.Value,
"The type of a PageFunction a journal entry is associated with cannot change.");
base.SaveState(contentObject); // Save controls state (JournalDataStreams).
}
//
// Reconstitutes the PageFunction associated with this journal entry so that it can be
// re-navigated to. Happens when returning from a child PF or doing journal navigation.
//
// The PageFunction should be implemented in pure code file without xaml file involved.
//
/// <SecurityNote>
/// Critical: Asserts ReflectionPermission to create an instance of the page function type.
/// Safe: The object created is of the same type that the application originally navigated to.
/// It is necessarily derived from PageFunctionBase.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal override PageFunctionBase ResumePageFunction()
{
PageFunctionBase pageFunction;
Invariant.Assert(this._typeName.Value != null, "JournalEntry does not contain the Type for the PageFunction to be created");
//First try Type.GetType from the saved typename, then try Activator.CreateInstanceFrom
//Type.GetType - Since the typename is fullyqualified
//we will end up using the default binding mechanism to locate and bind to the assembly.
//If the assembly was not a strongly named one nor is present in the APPBASE, this will
//fail.
Type pfType = Type.GetType(this._typeName.Value);
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert();
try
{
pageFunction = (PageFunctionBase)Activator.CreateInstance(pfType);
}
catch (Exception ex)
{
throw new Exception(SR.Get(SRID.FailedResumePageFunction, this._typeName.Value), ex);
}
finally
{
ReflectionPermission.RevertAssert();
}
InitializeComponent(pageFunction);
RestoreState(pageFunction);
return pageFunction;
}
#endregion
#region private method
private void InitializeComponent(PageFunctionBase pageFunction)
{
// Need to explicitly add a call to InitializeComponent() for Page
IComponentConnector iComponentConnector = pageFunction as IComponentConnector;
if (iComponentConnector != null)
{
iComponentConnector.InitializeComponent();
}
}
#endregion
// private methods
/////////////////////////////////////////////////////////////////////
// Private fields
//
// If you add any fields here, check if it needs to be serialized.
// If yes, then add it to the ISerializable implementation and make
// corresponding changes in the Serialization constructor.
//
/////////////////////////////////////////////////////////////////////
#region Private fields
/// AssemblyQualifiedName of the PageFunction Type
/// <SecurityNote>
/// Critical: The type name is used to create an instance under elevation. We have to make
/// sure that it is the same page function type that the application originally navigated to.
/// </SecurityNote>
private SecurityCriticalDataForSet<string> _typeName;
#endregion
}
//
// When the PageFunction is implemented in a xaml file, or it was navigated from a Uri,
// JournalEntryPageFunctionUri would be created to save journal data information.
//
[Serializable]
internal class JournalEntryPageFunctionUri : JournalEntryPageFunctionSaver, ISerializable
{
// Ctors
/////////////////////////////////////////////////////////////////////
#region Ctors
internal JournalEntryPageFunctionUri(JournalEntryGroupState jeGroupState, PageFunctionBase pageFunction, Uri markupUri)
: base(jeGroupState, pageFunction)
{
_markupUri = markupUri;
}
protected JournalEntryPageFunctionUri(SerializationInfo info, StreamingContext context)
: base(info, context)
{
_markupUri = (Uri)info.GetValue("_markupUri", typeof(Uri));
}
//
// ISerializable implementation
//
/// <SecurityNote>
/// Critical: does object serialization
/// Public OK: has a LinkDemand
/// </SecurityNote>
[SecurityCritical]
[SecurityPermissionAttribute(SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("_markupUri", _markupUri);
}
#endregion
// Internal methods
/////////////////////////////////////////////////////////////////////
#region Internal methods
//
// Create an instance of PageFunction for Resume purpose. this PageFunction should be created
// from a Uri.
//
internal override PageFunctionBase ResumePageFunction()
{
PageFunctionBase pageFunction;
//
// The page function was compiled from a xaml file.
//
// We should pay more attention on this scenario. The instance of PageFunction is created from
// the baml stream, but it should ignore the value setting for all the Journal-able properties
// and elements while the tree is created from the original baml stream.
//
Debug.Assert(_markupUri != null, "_markupUri in JournalEntryPageFunctionUri should be set.");
pageFunction = Application.LoadComponent(_markupUri, true) as PageFunctionBase;
RestoreState(pageFunction);
return pageFunction;
}
#endregion
// Private field
#region private fields
//
// Keep the Uri that is associated with current PageFunction page.
// It could be Navigator.Source or the Uri of Baml resource for the PageFunction type.
//
// Notes: We don't mix this with JournalEntry.Source, since NavigationService has some special usage
// for JE.Source, JE.Source could affect the Navigator.Source in some scenario.
//
private Uri _markupUri;
#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.Generic;
using System.Text;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#elif DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
using Newtonsoft.Json;
using System.IO;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Tests.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
namespace Newtonsoft.Json.Tests.Linq
{
[TestFixture]
public class JTokenReaderTest : TestFixtureBase
{
[Test]
public void ErrorTokenIndex()
{
JObject json = JObject.Parse(@"{""IntList"":[1, ""two""]}");
ExceptionAssert.Throws<Exception>(() =>
{
JsonSerializer serializer = new JsonSerializer();
serializer.Deserialize<TraceTestObject>(json.CreateReader());
}, "Could not convert string to integer: two. Path 'IntList[1]', line 1, position 20.");
}
#if !NET20
[Test]
public void YahooFinance()
{
JObject o =
new JObject(
new JProperty("Test1", new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc)),
new JProperty("Test2", new DateTimeOffset(2000, 10, 15, 5, 5, 5, new TimeSpan(11, 11, 0))),
new JProperty("Test3", "Test3Value"),
new JProperty("Test4", null)
);
using (JTokenReader jsonReader = new JTokenReader(o))
{
IJsonLineInfo lineInfo = jsonReader;
jsonReader.Read();
Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType);
Assert.AreEqual(false, lineInfo.HasLineInfo());
jsonReader.Read();
Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType);
Assert.AreEqual("Test1", jsonReader.Value);
Assert.AreEqual(false, lineInfo.HasLineInfo());
jsonReader.Read();
Assert.AreEqual(JsonToken.Date, jsonReader.TokenType);
Assert.AreEqual(new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc), jsonReader.Value);
Assert.AreEqual(false, lineInfo.HasLineInfo());
Assert.AreEqual(0, lineInfo.LinePosition);
Assert.AreEqual(0, lineInfo.LineNumber);
jsonReader.Read();
Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType);
Assert.AreEqual("Test2", jsonReader.Value);
jsonReader.Read();
Assert.AreEqual(JsonToken.Date, jsonReader.TokenType);
Assert.AreEqual(new DateTimeOffset(2000, 10, 15, 5, 5, 5, new TimeSpan(11, 11, 0)), jsonReader.Value);
jsonReader.Read();
Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType);
Assert.AreEqual("Test3", jsonReader.Value);
jsonReader.Read();
Assert.AreEqual(JsonToken.String, jsonReader.TokenType);
Assert.AreEqual("Test3Value", jsonReader.Value);
jsonReader.Read();
Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType);
Assert.AreEqual("Test4", jsonReader.Value);
jsonReader.Read();
Assert.AreEqual(JsonToken.Null, jsonReader.TokenType);
Assert.AreEqual(null, jsonReader.Value);
Assert.IsTrue(jsonReader.Read());
Assert.AreEqual(JsonToken.EndObject, jsonReader.TokenType);
Assert.IsFalse(jsonReader.Read());
Assert.AreEqual(JsonToken.None, jsonReader.TokenType);
}
using (JsonReader jsonReader = new JTokenReader(o.Property("Test2")))
{
Assert.IsTrue(jsonReader.Read());
Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType);
Assert.AreEqual("Test2", jsonReader.Value);
Assert.IsTrue(jsonReader.Read());
Assert.AreEqual(JsonToken.Date, jsonReader.TokenType);
Assert.AreEqual(new DateTimeOffset(2000, 10, 15, 5, 5, 5, new TimeSpan(11, 11, 0)), jsonReader.Value);
Assert.IsFalse(jsonReader.Read());
Assert.AreEqual(JsonToken.None, jsonReader.TokenType);
}
}
[Test]
public void ReadAsDateTimeOffsetBadString()
{
string json = @"{""Offset"":""blablahbla""}";
JObject o = JObject.Parse(json);
JsonReader reader = o.CreateReader();
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsDateTimeOffset(); }, "Could not convert string to DateTimeOffset: blablahbla. Path 'Offset', line 1, position 22.");
}
[Test]
public void ReadAsDateTimeOffsetBoolean()
{
string json = @"{""Offset"":true}";
JObject o = JObject.Parse(json);
JsonReader reader = o.CreateReader();
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsDateTimeOffset(); }, "Error reading date. Unexpected token: Boolean. Path 'Offset', line 1, position 14.");
}
[Test]
public void ReadAsDateTimeOffsetString()
{
string json = @"{""Offset"":""2012-01-24T03:50Z""}";
JObject o = JObject.Parse(json);
JsonReader reader = o.CreateReader();
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
reader.ReadAsDateTimeOffset();
Assert.AreEqual(JsonToken.Date, reader.TokenType);
Assert.AreEqual(typeof(DateTimeOffset), reader.ValueType);
Assert.AreEqual(new DateTimeOffset(2012, 1, 24, 3, 50, 0, TimeSpan.Zero), reader.Value);
}
#endif
[Test]
public void ReadLineInfo()
{
string input = @"{
CPU: 'Intel',
Drives: [
'DVD read/writer',
""500 gigabyte hard drive""
]
}";
JObject o = JObject.Parse(input);
using (JTokenReader jsonReader = new JTokenReader(o))
{
IJsonLineInfo lineInfo = jsonReader;
Assert.AreEqual(jsonReader.TokenType, JsonToken.None);
Assert.AreEqual(0, lineInfo.LineNumber);
Assert.AreEqual(0, lineInfo.LinePosition);
Assert.AreEqual(false, lineInfo.HasLineInfo());
Assert.AreEqual(null, jsonReader.CurrentToken);
jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.StartObject);
Assert.AreEqual(1, lineInfo.LineNumber);
Assert.AreEqual(1, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o, jsonReader.CurrentToken);
jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName);
Assert.AreEqual(jsonReader.Value, "CPU");
Assert.AreEqual(2, lineInfo.LineNumber);
Assert.AreEqual(6, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o.Property("CPU"), jsonReader.CurrentToken);
jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.String);
Assert.AreEqual(jsonReader.Value, "Intel");
Assert.AreEqual(2, lineInfo.LineNumber);
Assert.AreEqual(14, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o.Property("CPU").Value, jsonReader.CurrentToken);
jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName);
Assert.AreEqual(jsonReader.Value, "Drives");
Assert.AreEqual(3, lineInfo.LineNumber);
Assert.AreEqual(9, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o.Property("Drives"), jsonReader.CurrentToken);
jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.StartArray);
Assert.AreEqual(3, lineInfo.LineNumber);
Assert.AreEqual(11, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o.Property("Drives").Value, jsonReader.CurrentToken);
jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.String);
Assert.AreEqual(jsonReader.Value, "DVD read/writer");
Assert.AreEqual(4, lineInfo.LineNumber);
Assert.AreEqual(21, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o["Drives"][0], jsonReader.CurrentToken);
jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.String);
Assert.AreEqual(jsonReader.Value, "500 gigabyte hard drive");
Assert.AreEqual(5, lineInfo.LineNumber);
Assert.AreEqual(29, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o["Drives"][1], jsonReader.CurrentToken);
jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.EndArray);
Assert.AreEqual(3, lineInfo.LineNumber);
Assert.AreEqual(11, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o["Drives"], jsonReader.CurrentToken);
jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.EndObject);
Assert.AreEqual(1, lineInfo.LineNumber);
Assert.AreEqual(1, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o, jsonReader.CurrentToken);
jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.None);
Assert.AreEqual(null, jsonReader.CurrentToken);
jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.None);
Assert.AreEqual(null, jsonReader.CurrentToken);
}
}
[Test]
public void ReadBytes()
{
byte[] data = Encoding.UTF8.GetBytes("Hello world!");
JObject o =
new JObject(
new JProperty("Test1", data)
);
using (JTokenReader jsonReader = new JTokenReader(o))
{
jsonReader.Read();
Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType);
jsonReader.Read();
Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType);
Assert.AreEqual("Test1", jsonReader.Value);
byte[] readBytes = jsonReader.ReadAsBytes();
Assert.AreEqual(data, readBytes);
Assert.IsTrue(jsonReader.Read());
Assert.AreEqual(JsonToken.EndObject, jsonReader.TokenType);
Assert.IsFalse(jsonReader.Read());
Assert.AreEqual(JsonToken.None, jsonReader.TokenType);
}
}
[Test]
public void ReadBytesFailure()
{
ExceptionAssert.Throws<JsonReaderException>(() =>
{
JObject o =
new JObject(
new JProperty("Test1", 1)
);
using (JTokenReader jsonReader = new JTokenReader(o))
{
jsonReader.Read();
Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType);
jsonReader.Read();
Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType);
Assert.AreEqual("Test1", jsonReader.Value);
jsonReader.ReadAsBytes();
}
}, "Error reading bytes. Unexpected token: Integer. Path 'Test1'.");
}
public class HasBytes
{
public byte[] Bytes { get; set; }
}
[Test]
public void ReadBytesFromString()
{
var bytes = new HasBytes { Bytes = new byte[] { 1, 2, 3, 4 } };
var json = JsonConvert.SerializeObject(bytes);
TextReader textReader = new StringReader(json);
JsonReader jsonReader = new JsonTextReader(textReader);
var jToken = JToken.ReadFrom(jsonReader);
jsonReader = new JTokenReader(jToken);
var result2 = (HasBytes)JsonSerializer.Create(null)
.Deserialize(jsonReader, typeof(HasBytes));
CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 4 }, result2.Bytes);
}
[Test]
public void ReadBytesFromEmptyString()
{
var bytes = new HasBytes { Bytes = new byte[0] };
var json = JsonConvert.SerializeObject(bytes);
TextReader textReader = new StringReader(json);
JsonReader jsonReader = new JsonTextReader(textReader);
var jToken = JToken.ReadFrom(jsonReader);
jsonReader = new JTokenReader(jToken);
var result2 = (HasBytes)JsonSerializer.Create(null)
.Deserialize(jsonReader, typeof(HasBytes));
CollectionAssert.AreEquivalent(new byte[0], result2.Bytes);
}
public class ReadAsBytesTestObject
{
public byte[] Data;
}
[Test]
public void ReadAsBytesNull()
{
JsonSerializer s = new JsonSerializer();
JToken nullToken = JToken.ReadFrom(new JsonTextReader(new StringReader("{ Data: null }")));
ReadAsBytesTestObject x = s.Deserialize<ReadAsBytesTestObject>(new JTokenReader(nullToken));
Assert.IsNull(x.Data);
}
[Test]
public void DeserializeByteArrayWithTypeNameHandling()
{
TestObject test = new TestObject("Test", new byte[] { 72, 63, 62, 71, 92, 55 });
string json = JsonConvert.SerializeObject(test, Formatting.Indented, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
});
JObject o = JObject.Parse(json);
JsonSerializer serializer = new JsonSerializer();
serializer.TypeNameHandling = TypeNameHandling.All;
using (JsonReader nodeReader = o.CreateReader())
{
// Get exception here
TestObject newObject = (TestObject)serializer.Deserialize(nodeReader);
Assert.AreEqual("Test", newObject.Name);
CollectionAssert.AreEquivalent(new byte[] { 72, 63, 62, 71, 92, 55 }, newObject.Data);
}
}
[Test]
public void DeserializeStringInt()
{
string json = @"{
""PreProperty"": ""99"",
""PostProperty"": ""-1""
}";
JObject o = JObject.Parse(json);
JsonSerializer serializer = new JsonSerializer();
using (JsonReader nodeReader = o.CreateReader())
{
MyClass c = serializer.Deserialize<MyClass>(nodeReader);
Assert.AreEqual(99, c.PreProperty);
Assert.AreEqual(-1, c.PostProperty);
}
}
[Test]
public void ReadAsDecimalInt()
{
string json = @"{""Name"":1}";
JObject o = JObject.Parse(json);
JsonReader reader = o.CreateReader();
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
reader.ReadAsDecimal();
Assert.AreEqual(JsonToken.Float, reader.TokenType);
Assert.AreEqual(typeof(decimal), reader.ValueType);
Assert.AreEqual(1m, reader.Value);
}
[Test]
public void ReadAsInt32Int()
{
string json = @"{""Name"":1}";
JObject o = JObject.Parse(json);
JTokenReader reader = (JTokenReader)o.CreateReader();
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.AreEqual(o, reader.CurrentToken);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.AreEqual(o.Property("Name"), reader.CurrentToken);
reader.ReadAsInt32();
Assert.AreEqual(o["Name"], reader.CurrentToken);
Assert.AreEqual(JsonToken.Integer, reader.TokenType);
Assert.AreEqual(typeof(int), reader.ValueType);
Assert.AreEqual(1, reader.Value);
}
[Test]
public void ReadAsInt32BadString()
{
string json = @"{""Name"":""hi""}";
JObject o = JObject.Parse(json);
JsonReader reader = o.CreateReader();
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsInt32(); }, "Could not convert string to integer: hi. Path 'Name', line 1, position 12.");
}
[Test]
public void ReadAsInt32Boolean()
{
string json = @"{""Name"":true}";
JObject o = JObject.Parse(json);
JsonReader reader = o.CreateReader();
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsInt32(); }, "Error reading integer. Unexpected token: Boolean. Path 'Name', line 1, position 12.");
}
[Test]
public void ReadAsDecimalString()
{
string json = @"{""Name"":""1.1""}";
JObject o = JObject.Parse(json);
JsonReader reader = o.CreateReader();
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
reader.ReadAsDecimal();
Assert.AreEqual(JsonToken.Float, reader.TokenType);
Assert.AreEqual(typeof(decimal), reader.ValueType);
Assert.AreEqual(1.1m, reader.Value);
}
[Test]
public void ReadAsDecimalBadString()
{
string json = @"{""Name"":""blah""}";
JObject o = JObject.Parse(json);
JsonReader reader = o.CreateReader();
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsDecimal(); }, "Could not convert string to decimal: blah. Path 'Name', line 1, position 14.");
}
[Test]
public void ReadAsDecimalBoolean()
{
string json = @"{""Name"":true}";
JObject o = JObject.Parse(json);
JsonReader reader = o.CreateReader();
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsDecimal(); }, "Error reading decimal. Unexpected token: Boolean. Path 'Name', line 1, position 12.");
}
[Test]
public void ReadAsDecimalNull()
{
string json = @"{""Name"":null}";
JObject o = JObject.Parse(json);
JsonReader reader = o.CreateReader();
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
reader.ReadAsDecimal();
Assert.AreEqual(JsonToken.Null, reader.TokenType);
Assert.AreEqual(null, reader.ValueType);
Assert.AreEqual(null, reader.Value);
}
[Test]
public void InitialPath_PropertyBase_PropertyToken()
{
JObject o = new JObject
{
{ "prop1", true }
};
JTokenReader reader = new JTokenReader(o, "baseprop");
Assert.AreEqual("baseprop", reader.Path);
Assert.IsTrue(reader.Read());
Assert.AreEqual("baseprop", reader.Path);
Assert.IsTrue(reader.Read());
Assert.AreEqual("baseprop.prop1", reader.Path);
Assert.IsTrue(reader.Read());
Assert.AreEqual("baseprop.prop1", reader.Path);
Assert.IsTrue(reader.Read());
Assert.AreEqual("baseprop", reader.Path);
Assert.IsFalse(reader.Read());
Assert.AreEqual("baseprop", reader.Path);
}
[Test]
public void InitialPath_ArrayBase_PropertyToken()
{
JObject o = new JObject
{
{ "prop1", true }
};
JTokenReader reader = new JTokenReader(o, "[0]");
Assert.AreEqual("[0]", reader.Path);
Assert.IsTrue(reader.Read());
Assert.AreEqual("[0]", reader.Path);
Assert.IsTrue(reader.Read());
Assert.AreEqual("[0].prop1", reader.Path);
Assert.IsTrue(reader.Read());
Assert.AreEqual("[0].prop1", reader.Path);
Assert.IsTrue(reader.Read());
Assert.AreEqual("[0]", reader.Path);
Assert.IsFalse(reader.Read());
Assert.AreEqual("[0]", reader.Path);
}
[Test]
public void InitialPath_PropertyBase_ArrayToken()
{
JArray a = new JArray
{
1, 2
};
JTokenReader reader = new JTokenReader(a, "baseprop");
Assert.AreEqual("baseprop", reader.Path);
Assert.IsTrue(reader.Read());
Assert.AreEqual("baseprop", reader.Path);
Assert.IsTrue(reader.Read());
Assert.AreEqual("baseprop[0]", reader.Path);
Assert.IsTrue(reader.Read());
Assert.AreEqual("baseprop[1]", reader.Path);
Assert.IsTrue(reader.Read());
Assert.AreEqual("baseprop", reader.Path);
Assert.IsFalse(reader.Read());
Assert.AreEqual("baseprop", reader.Path);
}
[Test]
public void InitialPath_ArrayBase_ArrayToken()
{
JArray a = new JArray
{
1, 2
};
JTokenReader reader = new JTokenReader(a, "[0]");
Assert.AreEqual("[0]", reader.Path);
Assert.IsTrue(reader.Read());
Assert.AreEqual("[0]", reader.Path);
Assert.IsTrue(reader.Read());
Assert.AreEqual("[0][0]", reader.Path);
Assert.IsTrue(reader.Read());
Assert.AreEqual("[0][1]", reader.Path);
Assert.IsTrue(reader.Read());
Assert.AreEqual("[0]", reader.Path);
Assert.IsFalse(reader.Read());
Assert.AreEqual("[0]", reader.Path);
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System
{
#if NETFRAMEWORK_4_0 || SILVERLIGHT_5_0
public delegate void Action<T1, T2, T3, T4, T5, T6> (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
public delegate void Action<T1, T2, T3, T4, T5> (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
public delegate void Action<T1, T2, T3, T4, T5, T6, T7, T8> (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
public delegate void Action<T1, T2, T3, T4, T5, T6, T7> (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
public delegate void Action<T1, T2, T3> (T1 arg1, T2 arg2, T3 arg3);
public delegate void Action<T1, T2, T3, T4> (T1 arg1, T2 arg2, T3 arg3, T4 arg4);
public delegate void Action<T1, T2> (T1 arg1, T2 arg2);
public delegate void Action ();
#endif
#if !SILVERLIGHT_4_0_WP
public delegate void AppDomainInitializer (string[] args);
#endif
#if !SILVERLIGHT
public enum AppDomainManagerInitializationOptions
{
None = 0,
RegisterWithHost = 1,
}
public enum ConsoleColor
{
Black = 0,
DarkBlue = 1,
DarkGreen = 2,
DarkCyan = 3,
DarkRed = 4,
DarkMagenta = 5,
DarkYellow = 6,
Gray = 7,
DarkGray = 8,
Blue = 9,
Green = 10,
Cyan = 11,
Red = 12,
Magenta = 13,
Yellow = 14,
White = 15,
}
public enum ConsoleKey
{
Backspace = 8,
Tab = 9,
Clear = 12,
Enter = 13,
Pause = 19,
Escape = 27,
Spacebar = 32,
PageUp = 33,
PageDown = 34,
End = 35,
Home = 36,
LeftArrow = 37,
UpArrow = 38,
RightArrow = 39,
DownArrow = 40,
Select = 41,
Print = 42,
Execute = 43,
PrintScreen = 44,
Insert = 45,
Delete = 46,
Help = 47,
D0 = 48,
D1 = 49,
D2 = 50,
D3 = 51,
D4 = 52,
D5 = 53,
D6 = 54,
D7 = 55,
D8 = 56,
D9 = 57,
A = 65,
B = 66,
C = 67,
D = 68,
E = 69,
F = 70,
G = 71,
H = 72,
I = 73,
J = 74,
K = 75,
L = 76,
M = 77,
N = 78,
O = 79,
P = 80,
Q = 81,
R = 82,
S = 83,
T = 84,
U = 85,
V = 86,
W = 87,
X = 88,
Y = 89,
Z = 90,
LeftWindows = 91,
RightWindows = 92,
Applications = 93,
Sleep = 95,
NumPad0 = 96,
NumPad1 = 97,
NumPad2 = 98,
NumPad3 = 99,
NumPad4 = 100,
NumPad5 = 101,
NumPad6 = 102,
NumPad7 = 103,
NumPad8 = 104,
NumPad9 = 105,
Multiply = 106,
Add = 107,
Separator = 108,
Subtract = 109,
Decimal = 110,
Divide = 111,
F1 = 112,
F2 = 113,
F3 = 114,
F4 = 115,
F5 = 116,
F6 = 117,
F7 = 118,
F8 = 119,
F9 = 120,
F10 = 121,
F11 = 122,
F12 = 123,
F13 = 124,
F14 = 125,
F15 = 126,
F16 = 127,
F17 = 128,
F18 = 129,
F19 = 130,
F20 = 131,
F21 = 132,
F22 = 133,
F23 = 134,
F24 = 135,
BrowserBack = 166,
BrowserForward = 167,
BrowserRefresh = 168,
BrowserStop = 169,
BrowserSearch = 170,
BrowserFavorites = 171,
BrowserHome = 172,
VolumeMute = 173,
VolumeDown = 174,
VolumeUp = 175,
MediaNext = 176,
MediaPrevious = 177,
MediaStop = 178,
MediaPlay = 179,
LaunchMail = 180,
LaunchMediaSelect = 181,
LaunchApp1 = 182,
LaunchApp2 = 183,
Oem1 = 186,
OemPlus = 187,
OemComma = 188,
OemMinus = 189,
OemPeriod = 190,
Oem2 = 191,
Oem3 = 192,
Oem4 = 219,
Oem5 = 220,
Oem6 = 221,
Oem7 = 222,
Oem8 = 223,
Oem102 = 226,
Process = 229,
Packet = 231,
Attention = 246,
CrSel = 247,
ExSel = 248,
EraseEndOfFile = 249,
Play = 250,
Zoom = 251,
NoName = 252,
Pa1 = 253,
OemClear = 254,
}
public enum ConsoleModifiers
{
Alt = 1,
Shift = 2,
Control = 4,
}
public enum ConsoleSpecialKey
{
ControlC = 0,
ControlBreak = 1,
}
public delegate void CrossAppDomainDelegate ();
public enum EnvironmentVariableTarget
{
Process = 0,
User = 1,
Machine = 2,
}
#endif
#if NETFRAMEWORK_4_0
public delegate TResult Func<T1, T2, T3, T4, T5, TResult> (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
public delegate TResult Func<T1, T2, T3, TResult> (T1 arg1, T2 arg2, T3 arg3);
public delegate TResult Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult> (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
public delegate TResult Func<T1, T2, T3, T4, TResult> (T1 arg1, T2 arg2, T3 arg3, T4 arg4);
public delegate TResult Func<T1, T2, T3, T4, T5, T6, TResult> (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
public delegate TResult Func<T1, T2, T3, T4, T5, T6, T7, TResult> (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
public delegate TResult Func<TResult> ();
public delegate TResult Func<T1, T2, TResult> (T1 arg1, T2 arg2);
public delegate TResult Func<T, TResult> (T arg);
#endif
#if !SILVERLIGHT_4_0_WP
public enum GCCollectionMode
{
Default = 0,
Forced = 1,
Optimized = 2,
}
#endif
#if !SILVERLIGHT
public enum GCNotificationStatus
{
Succeeded = 0,
Failed = 1,
Canceled = 2,
Timeout = 3,
NotApplicable = 4,
}
#endif
public enum LoaderOptimization
{
NotSpecified = 0,
SingleDomain = 1,
MultiDomain = 2,
MultiDomainHost = 3,
#if !SILVERLIGHT
DomainMask = 3,
DisallowBindings = 4,
#endif
}
#if !SILVERLIGHT_4_0_WP
public enum MidpointRounding
{
ToEven = 0,
AwayFromZero = 1,
}
#endif
public enum PlatformID
{
Win32S = 0,
Win32Windows = 1,
Win32NT = 2,
WinCE = 3,
Unix = 4,
Xbox = 5,
#if !SILVERLIGHT_4_0_WP
MacOSX = 6,
#endif
}
public enum StringSplitOptions
{
None = 0,
RemoveEmptyEntries = 1,
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
namespace VNEngine
{
public class AudioManager : MonoBehaviour
{
public static AudioManager audio_manager;
public AudioSource background_music_audio_source; // Music that plays in background. Only one track of music will ever be playing at once
public AudioSource voice_audio_source; // Audio source playing the talking of the voice actors
public AudioSource ambience_audio_source; // Rain falling, city streets, vague murmuring. Allows an extra layer of sounds to be used in addition to background_music
bool muted = false; // If muted, NO audio will play
public GameObject sound_effect_prefab; // Must be an object with an audiosource, and necessary for PlaySoundEffect nodes
// Volume controls
[HideInInspector]
public float master_volume = 1;
[HideInInspector]
public float music_volume = 1;
[HideInInspector]
public float voice_volume = 1;
[HideInInspector]
public float effects_volume = 1;
public Slider Master_Volume_Slider;
public Slider Music_Volume_Slider;
public Slider Voice_Volume_Slider;
public Slider Effects_Volume_Slider;
public List<AudioSource> talking_beeps_list;
void Awake()
{
audio_manager = this;
}
void Start()
{
// Load player preferences
Master_Volume_Changed(PlayerPrefs.GetFloat("MasterVolume", 1));
Voice_Volume_Changed(PlayerPrefs.GetFloat("VoiceVolume", 1));
Music_Volume_Changed(PlayerPrefs.GetFloat("MusicVolume", 1));
Effects_Volume_Changed(PlayerPrefs.GetFloat("EffectsVolume", 1));
// Set sliders
if (Master_Volume_Slider)
Master_Volume_Slider.value = master_volume;
if (Music_Volume_Slider)
Music_Volume_Slider.value = music_volume;
if (Voice_Volume_Slider)
Voice_Volume_Slider.value = voice_volume;
if (Effects_Volume_Slider)
Effects_Volume_Slider.value = effects_volume;
}
// Fades out the current background music over seconds_it_takes_to_fade_out
public IEnumerator Fade_Out_Music(float seconds_it_takes_to_fade_out)
{
if (background_music_audio_source != null)
{
while (background_music_audio_source.volume > 0)
{
background_music_audio_source.volume -= (1 / seconds_it_takes_to_fade_out) * Time.deltaTime;
yield return null;
}
}
}
// Fades out the current background music over seconds_it_takes_to_fade_out
public IEnumerator Fade_Out_Ambience(float seconds_it_takes_to_fade_out)
{
if (ambience_audio_source != null)
{
while (ambience_audio_source.volume > 0)
{
ambience_audio_source.volume -= (1 / seconds_it_takes_to_fade_out) * Time.deltaTime;
yield return null;
}
}
}
// Starts the new background music and starts it playing
public void Set_Music(AudioClip new_music)
{
background_music_audio_source.clip = new_music;
background_music_audio_source.loop = true;
background_music_audio_source.volume = music_volume;
background_music_audio_source.Play();
}
// Starts the new ambience music and starts it playing
public void Set_Ambience(AudioClip new_music)
{
ambience_audio_source.clip = new_music;
ambience_audio_source.loop = true;
ambience_audio_source.volume = music_volume;
ambience_audio_source.Play();
}
// Toggles the muting of ALL audio in the scene
public void Toggle_Audio_Muting()
{
Debug.Log("Toggling audio muting");
if (!muted)
AudioListener.volume = 0;
else
AudioListener.volume = master_volume;
muted = !muted;
}
public void Play_Voice_Clip(AudioClip voice_clip)
{
voice_audio_source.Stop();
voice_audio_source.clip = voice_clip;
voice_audio_source.Play();
}
// Creates a new gameobject with its own AudioSource that destroys itself after the sound is done playing
public void Play_Sound_Effect(AudioClip voice_clip)
{
GameObject sound_obj = Instantiate(sound_effect_prefab) as GameObject;
AudioSource audio = sound_obj.GetComponent<AudioSource>();
audio.clip = voice_clip;
audio.playOnAwake = true;
audio.volume = effects_volume;
}
// Called every time a character is printed to the screen, plays 1 instance of the given sound
public void Play_Talking_Beep(AudioClip beep)
{
bool found_free_audiosource = false;
foreach (AudioSource aud in talking_beeps_list)
{
// Check if the audiosource is playing
if (!aud.isPlaying)
{
// AudioSource is not playing, make it play the beep
aud.clip = beep;
aud.Play();
found_free_audiosource = true;
break;
}
}
if (!found_free_audiosource)
Debug.Log("Could not find silent AudioSource for Play_Talking_Beep to use. Please add more AudioSources to the talking_beeps_list in AudioManager", this.gameObject);
}
// Volume options managed by the sliders in the pause menu
public void Master_Volume_Changed(float new_volume)
{
master_volume = new_volume;
// Change the audio listener's volume
AudioListener.volume = master_volume;
SavePlayerPreference("MasterVolume", new_volume);
}
public void Voice_Volume_Changed(float new_volume)
{
voice_volume = new_volume;
voice_audio_source.volume = new_volume;
// Change the talking beeps volume, as they count as voice volume
foreach (AudioSource aud in talking_beeps_list)
{
aud.volume = voice_volume;
}
SavePlayerPreference("VoiceVolume", new_volume);
}
public void Music_Volume_Changed(float new_volume)
{
music_volume = new_volume;
background_music_audio_source.volume = new_volume;
ambience_audio_source.volume = new_volume;
SavePlayerPreference("MusicVolume", new_volume);
}
public void Effects_Volume_Changed(float new_volume)
{
effects_volume = new_volume;
SavePlayerPreference("EffectsVolume", new_volume);
}
// Player preferences live in Windows registries and persist between plays
public void SavePlayerPreference(string key, bool value)
{
PlayerPrefs.SetInt(key, System.Convert.ToInt32(value));
PlayerPrefs.Save();
}
public void SavePlayerPreference(string key, float value)
{
PlayerPrefs.SetFloat(key, value);
PlayerPrefs.Save();
}
}
}
| |
/* ====================================================================
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 TestCases.SS.UserModel
{
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS;
using NPOI.SS.UserModel;
using NUnit.Framework;
using System;
using System.Text;
using TestCases.SS;
/**
* Common superclass for testing implementatiosn of
* {@link NPOI.SS.usermodel.Cell}
*/
public abstract class BaseTestCell
{
protected ITestDataProvider _testDataProvider;
/**
* @param testDataProvider an object that provides test data in HSSF / XSSF specific way
*/
protected BaseTestCell(ITestDataProvider testDataProvider)
{
// One or more test methods depends on the american culture.
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
_testDataProvider = testDataProvider;
}
[Test]
public void TestSetValues()
{
IWorkbook book = _testDataProvider.CreateWorkbook();
ISheet sheet = book.CreateSheet("test");
IRow row = sheet.CreateRow(0);
ICreationHelper factory = book.GetCreationHelper();
ICell cell = row.CreateCell(0);
cell.SetCellValue(1.2);
Assert.AreEqual(1.2, cell.NumericCellValue, 0.0001);
Assert.AreEqual(CellType.Numeric, cell.CellType);
AssertProhibitedValueAccess(cell, CellType.Boolean, CellType.String,
CellType.Formula, CellType.Error);
cell.SetCellValue(false);
Assert.AreEqual(false, cell.BooleanCellValue);
Assert.AreEqual(CellType.Boolean, cell.CellType);
cell.SetCellValue(true);
Assert.AreEqual(true, cell.BooleanCellValue);
AssertProhibitedValueAccess(cell, CellType.Numeric, CellType.String,
CellType.Formula, CellType.Error);
cell.SetCellValue(factory.CreateRichTextString("Foo"));
Assert.AreEqual("Foo", cell.RichStringCellValue.String);
Assert.AreEqual("Foo", cell.StringCellValue);
Assert.AreEqual(CellType.String, cell.CellType);
AssertProhibitedValueAccess(cell, CellType.Numeric, CellType.Boolean,
CellType.Formula, CellType.Error);
cell.SetCellValue("345");
Assert.AreEqual("345", cell.RichStringCellValue.String);
Assert.AreEqual("345", cell.StringCellValue);
Assert.AreEqual(CellType.String, cell.CellType);
AssertProhibitedValueAccess(cell, CellType.Numeric, CellType.Boolean,
CellType.Formula, CellType.Error);
DateTime dt = DateTime.Now.AddMilliseconds(123456789);
cell.SetCellValue(dt);
Assert.IsTrue((dt.Ticks - cell.DateCellValue.Ticks) >= -20000);
Assert.AreEqual(CellType.Numeric, cell.CellType);
AssertProhibitedValueAccess(cell, CellType.Boolean, CellType.String,
CellType.Formula, CellType.Error);
cell.SetCellValue(dt);
Assert.IsTrue((dt.Ticks - cell.DateCellValue.Ticks) >= -20000);
Assert.AreEqual(CellType.Numeric, cell.CellType);
AssertProhibitedValueAccess(cell, CellType.Boolean, CellType.String,
CellType.Formula, CellType.Error);
cell.SetCellErrorValue(FormulaError.NA.Code);
Assert.AreEqual(FormulaError.NA.Code, cell.ErrorCellValue);
Assert.AreEqual(CellType.Error, cell.CellType);
AssertProhibitedValueAccess(cell, CellType.Numeric, CellType.Boolean,
CellType.Formula, CellType.String);
}
private static void AssertProhibitedValueAccess(ICell cell, params CellType[] types)
{
object a;
foreach (CellType type in types)
{
try
{
switch (type)
{
case CellType.Numeric:
a = cell.NumericCellValue;
break;
case CellType.String:
a = cell.StringCellValue;
break;
case CellType.Boolean:
a = cell.BooleanCellValue;
break;
case CellType.Formula:
a = cell.CellFormula;
break;
case CellType.Error:
a = cell.ErrorCellValue;
break;
}
Assert.Fail("Should get exception when Reading cell type (" + type + ").");
}
catch (InvalidOperationException e)
{
// expected during successful test
Assert.IsTrue(e.Message.StartsWith("Cannot get a"));
}
}
}
/**
* test that Boolean (BoolErrRecord) are supported properly.
* @see testErr
*/
[Test]
public void TestBool()
{
IWorkbook wb1 = _testDataProvider.CreateWorkbook();
ISheet s = wb1.CreateSheet("testSheet1");
IRow r;
ICell c;
// B1
r = s.CreateRow(0);
c = r.CreateCell(1);
Assert.AreEqual(0, c.RowIndex);
Assert.AreEqual(1, c.ColumnIndex);
c.SetCellValue(true);
Assert.AreEqual(true, c.BooleanCellValue, "B1 value");
// C1
c = r.CreateCell(2);
Assert.AreEqual(0, c.RowIndex);
Assert.AreEqual(2, c.ColumnIndex);
c.SetCellValue(false);
Assert.AreEqual(false, c.BooleanCellValue, "C1 value");
// Make sure values are saved and re-read correctly.
IWorkbook wb2 = _testDataProvider.WriteOutAndReadBack(wb1);
wb1.Close();
s = wb2.GetSheet("testSheet1");
r = s.GetRow(0);
Assert.AreEqual(2, r.PhysicalNumberOfCells, "Row 1 should have 2 cells");
c = r.GetCell(1);
Assert.AreEqual(0, c.RowIndex);
Assert.AreEqual(1, c.ColumnIndex);
Assert.AreEqual(CellType.Boolean, c.CellType);
Assert.AreEqual(true, c.BooleanCellValue, "B1 value");
c = r.GetCell(2);
Assert.AreEqual(0, c.RowIndex);
Assert.AreEqual(2, c.ColumnIndex);
Assert.AreEqual(CellType.Boolean, c.CellType);
Assert.AreEqual(false, c.BooleanCellValue, "C1 value");
wb2.Close();
}
/**
* test that Error types (BoolErrRecord) are supported properly.
* @see testBool
*/
[Test]
public void TestErr()
{
IWorkbook wb1 = _testDataProvider.CreateWorkbook();
ISheet s = wb1.CreateSheet("testSheet1");
IRow r;
ICell c;
// B1
r = s.CreateRow(0);
c = r.CreateCell(1);
Assert.AreEqual(0, c.RowIndex);
Assert.AreEqual(1, c.ColumnIndex);
c.SetCellErrorValue(FormulaError.NULL.Code);
Assert.AreEqual(FormulaError.NULL.Code, c.ErrorCellValue, "B1 value == #NULL!");
// C1
c = r.CreateCell(2);
Assert.AreEqual(0, c.RowIndex);
Assert.AreEqual(2, c.ColumnIndex);
c.SetCellErrorValue(FormulaError.DIV0.Code);
Assert.AreEqual(FormulaError.DIV0.Code, c.ErrorCellValue, "C1 value == #DIV/0!");
IWorkbook wb2 = _testDataProvider.WriteOutAndReadBack(wb1);
wb1.Close();
s = wb2.GetSheet("testSheet1");
r = s.GetRow(0);
Assert.AreEqual(2, r.PhysicalNumberOfCells, "Row 1 should have 2 cells");
c = r.GetCell(1);
Assert.AreEqual(0, c.RowIndex);
Assert.AreEqual(1, c.ColumnIndex);
Assert.AreEqual(CellType.Error, c.CellType);
Assert.AreEqual(FormulaError.NULL.Code, c.ErrorCellValue, "B1 value == #NULL!");
c = r.GetCell(2);
Assert.AreEqual(0, c.RowIndex);
Assert.AreEqual(2, c.ColumnIndex);
Assert.AreEqual(CellType.Error, c.CellType);
Assert.AreEqual(FormulaError.DIV0.Code, c.ErrorCellValue, "C1 value == #DIV/0!");
wb2.Close();
}
/**
* test that Cell Styles being applied to formulas remain intact
*/
[Test]
public void TestFormulaStyle()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet s = wb.CreateSheet("testSheet1");
IRow r = null;
ICell c = null;
ICellStyle cs = wb.CreateCellStyle();
IFont f = wb.CreateFont();
f.FontHeightInPoints = 20;
f.Color = (HSSFColor.Red.Index);
f.Boldweight = (int)FontBoldWeight.Bold;
f.FontName = "Arial Unicode MS";
cs.FillBackgroundColor = 3;
cs.SetFont(f);
cs.BorderTop = BorderStyle.Thin;
cs.BorderRight = BorderStyle.Thin;
cs.BorderLeft = BorderStyle.Thin;
cs.BorderBottom = BorderStyle.Thin;
r = s.CreateRow(0);
c = r.CreateCell(0);
c.CellStyle = cs;
c.CellFormula = ("2*3");
wb = _testDataProvider.WriteOutAndReadBack(wb);
s = wb.GetSheetAt(0);
r = s.GetRow(0);
c = r.GetCell(0);
Assert.AreEqual(c.CellType, CellType.Formula, "Formula Cell at 0,0");
cs = c.CellStyle;
Assert.IsNotNull(cs, "Formula Cell Style");
Assert.AreEqual(f.Index, cs.FontIndex, "Font Index Matches");
Assert.AreEqual(BorderStyle.Thin, cs.BorderTop , "Top Border");
Assert.AreEqual(BorderStyle.Thin, cs.BorderLeft, "Left Border");
Assert.AreEqual(BorderStyle.Thin, cs.BorderRight, "Right Border");
Assert.AreEqual(BorderStyle.Thin, cs.BorderBottom, "Bottom Border");
}
/**tests the ToString() method of HSSFCell*/
[Test]
public void TestToString()
{
IWorkbook wb1 = _testDataProvider.CreateWorkbook();
IRow r = wb1.CreateSheet("Sheet1").CreateRow(0);
ICreationHelper factory = wb1.GetCreationHelper();
r.CreateCell(0).SetCellValue(false);
r.CreateCell(1).SetCellValue(true);
r.CreateCell(2).SetCellValue(1.5);
r.CreateCell(3).SetCellValue(factory.CreateRichTextString("Astring"));
r.CreateCell(4).SetCellErrorValue(FormulaError.DIV0.Code);
r.CreateCell(5).SetCellFormula("A1+B1");
r.CreateCell(6); // blank
// create date-formatted cell
DateTime c = new DateTime(2010, 01, 02, 00, 00, 00);
r.CreateCell(7).SetCellValue(c);
ICellStyle dateStyle = wb1.CreateCellStyle();
short formatId = wb1.GetCreationHelper().CreateDataFormat().GetFormat("dd-MMM-yyyy"); // m/d/yy h:mm any date format will do
dateStyle.DataFormat = formatId;
r.GetCell(7).CellStyle = dateStyle;
Assert.AreEqual("FALSE", r.GetCell(0).ToString(), "Boolean");
Assert.AreEqual("TRUE", r.GetCell(1).ToString(), "Boolean");
Assert.AreEqual("1.5", r.GetCell(2).ToString(), "Numeric");
Assert.AreEqual("Astring", r.GetCell(3).ToString(), "String");
Assert.AreEqual("#DIV/0!", r.GetCell(4).ToString(), "Error");
Assert.AreEqual("A1+B1", r.GetCell(5).ToString(), "Formula");
Assert.AreEqual("", r.GetCell(6).ToString(), "Blank");
// toString on a date-formatted cell displays dates as dd-MMM-yyyy, which has locale problems with the month
String dateCell1 = r.GetCell(7).ToString();
Assert.IsTrue(dateCell1.StartsWith("02-"), "Date (Day)");
Assert.IsTrue(dateCell1.EndsWith("-2010"), "Date (Year)");
//Write out the file, read it in, and then check cell values
IWorkbook wb2 = _testDataProvider.WriteOutAndReadBack(wb1);
wb1.Close();
r = wb2.GetSheetAt(0).GetRow(0);
Assert.AreEqual("FALSE", r.GetCell(0).ToString(), "Boolean");
Assert.AreEqual("TRUE", r.GetCell(1).ToString(), "Boolean");
Assert.AreEqual("1.5", r.GetCell(2).ToString(), "Numeric");
Assert.AreEqual("Astring", r.GetCell(3).ToString(), "String");
Assert.AreEqual("#DIV/0!", r.GetCell(4).ToString(), "Error");
Assert.AreEqual("A1+B1", r.GetCell(5).ToString(), "Formula");
Assert.AreEqual("", r.GetCell(6).ToString(), "Blank");
String dateCell2 = r.GetCell(7).ToString();
Assert.AreEqual(dateCell1, dateCell2, "Date");
wb2.Close();
}
/**
* Test that Setting cached formula result keeps the cell type
*/
[Test]
public void TestSetFormulaValue()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet s = wb.CreateSheet();
IRow r = s.CreateRow(0);
ICell c1 = r.CreateCell(0);
c1.CellFormula = ("NA()");
Assert.AreEqual(0.0, c1.NumericCellValue, 0.0);
Assert.AreEqual(CellType.Numeric, c1.CachedFormulaResultType);
c1.SetCellValue(10);
Assert.AreEqual(10.0, c1.NumericCellValue, 0.0);
Assert.AreEqual(CellType.Formula, c1.CellType);
Assert.AreEqual(CellType.Numeric, c1.CachedFormulaResultType);
ICell c2 = r.CreateCell(1);
c2.CellFormula = ("NA()");
Assert.AreEqual(0.0, c2.NumericCellValue, 0.0);
Assert.AreEqual(CellType.Numeric, c2.CachedFormulaResultType);
c2.SetCellValue("I Changed!");
Assert.AreEqual("I Changed!", c2.StringCellValue);
Assert.AreEqual(CellType.Formula, c2.CellType);
Assert.AreEqual(CellType.String, c2.CachedFormulaResultType);
//calglin Cell.CellFormula = (null) for a non-formula cell
ICell c3 = r.CreateCell(2);
c3.CellFormula = (null);
Assert.AreEqual(CellType.Blank, c3.CellType);
}
private ICell CreateACell(IWorkbook wb)
{
return wb.CreateSheet("Sheet1").CreateRow(0).CreateCell(0);
}
/**
* bug 58452: Copy cell formulas containing unregistered function names
* Make sure that formulas with unknown/unregistered UDFs can be written to and read back from a file.
*
* @throws IOException
*/
[Test]
public void TestFormulaWithUnknownUDF()
{
IWorkbook wb1 = _testDataProvider.CreateWorkbook();
IFormulaEvaluator evaluator1 = wb1.GetCreationHelper().CreateFormulaEvaluator();
try
{
ICell cell1 = wb1.CreateSheet().CreateRow(0).CreateCell(0);
String formula = "myFunc(\"arg\")";
cell1.SetCellFormula(formula);
ConfirmFormulaWithUnknownUDF(formula, cell1, evaluator1);
IWorkbook wb2 = _testDataProvider.WriteOutAndReadBack(wb1);
IFormulaEvaluator evaluator2 = wb2.GetCreationHelper().CreateFormulaEvaluator();
try
{
ICell cell2 = wb2.GetSheetAt(0).GetRow(0).GetCell(0);
ConfirmFormulaWithUnknownUDF(formula, cell2, evaluator2);
}
finally
{
wb2.Close();
}
}
finally
{
wb1.Close();
}
}
private static void ConfirmFormulaWithUnknownUDF(String expectedFormula, ICell cell, IFormulaEvaluator evaluator)
{
Assert.AreEqual(expectedFormula, cell.CellFormula);
try
{
evaluator.Evaluate(cell);
Assert.Fail("Expected NotImplementedFunctionException/NotImplementedException");
}
catch (NotImplementedException)
{
// expected
}
}
[Test]
public void TestChangeTypeStringToBool()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ICell cell = CreateACell(wb);
cell.SetCellValue("TRUE");
Assert.AreEqual(CellType.String, cell.CellType);
// test conversion of cell from text to boolean
cell.SetCellType(CellType.Boolean);
Assert.AreEqual(CellType.Boolean, cell.CellType);
Assert.AreEqual(true, cell.BooleanCellValue);
cell.SetCellType(CellType.String);
Assert.AreEqual("TRUE", cell.RichStringCellValue.String);
// 'false' text to bool and back
cell.SetCellValue("FALSE");
cell.SetCellType(CellType.Boolean);
Assert.AreEqual(CellType.Boolean, cell.CellType);
Assert.AreEqual(false, cell.BooleanCellValue);
cell.SetCellType(CellType.String);
Assert.AreEqual("FALSE", cell.RichStringCellValue.String);
wb.Close();
}
[Test]
public void TestChangeTypeBoolToString()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ICell cell = CreateACell(wb);
cell.SetCellValue(true);
// test conversion of cell from boolean to text
cell.SetCellType(CellType.String);
Assert.AreEqual("TRUE", cell.RichStringCellValue.String);
wb.Close();
}
[Test]
public void TestChangeTypeErrorToNumber()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ICell cell = CreateACell(wb);
cell.SetCellErrorValue(FormulaError.NAME.Code);
try
{
cell.SetCellValue(2.5);
}
catch (InvalidCastException)
{
Assert.Fail("Identified bug 46479b");
}
Assert.AreEqual(2.5, cell.NumericCellValue, 0.0);
wb.Close();
}
[Test]
public void TestChangeTypeErrorToBoolean()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ICell cell = CreateACell(wb);
cell.SetCellErrorValue(FormulaError.NAME.Code);
cell.SetCellValue(true);
// Identify bug 46479c
Assert.AreEqual(true, cell.BooleanCellValue);
wb.Close();
}
/**
* Test for a bug observed around svn r886733 when using
* {@link FormulaEvaluator#EvaluateInCell(Cell)} with a
* string result type.
*/
[Test]
public void TestConvertStringFormulaCell()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ICell cellA1 = CreateACell(wb);
cellA1.CellFormula = ("\"abc\"");
// default cached formula result is numeric zero
Assert.AreEqual(0.0, cellA1.NumericCellValue, 0.0);
IFormulaEvaluator fe = cellA1.Sheet.Workbook.GetCreationHelper().CreateFormulaEvaluator();
fe.EvaluateFormulaCell(cellA1);
Assert.AreEqual("abc", cellA1.StringCellValue);
fe.EvaluateInCell(cellA1);
Assert.IsFalse(cellA1.StringCellValue.Equals(""), "Identified bug with writing back formula result of type string");
Assert.AreEqual("abc", cellA1.StringCellValue);
wb.Close();
}
/**
* similar to {@link #testConvertStringFormulaCell()} but Checks at a
* lower level that {#link {@link Cell#SetCellType(int)} works properly
*/
[Test]
public void TestSetTypeStringOnFormulaCell()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ICell cellA1 = CreateACell(wb);
IFormulaEvaluator fe = cellA1.Sheet.Workbook.GetCreationHelper().CreateFormulaEvaluator();
cellA1.CellFormula = ("\"DEF\"");
fe.ClearAllCachedResultValues();
fe.EvaluateFormulaCell(cellA1);
Assert.AreEqual("DEF", cellA1.StringCellValue);
cellA1.SetCellType(CellType.String);
Assert.AreEqual("DEF", cellA1.StringCellValue);
cellA1.CellFormula = ("25.061");
fe.ClearAllCachedResultValues();
fe.EvaluateFormulaCell(cellA1);
ConfirmCannotReadString(cellA1);
Assert.AreEqual(25.061, cellA1.NumericCellValue, 0.0);
cellA1.SetCellType(CellType.String);
Assert.AreEqual("25.061", cellA1.StringCellValue);
cellA1.CellFormula = ("TRUE");
fe.ClearAllCachedResultValues();
fe.EvaluateFormulaCell(cellA1);
ConfirmCannotReadString(cellA1);
Assert.AreEqual(true, cellA1.BooleanCellValue);
cellA1.SetCellType(CellType.String);
Assert.AreEqual("TRUE", cellA1.StringCellValue);
cellA1.CellFormula = ("#NAME?");
fe.ClearAllCachedResultValues();
fe.EvaluateFormulaCell(cellA1);
ConfirmCannotReadString(cellA1);
Assert.AreEqual(FormulaError.NAME, FormulaError.ForInt(cellA1.ErrorCellValue));
cellA1.SetCellType(CellType.String);
Assert.AreEqual("#NAME?", cellA1.StringCellValue);
wb.Close();
}
private static void ConfirmCannotReadString(ICell cell)
{
AssertProhibitedValueAccess(cell, CellType.String);
}
/**
* Test for bug in ConvertCellValueToBoolean to make sure that formula results get Converted
*/
[Test]
public void TestChangeTypeFormulaToBoolean()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ICell cell = CreateACell(wb);
cell.CellFormula = ("1=1");
cell.SetCellValue(true);
cell.SetCellType(CellType.Boolean);
Assert.IsTrue(cell.BooleanCellValue, "Identified bug 46479d");
Assert.AreEqual(true, cell.BooleanCellValue);
wb.Close();
}
/**
* Bug 40296: HSSFCell.CellFormula = throws
* InvalidCastException if cell is Created using HSSFRow.CreateCell(short column, int type)
*/
[Test]
public void Test40296()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet workSheet = wb.CreateSheet("Sheet1");
ICell cell;
IRow row = workSheet.CreateRow(0);
cell = row.CreateCell(0, CellType.Numeric);
cell.SetCellValue(1.0);
Assert.AreEqual(CellType.Numeric, cell.CellType);
Assert.AreEqual(1.0, cell.NumericCellValue, 0.0);
cell = row.CreateCell(1, CellType.Numeric);
cell.SetCellValue(2.0);
Assert.AreEqual(CellType.Numeric, cell.CellType);
Assert.AreEqual(2.0, cell.NumericCellValue, 0.0);
cell = row.CreateCell(2, CellType.Formula);
cell.CellFormula = ("SUM(A1:B1)");
Assert.AreEqual(CellType.Formula, cell.CellType);
Assert.AreEqual("SUM(A1:B1)", cell.CellFormula);
//serialize and check again
wb = _testDataProvider.WriteOutAndReadBack(wb);
row = wb.GetSheetAt(0).GetRow(0);
cell = row.GetCell(0);
Assert.AreEqual(CellType.Numeric, cell.CellType);
Assert.AreEqual(1.0, cell.NumericCellValue, 0.0);
cell = row.GetCell(1);
Assert.AreEqual(CellType.Numeric, cell.CellType);
Assert.AreEqual(2.0, cell.NumericCellValue, 0.0);
cell = row.GetCell(2);
Assert.AreEqual(CellType.Formula, cell.CellType);
Assert.AreEqual("SUM(A1:B1)", cell.CellFormula);
}
[Test]
public void TestSetStringInFormulaCell_bug44606()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ICell cell = wb.CreateSheet("Sheet1").CreateRow(0).CreateCell(0);
cell.CellFormula = ("B1&C1");
try
{
cell.SetCellValue(wb.GetCreationHelper().CreateRichTextString("hello"));
}
catch (InvalidCastException)
{
throw new AssertionException("Identified bug 44606");
}
}
/**
* Make sure that cell.SetCellType(Cell.CELL_TYPE_BLANK) preserves the cell style
*/
[Test]
public void TestSetBlank_bug47028()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ICellStyle style = wb.CreateCellStyle();
ICell cell = wb.CreateSheet("Sheet1").CreateRow(0).CreateCell(0);
cell.CellStyle = (style);
int i1 = cell.CellStyle.Index;
cell.SetCellType(CellType.Blank);
int i2 = cell.CellStyle.Index;
Assert.AreEqual(i1, i2);
}
/**
* Excel's implementation of floating number arithmetic does not fully adhere to IEEE 754:
*
* From http://support.microsoft.com/kb/78113:
*
* <ul>
* <li> Positive/Negative InfInities:
* InfInities occur when you divide by 0. Excel does not support infInities, rather,
* it gives a #DIV/0! error in these cases.
* </li>
* <li>
* Not-a-Number (NaN):
* NaN is used to represent invalid operations (such as infInity/infinity,
* infInity-infinity, or the square root of -1). NaNs allow a program to
* continue past an invalid operation. Excel instead immediately generates
* an error such as #NUM! or #DIV/0!.
* </li>
* </ul>
*/
[Test]
public void TestNanAndInfInity()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet workSheet = wb.CreateSheet("Sheet1");
IRow row = workSheet.CreateRow(0);
ICell cell0 = row.CreateCell(0);
cell0.SetCellValue(Double.NaN);
Assert.AreEqual(CellType.Error, cell0.CellType, "Double.NaN should change cell type to CELL_TYPE_ERROR");
Assert.AreEqual(FormulaError.NUM, FormulaError.ForInt(cell0.ErrorCellValue), "Double.NaN should change cell value to #NUM!");
ICell cell1 = row.CreateCell(1);
cell1.SetCellValue(Double.PositiveInfinity);
Assert.AreEqual(CellType.Error, cell1.CellType, "Double.PositiveInfinity should change cell type to CELL_TYPE_ERROR");
Assert.AreEqual(FormulaError.DIV0, FormulaError.ForInt(cell1.ErrorCellValue), "Double.POSITIVE_INFINITY should change cell value to #DIV/0!");
ICell cell2 = row.CreateCell(2);
cell2.SetCellValue(Double.NegativeInfinity);
Assert.AreEqual(CellType.Error, cell2.CellType, "Double.NegativeInfinity should change cell type to CELL_TYPE_ERROR");
Assert.AreEqual(FormulaError.DIV0, FormulaError.ForInt(cell2.ErrorCellValue), "Double.NEGATIVE_INFINITY should change cell value to #DIV/0!");
wb = _testDataProvider.WriteOutAndReadBack(wb);
row = wb.GetSheetAt(0).GetRow(0);
cell0 = row.GetCell(0);
Assert.AreEqual(CellType.Error, cell0.CellType);
Assert.AreEqual(FormulaError.NUM, FormulaError.ForInt(cell0.ErrorCellValue));
cell1 = row.GetCell(1);
Assert.AreEqual(CellType.Error, cell1.CellType);
Assert.AreEqual(FormulaError.DIV0, FormulaError.ForInt(cell1.ErrorCellValue));
cell2 = row.GetCell(2);
Assert.AreEqual(CellType.Error, cell2.CellType);
Assert.AreEqual(FormulaError.DIV0, FormulaError.ForInt(cell2.ErrorCellValue));
}
[Test]
public void TestDefaultStyleProperties()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ICell cell = wb.CreateSheet("Sheet1").CreateRow(0).CreateCell(0);
ICellStyle style = cell.CellStyle;
Assert.IsTrue(style.IsLocked);
Assert.IsFalse(style.IsHidden);
Assert.AreEqual(0, style.Indention);
Assert.AreEqual(0, style.FontIndex);
Assert.AreEqual(0, (int)style.Alignment);
Assert.AreEqual(0, style.DataFormat);
Assert.AreEqual(false, style.WrapText);
ICellStyle style2 = wb.CreateCellStyle();
Assert.IsTrue(style2.IsLocked);
Assert.IsFalse(style2.IsHidden);
style2.IsLocked = (/*setter*/false);
style2.IsHidden = (/*setter*/true);
Assert.IsFalse(style2.IsLocked);
Assert.IsTrue(style2.IsHidden);
wb = _testDataProvider.WriteOutAndReadBack(wb);
cell = wb.GetSheetAt(0).GetRow(0).GetCell(0);
style = cell.CellStyle;
Assert.IsFalse(style2.IsLocked);
Assert.IsTrue(style2.IsHidden);
style2.IsLocked = (/*setter*/true);
style2.IsHidden = (/*setter*/false);
Assert.IsTrue(style2.IsLocked);
Assert.IsFalse(style2.IsHidden);
}
[Test]
public void TestBug55658SetNumericValue()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet sh = wb.CreateSheet();
IRow row = sh.CreateRow(0);
ICell cell = row.CreateCell(0);
cell.SetCellValue(23);
cell.SetCellValue("some");
cell = row.CreateCell(1);
cell.SetCellValue(23);
cell.SetCellValue("24");
wb = _testDataProvider.WriteOutAndReadBack(wb);
Assert.AreEqual("some", wb.GetSheetAt(0).GetRow(0).GetCell(0).StringCellValue);
Assert.AreEqual("24", wb.GetSheetAt(0).GetRow(0).GetCell(1).StringCellValue);
}
[Test]
public void TestRemoveHyperlink()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet sh = wb.CreateSheet("test");
IRow row = sh.CreateRow(0);
ICreationHelper helper = wb.GetCreationHelper();
ICell cell1 = row.CreateCell(1);
IHyperlink link1 = helper.CreateHyperlink(HyperlinkType.Url);
cell1.Hyperlink = (/*setter*/link1);
Assert.IsNotNull(cell1.Hyperlink);
cell1.RemoveHyperlink();
Assert.IsNull(cell1.Hyperlink);
ICell cell2 = row.CreateCell(0);
IHyperlink link2 = helper.CreateHyperlink(HyperlinkType.Url);
cell2.Hyperlink = (/*setter*/link2);
Assert.IsNotNull(cell2.Hyperlink);
cell2.Hyperlink = (/*setter*/null);
Assert.IsNull(cell2.Hyperlink);
ICell cell3 = row.CreateCell(2);
IHyperlink link3 = helper.CreateHyperlink(HyperlinkType.Url);
link3.Address = (/*setter*/"http://poi.apache.org/");
cell3.Hyperlink = (/*setter*/link3);
Assert.IsNotNull(cell3.Hyperlink);
IWorkbook wbBack = _testDataProvider.WriteOutAndReadBack(wb);
Assert.IsNotNull(wbBack);
cell1 = wbBack.GetSheet("test").GetRow(0).GetCell(1);
Assert.IsNull(cell1.Hyperlink);
cell2 = wbBack.GetSheet("test").GetRow(0).GetCell(0);
Assert.IsNull(cell2.Hyperlink);
cell3 = wbBack.GetSheet("test").GetRow(0).GetCell(2);
Assert.IsNotNull(cell3.Hyperlink);
}
/**
* Cell with the formula that returns error must return error code(There was
* an problem that cell could not return error value form formula cell).
* @
*/
[Test]
public void TestGetErrorCellValueFromFormulaCell()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
try
{
ISheet sheet = wb.CreateSheet();
IRow row = sheet.CreateRow(0);
ICell cell = row.CreateCell(0);
cell.CellFormula = (/*setter*/"SQRT(-1)");
wb.GetCreationHelper().CreateFormulaEvaluator().EvaluateFormulaCell(cell);
Assert.AreEqual(36, cell.ErrorCellValue);
}
finally
{
wb.Close();
}
}
[Test]
public void TestSetRemoveStyle()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet sheet = wb.CreateSheet();
IRow row = sheet.CreateRow(0);
ICell cell = row.CreateCell(0);
// different default style indexes for HSSF and XSSF/SXSSF
ICellStyle defaultStyle = wb.GetCellStyleAt(wb is HSSFWorkbook ? (short)15 : (short)0);
// Starts out with the default style
Assert.AreEqual(defaultStyle, cell.CellStyle);
// Create some styles, no change
ICellStyle style1 = wb.CreateCellStyle();
ICellStyle style2 = wb.CreateCellStyle();
style1.DataFormat = (/*setter*/(short)2);
style2.DataFormat = (/*setter*/(short)3);
Assert.AreEqual(defaultStyle, cell.CellStyle);
// Apply one, Changes
cell.CellStyle = (/*setter*/style1);
Assert.AreEqual(style1, cell.CellStyle);
// Apply the other, Changes
cell.CellStyle = (/*setter*/style2);
Assert.AreEqual(style2, cell.CellStyle);
// Remove, goes back to default
cell.CellStyle = (/*setter*/null);
Assert.AreEqual(defaultStyle, cell.CellStyle);
// Add back, returns
cell.CellStyle = (/*setter*/style2);
Assert.AreEqual(style2, cell.CellStyle);
wb.Close();
}
[Test]
public void Test57008()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet sheet = wb.CreateSheet();
IRow row0 = sheet.CreateRow(0);
ICell cell0 = row0.CreateCell(0);
cell0.SetCellValue("row 0, cell 0 _x0046_ without Changes");
ICell cell1 = row0.CreateCell(1);
cell1.SetCellValue("row 0, cell 1 _x005fx0046_ with Changes");
ICell cell2 = row0.CreateCell(2);
cell2.SetCellValue("hgh_x0041_**_x0100_*_x0101_*_x0190_*_x0200_*_x0300_*_x0427_*");
CheckUnicodeValues(wb);
// String fname = "/tmp/Test_xNNNN_inCell" + (wb is HSSFWorkbook ? ".xls" : ".xlsx");
// FileOutputStream out1 = new FileOutputStream(fname);
// try {
// wb.Write(out1);
// } finally {
// out1.Close();
// }
IWorkbook wbBack = _testDataProvider.WriteOutAndReadBack(wb);
CheckUnicodeValues(wbBack);
}
protected void CheckUnicodeValues(IWorkbook wb)
{
Assert.AreEqual((wb is HSSFWorkbook ? "row 0, cell 0 _x0046_ without Changes" : "row 0, cell 0 F without Changes"),
wb.GetSheetAt(0).GetRow(0).GetCell(0).ToString());
Assert.AreEqual((wb is HSSFWorkbook ? "row 0, cell 1 _x005fx0046_ with Changes" : "row 0, cell 1 _x005fx0046_ with Changes"),
wb.GetSheetAt(0).GetRow(0).GetCell(1).ToString());
Assert.AreEqual((wb is HSSFWorkbook ? "hgh_x0041_**_x0100_*_x0101_*_x0190_*_x0200_*_x0300_*_x0427_*" : "hghA**\u0100*\u0101*\u0190*\u0200*\u0300*\u0427*"),
wb.GetSheetAt(0).GetRow(0).GetCell(2).ToString());
}
/**
* The maximum length of cell contents (text) is 32,767 characters.
* @
*/
[Test]
public void TestMaxTextLength()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet sheet = wb.CreateSheet();
ICell cell = sheet.CreateRow(0).CreateCell(0);
int maxlen = wb is HSSFWorkbook ?
SpreadsheetVersion.EXCEL97.MaxTextLength
: SpreadsheetVersion.EXCEL2007.MaxTextLength;
Assert.AreEqual(32767, maxlen);
StringBuilder b = new StringBuilder();
// 32767 is okay
for (int i = 0; i < maxlen; i++)
{
b.Append("X");
}
cell.SetCellValue(b.ToString());
b.Append("X");
// 32768 produces an invalid XLS file
try
{
cell.SetCellValue(b.ToString());
Assert.Fail("Expected exception");
}
catch (ArgumentException e)
{
Assert.AreEqual("The maximum length of cell contents (text) is 32,767 characters", e.Message);
}
wb.Close();
}
/**
* Tests that the setAsActiveCell and getActiveCell function pairs work together
*/
[Test]
public void SetAsActiveCell()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet sheet = wb.CreateSheet();
IRow row = sheet.CreateRow(0);
ICell A1 = row.CreateCell(0);
ICell B1 = row.CreateCell(1);
A1.SetAsActiveCell();
Assert.AreEqual(A1.Address, sheet.ActiveCell);
B1.SetAsActiveCell();
Assert.AreEqual(B1.Address, sheet.ActiveCell);
wb.Close();
}
[Test]
public void GetCellComment()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet sheet = wb.CreateSheet();
ICreationHelper factory = wb.GetCreationHelper();
IRow row = sheet.CreateRow(0);
ICell cell = row.CreateCell(1);
// cell does not have a comment
Assert.IsNull(cell.CellComment);
// add a cell comment
IClientAnchor anchor = factory.CreateClientAnchor();
anchor.Col1 = cell.ColumnIndex;
anchor.Col2 = cell.ColumnIndex + 1;
anchor.Row1 = row.RowNum;
anchor.Row2 = row.RowNum + 3;
IDrawing drawing = sheet.CreateDrawingPatriarch();
IComment comment = drawing.CreateCellComment(anchor);
IRichTextString str = factory.CreateRichTextString("Hello, World!");
comment.String = str;
comment.Author = "Apache POI";
cell.CellComment = comment;
// ideally assertSame, but XSSFCell creates a new XSSFCellComment wrapping the same bean for every call to getCellComment.
Assert.AreEqual(comment, cell.CellComment);
wb.Close();
}
[Test]
public void PrimitiveToEnumReplacementDoesNotBreakBackwardsCompatibility()
{
// bug 59836
// until we have changes POI from working on primitives (int) to enums,
// we should make sure we minimize backwards compatibility breakages.
// This method tests the old way of working with cell types, alignment, etc.
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet sheet = wb.CreateSheet();
IRow row = sheet.CreateRow(0);
ICell cell = row.CreateCell(0);
// CellType.* -> CellType.*
cell.SetCellValue(5.0);
Assert.AreEqual(CellType.Numeric, cell.CellType);
Assert.AreEqual(0, (int)cell.CellType);
//Assert.AreEqual(CellType.NUMERIC, cell.GetCellTypeEnum()); // make sure old way and new way are compatible
// make sure switch(int|Enum) still works. Cases must be statically resolvable in1 Java 6 ("constant expression required")
switch (cell.CellType)
{
case CellType.Numeric:
// expected
break;
case CellType.String:
case CellType.Error:
case CellType.Formula:
case CellType.Blank:
default:
Assert.Fail("unexpected cell type: " + cell.CellType);
break;
}
}
}
}
| |
// 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.Immutable;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Threading;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.VisualStudio.Debugger;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.ComponentInterfaces;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
public abstract class ExpressionCompiler :
IDkmClrExpressionCompiler,
IDkmClrExpressionCompilerCallback,
IDkmModuleModifiedNotification
{
static ExpressionCompiler()
{
FatalError.Handler = FailFast.OnFatalException;
}
private static readonly ReadOnlyCollection<Alias> s_NoAliases = new ReadOnlyCollection<Alias>(new Alias[0]);
DkmCompiledClrLocalsQuery IDkmClrExpressionCompiler.GetClrLocalVariableQuery(
DkmInspectionContext inspectionContext,
DkmClrInstructionAddress instructionAddress,
bool argumentsOnly)
{
try
{
var moduleInstance = instructionAddress.ModuleInstance;
var runtimeInstance = instructionAddress.RuntimeInstance;
var runtimeInspectionContext = RuntimeInspectionContext.Create(inspectionContext);
var aliases = argumentsOnly ? null : s_NoAliases;
string error;
var r = this.CompileWithRetry(
moduleInstance,
runtimeInstance.GetMetadataBlocks(moduleInstance.AppDomain),
(blocks, useReferencedModulesOnly) => CreateMethodContext(instructionAddress, blocks, useReferencedModulesOnly),
(context, diagnostics) =>
{
var builder = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(
aliases,
builder,
argumentsOnly,
diagnostics,
out typeName,
testData: null);
Debug.Assert((builder.Count == 0) == (assembly.Count == 0));
var locals = new ReadOnlyCollection<DkmClrLocalVariableInfo>(builder.SelectAsArray(ToLocalVariableInfo));
builder.Free();
return new GetLocalsResult(typeName, locals, assembly);
},
out error);
return DkmCompiledClrLocalsQuery.Create(runtimeInstance, null, this.CompilerId, r.Assembly, r.TypeName, r.Locals);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
void IDkmClrExpressionCompiler.CompileExpression(
DkmLanguageExpression expression,
DkmClrInstructionAddress instructionAddress,
DkmInspectionContext inspectionContext,
out string error,
out DkmCompiledClrInspectionQuery result)
{
try
{
var moduleInstance = instructionAddress.ModuleInstance;
var runtimeInstance = instructionAddress.RuntimeInstance;
var runtimeInspectionContext = RuntimeInspectionContext.Create(inspectionContext);
var r = this.CompileWithRetry(
moduleInstance,
runtimeInstance.GetMetadataBlocks(moduleInstance.AppDomain),
(blocks, useReferencedModulesOnly) => CreateMethodContext(instructionAddress, blocks, useReferencedModulesOnly),
(context, diagnostics) =>
{
ResultProperties resultProperties;
var compileResult = context.CompileExpression(
runtimeInspectionContext,
expression.Text,
expression.CompilationFlags,
diagnostics,
out resultProperties,
testData: null);
return new CompileExpressionResult(compileResult, resultProperties);
},
out error);
result = r.CompileResult.ToQueryResult(this.CompilerId, r.ResultProperties, runtimeInstance);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
void IDkmClrExpressionCompiler.CompileAssignment(
DkmLanguageExpression expression,
DkmClrInstructionAddress instructionAddress,
DkmEvaluationResult lValue,
out string error,
out DkmCompiledClrInspectionQuery result)
{
try
{
var moduleInstance = instructionAddress.ModuleInstance;
var runtimeInstance = instructionAddress.RuntimeInstance;
var runtimeInspectionContext = RuntimeInspectionContext.Create(lValue.InspectionContext);
var r = this.CompileWithRetry(
moduleInstance,
runtimeInstance.GetMetadataBlocks(moduleInstance.AppDomain),
(blocks, useReferencedModulesOnly) => CreateMethodContext(instructionAddress, blocks, useReferencedModulesOnly),
(context, diagnostics) =>
{
ResultProperties resultProperties;
var compileResult = context.CompileAssignment(
runtimeInspectionContext,
lValue.FullName,
expression.Text,
diagnostics,
out resultProperties,
testData: null);
return new CompileExpressionResult(compileResult, resultProperties);
},
out error);
Debug.Assert((r.ResultProperties.Flags & DkmClrCompilationResultFlags.PotentialSideEffect) == DkmClrCompilationResultFlags.PotentialSideEffect);
result = r.CompileResult.ToQueryResult(this.CompilerId, r.ResultProperties, runtimeInstance);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
void IDkmClrExpressionCompilerCallback.CompileDisplayAttribute(
DkmLanguageExpression expression,
DkmClrModuleInstance moduleInstance,
int token,
out string error,
out DkmCompiledClrInspectionQuery result)
{
try
{
var runtimeInstance = moduleInstance.RuntimeInstance;
var appDomain = moduleInstance.AppDomain;
var compileResult = this.CompileWithRetry(
moduleInstance,
runtimeInstance.GetMetadataBlocks(appDomain),
(blocks, useReferencedModulesOnly) => CreateTypeContext(appDomain, blocks, moduleInstance.Mvid, token, useReferencedModulesOnly),
(context, diagnostics) =>
{
ResultProperties unusedResultProperties;
return context.CompileExpression(
RuntimeInspectionContext.Empty,
expression.Text,
DkmEvaluationFlags.TreatAsExpression,
diagnostics,
out unusedResultProperties,
testData: null);
},
out error);
result = compileResult.ToQueryResult(this.CompilerId, default(ResultProperties), runtimeInstance);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
/// <remarks>
/// Internal for testing.
/// </remarks>
internal static bool ShouldTryAgainWithMoreMetadataBlocks(DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtrFunction, ImmutableArray<AssemblyIdentity> missingAssemblyIdentities, ref ImmutableArray<MetadataBlock> references)
{
var newReferences = DkmUtilities.GetMetadataBlocks(getMetaDataBytesPtrFunction, missingAssemblyIdentities);
if (newReferences.Length > 0)
{
references = references.AddRange(newReferences);
return true;
}
return false;
}
void IDkmModuleModifiedNotification.OnModuleModified(DkmModuleInstance moduleInstance)
{
// If the module is not a managed module, the module change has no effect.
var module = moduleInstance as DkmClrModuleInstance;
if (module == null)
{
return;
}
// Drop any context cached on the AppDomain.
var appDomain = module.AppDomain;
RemoveDataItem(appDomain);
}
internal abstract DiagnosticFormatter DiagnosticFormatter { get; }
internal abstract DkmCompilerId CompilerId { get; }
internal abstract EvaluationContextBase CreateTypeContext(
DkmClrAppDomain appDomain,
ImmutableArray<MetadataBlock> metadataBlocks,
Guid moduleVersionId,
int typeToken,
bool useReferencedModulesOnly);
internal abstract EvaluationContextBase CreateMethodContext(
DkmClrAppDomain appDomain,
ImmutableArray<MetadataBlock> metadataBlocks,
Lazy<ImmutableArray<AssemblyReaders>> lazyAssemblyReaders,
object symReader,
Guid moduleVersionId,
int methodToken,
int methodVersion,
int ilOffset,
int localSignatureToken,
bool useReferencedModulesOnly);
internal abstract void RemoveDataItem(DkmClrAppDomain appDomain);
private EvaluationContextBase CreateMethodContext(DkmClrInstructionAddress instructionAddress, ImmutableArray<MetadataBlock> metadataBlocks, bool useReferencedModulesOnly)
{
var moduleInstance = instructionAddress.ModuleInstance;
var methodToken = instructionAddress.MethodId.Token;
int localSignatureToken;
try
{
localSignatureToken = moduleInstance.GetLocalSignatureToken(methodToken);
}
catch (InvalidOperationException)
{
// No local signature. May occur when debugging .dmp.
localSignatureToken = 0;
}
catch (FileNotFoundException)
{
// No local signature. May occur when debugging heapless dumps.
localSignatureToken = 0;
}
return this.CreateMethodContext(
moduleInstance.AppDomain,
metadataBlocks,
new Lazy<ImmutableArray<AssemblyReaders>>(() => instructionAddress.MakeAssemblyReaders(), LazyThreadSafetyMode.None),
symReader: moduleInstance.GetSymReader(),
moduleVersionId: moduleInstance.Mvid,
methodToken: methodToken,
methodVersion: (int)instructionAddress.MethodId.Version,
ilOffset: (int)instructionAddress.ILOffset,
localSignatureToken: localSignatureToken,
useReferencedModulesOnly: useReferencedModulesOnly);
}
internal delegate EvaluationContextBase CreateContextDelegate(ImmutableArray<MetadataBlock> metadataBlocks, bool useReferencedModulesOnly);
internal delegate TResult CompileDelegate<TResult>(EvaluationContextBase context, DiagnosticBag diagnostics);
private TResult CompileWithRetry<TResult>(
DkmClrModuleInstance moduleInstance,
ImmutableArray<MetadataBlock> metadataBlocks,
CreateContextDelegate createContext,
CompileDelegate<TResult> compile,
out string errorMessage)
{
return CompileWithRetry(
metadataBlocks,
this.DiagnosticFormatter,
createContext,
compile,
(AssemblyIdentity assemblyIdentity, out uint size) => moduleInstance.AppDomain.GetMetaDataBytesPtr(assemblyIdentity.GetDisplayName(), out size),
out errorMessage);
}
internal static TResult CompileWithRetry<TResult>(
ImmutableArray<MetadataBlock> metadataBlocks,
DiagnosticFormatter formatter,
CreateContextDelegate createContext,
CompileDelegate<TResult> compile,
DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr,
out string errorMessage)
{
errorMessage = null;
TResult compileResult;
PooledHashSet<AssemblyIdentity> assembliesLoadedInRetryLoop = null;
bool tryAgain;
do
{
var context = createContext(metadataBlocks, useReferencedModulesOnly: false);
var diagnostics = DiagnosticBag.GetInstance();
compileResult = compile(context, diagnostics);
tryAgain = false;
if (diagnostics.HasAnyErrors())
{
bool useReferencedModulesOnly;
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
errorMessage = context.GetErrorMessageAndMissingAssemblyIdentities(
diagnostics,
formatter,
preferredUICulture: null,
useReferencedModulesOnly: out useReferencedModulesOnly,
missingAssemblyIdentities: out missingAssemblyIdentities);
if (useReferencedModulesOnly)
{
Debug.Assert(missingAssemblyIdentities.IsEmpty);
var otherContext = createContext(metadataBlocks, useReferencedModulesOnly: true);
var otherDiagnostics = DiagnosticBag.GetInstance();
var otherResult = compile(otherContext, otherDiagnostics);
if (!otherDiagnostics.HasAnyErrors())
{
errorMessage = null;
compileResult = otherResult;
}
otherDiagnostics.Free();
}
else
{
if (!missingAssemblyIdentities.IsEmpty)
{
if (assembliesLoadedInRetryLoop == null)
{
assembliesLoadedInRetryLoop = PooledHashSet<AssemblyIdentity>.GetInstance();
}
// If any identities failed to add (they were already in the list), then don't retry.
if (assembliesLoadedInRetryLoop.AddAll(missingAssemblyIdentities))
{
tryAgain = ShouldTryAgainWithMoreMetadataBlocks(getMetaDataBytesPtr, missingAssemblyIdentities, ref metadataBlocks);
}
}
}
}
diagnostics.Free();
} while (tryAgain);
assembliesLoadedInRetryLoop?.Free();
return compileResult;
}
private static DkmClrLocalVariableInfo ToLocalVariableInfo(LocalAndMethod local)
{
return DkmClrLocalVariableInfo.Create(local.LocalName, local.MethodName, local.Flags, DkmEvaluationResultCategory.Data, local.GetCustomTypeInfo().ToDkmClrCustomTypeInfo());
}
private struct GetLocalsResult
{
internal readonly string TypeName;
internal readonly ReadOnlyCollection<DkmClrLocalVariableInfo> Locals;
internal readonly ReadOnlyCollection<byte> Assembly;
internal GetLocalsResult(string typeName, ReadOnlyCollection<DkmClrLocalVariableInfo> locals, ReadOnlyCollection<byte> assembly)
{
this.TypeName = typeName;
this.Locals = locals;
this.Assembly = assembly;
}
}
private struct CompileExpressionResult
{
internal readonly CompileResult CompileResult;
internal readonly ResultProperties ResultProperties;
internal CompileExpressionResult(CompileResult compileResult, ResultProperties resultProperties)
{
this.CompileResult = compileResult;
this.ResultProperties = resultProperties;
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Azure.Management.HDInsight.Job
{
/// <summary>
/// Operations for managing jobs against HDInsight clusters.
/// </summary>
public partial class JobOperationsExtensions
{
/// <summary>
/// Gets the task log summary from execution of a jobDetails.
/// </summary>
/// <param name="jobId">
/// Required. The id of the job.
/// </param>
/// <param name="targetDirectory">
/// Required. The directory in which to download the logs to.
/// </param>
/// <param name="storageAccountName">
/// The name of the storage account
/// </param>
/// <param name="storageAccountKey">
///
/// </param>
/// <param name="defaultContainer">
///
/// </param>
/// Cancellation token.
/// </param>
/// <returns>
///
/// </returns>
public static void DownloadJobTaskLogs(this IJobOperations operations, string jobId, string targetDirectory,
string storageAccountName, string storageAccountKey, string defaultContainer)
{
Task.Factory.StartNew(
(object s) =>
((IJobOperations) s).DownloadJobTaskLogsAsync(jobId, targetDirectory, storageAccountName,
storageAccountKey, defaultContainer), operations, CancellationToken.None,
TaskCreationOptions.None, TaskScheduler.Default)
.Unwrap()
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Gets the task log summary from execution of a jobDetails.
/// </summary>
/// <param name="jobId">
/// Required. The id of the job.
/// </param>
/// <param name="targetDirectory">
/// Required. The directory in which to download the logs to.
/// </param>
/// <param name="storageAccountName">
/// The name of the storage account.
/// </param>
/// <param name="storageAccountKey">
/// The default storage account key.
/// </param>
/// <param name="defaultContainer">
/// The default container.
/// </param>
/// Cancellation token.
/// </param>
/// <returns>
///
/// </returns>
public static Task DownloadJobTaskLogsAsync(this IJobOperations operations, string jobId, string targetDirectory,
string storageAccountName, string storageAccountKey, string defaultContainer)
{
return operations.DownloadJobTaskLogsAsync(jobId, targetDirectory, storageAccountName, storageAccountKey,
defaultContainer, CancellationToken.None);
}
/// <summary>
/// Gets the output from the execution of an individual jobDetails.
/// </summary>
/// <param name="jobId">
/// Required. The id of the job.
/// </param>
/// <param name="defaultContainer">
/// Required. The default container.
/// </param>
/// <param name="storageAccountName">
/// Required. The storage account the container lives on.
/// </param>
/// <returns>
/// The output of an individual jobDetails by jobId.
/// </returns>
public static Stream GetJobOutput(this IJobOperations operations, string jobId, string storageAccountName,
string storageAccountKey, string defaultContainer)
{
return Task.Factory.StartNew(
(object s) =>
((IJobOperations) s).GetJobOutputAsync(jobId, storageAccountName, storageAccountKey,
defaultContainer), operations,
CancellationToken.None,
TaskCreationOptions.None, TaskScheduler.Default)
.Unwrap()
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Gets the output from the execution of an individual jobDetails.
/// </summary>
/// <param name="operations"></param>
/// <param name="jobId">
/// Required. The id of the job.
/// </param>
/// <param name="storageAccountName">
/// Required. The storage account the container lives on.
/// </param>
/// <param name="storageAccountKey"></param>
/// <param name="defaultContainer">
/// Required. The default container.
/// </param>
/// <returns>
/// The output of an individual jobDetails by jobId.
/// </returns>
public static Task<Stream> GetJobOutputAsync(this IJobOperations operations, string jobId,
string storageAccountName, string storageAccountKey, string defaultContainer)
{
return operations.GetJobOutputAsync(jobId, storageAccountName, storageAccountKey,
defaultContainer, CancellationToken.None);
}
/// <summary>
/// Gets the error logs from the execution of an individual jobDetails.
/// </summary>
/// <param name="jobId">
/// Required. The id of the job.
/// </param>
/// <param name="defaultContainer">
/// Required. The default container.
/// </param>
/// <param name="storageAccountName">
/// Required. The storage account the container lives on.
/// </param>
/// <returns>
/// The error logs of an individual jobDetails by jobId.
/// </returns>
public static Stream GetJobErrorLogs(this IJobOperations operations, string jobId,
string storageAccountName, string storageAccountKey, string defaultContainer)
{
return Task.Factory.StartNew(
(object s) =>
((IJobOperations)s).GetJobErrorLogsAsync(jobId, storageAccountName, storageAccountKey,
defaultContainer), operations,
CancellationToken.None,
TaskCreationOptions.None, TaskScheduler.Default)
.Unwrap()
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Gets the error logs from the execution of an individual jobDetails.
/// </summary>
/// <param name="jobId">
/// Required. The id of the job.
/// </param>
/// <param name="defaultContainer">
/// Required. The default container.
/// </param>
/// <param name="storageAccountName">
/// Required. The storage account the container lives on.
/// </param>
/// <returns>
/// The error logs of an individual jobDetails by jobId.
/// </returns>
public static Task<Stream> GetJobErrorLogsAsync(this IJobOperations operations, string jobId,
string storageAccountName, string storageAccountKey, string defaultContainer)
{
return operations.GetJobErrorLogsAsync(jobId, storageAccountName, storageAccountKey,
defaultContainer, CancellationToken.None);
}
/// <summary>
/// Gets the task logs from the execution of an individual jobDetails.
/// </summary>
/// <param name="jobId">
/// Required. The id of the job.
/// </param>
/// <param name="defaultContainer">
/// Required. The default container.
/// </param>
/// <param name="storageAccountName">
/// Required. The storage account the container lives on.
/// </param>
/// <returns>
/// The task logs of an individual jobDetails by jobId.
/// </returns>
public static Stream GetJobTaskLogSummary(this IJobOperations operations, string jobId,
string storageAccountName, string storageAccountKey, string defaultContainer)
{
return Task.Factory.StartNew(
(object s) =>
((IJobOperations)s).GetJobTaskLogSummaryAsync(jobId, storageAccountName, storageAccountKey,
defaultContainer), operations, CancellationToken.None,
TaskCreationOptions.None, TaskScheduler.Default)
.Unwrap()
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Gets the task logs from the execution of an individual jobDetails.
/// </summary>
/// <param name="jobId">
/// Required. The id of the job.
/// </param>
/// <param name="defaultContainer">
/// Required. The default container.
/// </param>
/// <param name="storageAccountName">
/// Required. The storage account the container lives on.
/// </param>
/// <returns>
/// The task logs of an individual jobDetails by jobId.
/// </returns>
public static Task<Stream> GetJobTaskLogSummaryAsync(this IJobOperations operations, string jobId,
string storageAccountName, string storageAccountKey, string defaultContainer)
{
return operations.GetJobTaskLogSummaryAsync(jobId, storageAccountName, storageAccountKey,
defaultContainer, CancellationToken.None);
}
}
}
| |
#region Copyright
//
// Nini Configuration Project.
// Copyright (C) 2006 Brent R. Matzelle. All rights reserved.
//
// This software is published under the terms of the MIT X11 license, a copy of
// which has been included with this distribution in the LICENSE.txt file.
//
#endregion
using System;
using System.IO;
using System.Text;
namespace Nini.Ini
{
#region IniWriteState enumeration
/// <include file='IniWriter.xml' path='//Enum[@name="IniWriteState"]/docs/*' />
public enum IniWriteState : int
{
/// <include file='IniWriter.xml' path='//Enum[@name="IniWriteState"]/Value[@name="Start"]/docs/*' />
Start,
/// <include file='IniWriter.xml' path='//Enum[@name="IniWriteState"]/Value[@name="BeforeFirstSection"]/docs/*' />
BeforeFirstSection,
/// <include file='IniWriter.xml' path='//Enum[@name="IniWriteState"]/Value[@name="Section"]/docs/*' />
Section,
/// <include file='IniWriter.xml' path='//Enum[@name="IniWriteState"]/Value[@name="Closed"]/docs/*' />
Closed
};
#endregion
/// <include file='IniWriter.xml' path='//Class[@name="IniWriter"]/docs/*' />
public class IniWriter : IDisposable
{
#region Private variables
int indentation = 0;
bool useValueQuotes = false;
IniWriteState writeState = IniWriteState.Start;
char commentDelimiter = ';';
char assignDelimiter = '=';
TextWriter textWriter = null;
string eol = "\r\n";
StringBuilder indentationBuffer = new StringBuilder ();
Stream baseStream = null;
bool disposed = false;
#endregion
#region Public properties
/// <include file='IniWriter.xml' path='//Property[@name="Indentation"]/docs/*' />
public int Indentation
{
get { return indentation; }
set
{
if (value < 0)
throw new ArgumentException ("Negative values are illegal");
indentation = value;
indentationBuffer.Remove(0, indentationBuffer.Length);
for (int i = 0; i < value; i++)
indentationBuffer.Append (' ');
}
}
/// <include file='IniWriter.xml' path='//Property[@name="UseValueQuotes"]/docs/*' />
public bool UseValueQuotes
{
get { return useValueQuotes; }
set { useValueQuotes = value; }
}
/// <include file='IniWriter.xml' path='//Property[@name="WriteState"]/docs/*' />
public IniWriteState WriteState
{
get { return writeState; }
}
/// <include file='IniWriter.xml' path='//Property[@name="CommentDelimiter"]/docs/*' />
public char CommentDelimiter
{
get { return commentDelimiter; }
set { commentDelimiter = value; }
}
/// <include file='IniWriter.xml' path='//Property[@name="AssignDelimiter"]/docs/*' />
public char AssignDelimiter
{
get { return assignDelimiter; }
set { assignDelimiter = value; }
}
/// <include file='IniWriter.xml' path='//Property[@name="BaseStream"]/docs/*' />
public Stream BaseStream
{
get { return baseStream; }
}
#endregion
#region Constructors
/// <include file='IniWriter.xml' path='//Constructor[@name="ConstructorPath"]/docs/*' />
public IniWriter(string filePath)
: this (new FileStream (filePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
}
/// <include file='IniWriter.xml' path='//Constructor[@name="ConstructorTextWriter"]/docs/*' />
public IniWriter (TextWriter writer)
{
textWriter = writer;
StreamWriter streamWriter = writer as StreamWriter;
if (streamWriter != null) {
baseStream = streamWriter.BaseStream;
}
}
/// <include file='IniWriter.xml' path='//Constructor[@name="ConstructorStream"]/docs/*' />
public IniWriter (Stream stream)
: this (new StreamWriter (stream))
{
}
#endregion
#region Public methods
/// <include file='IniWriter.xml' path='//Method[@name="Close"]/docs/*' />
public void Close ()
{
textWriter.Close ();
writeState = IniWriteState.Closed;
}
/// <include file='IniWriter.xml' path='//Method[@name="Flush"]/docs/*' />
public void Flush ()
{
textWriter.Flush ();
}
/// <include file='IniWriter.xml' path='//Method[@name="ToString"]/docs/*' />
public override string ToString ()
{
return textWriter.ToString ();
}
/// <include file='IniWriter.xml' path='//Method[@name="WriteSection"]/docs/*' />
public void WriteSection (string section)
{
ValidateState ();
writeState = IniWriteState.Section;
WriteLine ("[" + section + "]");
}
/// <include file='IniWriter.xml' path='//Method[@name="WriteSectionComment"]/docs/*' />
public void WriteSection (string section, string comment)
{
ValidateState ();
writeState = IniWriteState.Section;
WriteLine ("[" + section + "]" + Comment(comment));
}
/// <include file='IniWriter.xml' path='//Method[@name="WriteKey"]/docs/*' />
public void WriteKey (string key, string value)
{
ValidateStateKey ();
WriteLine (key + " " + assignDelimiter + " " + GetKeyValue (value));
}
/// <include file='IniWriter.xml' path='//Method[@name="WriteKeyComment"]/docs/*' />
public void WriteKey (string key, string value, string comment)
{
ValidateStateKey ();
WriteLine (key + " " + assignDelimiter + " " + GetKeyValue (value) + Comment (comment));
}
/// <include file='IniWriter.xml' path='//Method[@name="WriteEmpty"]/docs/*' />
public void WriteEmpty ()
{
ValidateState ();
if (writeState == IniWriteState.Start) {
writeState = IniWriteState.BeforeFirstSection;
}
WriteLine ("");
}
/// <include file='IniWriter.xml' path='//Method[@name="WriteEmptyComment"]/docs/*' />
public void WriteEmpty (string comment)
{
ValidateState ();
if (writeState == IniWriteState.Start) {
writeState = IniWriteState.BeforeFirstSection;
}
if (comment == null) {
WriteLine ("");
} else {
WriteLine (commentDelimiter + " " + comment);
}
}
/// <include file='IniWriter.xml' path='//Method[@name="Dispose"]/docs/*' />
public void Dispose ()
{
Dispose (true);
}
#endregion
#region Protected methods
/// <include file='IniWriter.xml' path='//Method[@name="DisposeBoolean"]/docs/*' />
protected virtual void Dispose (bool disposing)
{
if (!disposed)
{
textWriter.Close ();
baseStream.Close ();
disposed = true;
if (disposing)
{
GC.SuppressFinalize (this);
}
}
}
#endregion
#region Private methods
/// <summary>
/// Destructor.
/// </summary>
~IniWriter ()
{
Dispose (false);
}
/// <summary>
/// Returns the value of a key.
/// </summary>
private string GetKeyValue (string text)
{
string result;
if (useValueQuotes) {
result = MassageValue ('"' + text + '"');
} else {
result = MassageValue (text);
}
return result;
}
/// <summary>
/// Validates whether a key can be written.
/// </summary>
private void ValidateStateKey ()
{
ValidateState ();
switch (writeState)
{
case IniWriteState.BeforeFirstSection:
case IniWriteState.Start:
throw new InvalidOperationException ("The WriteState is not Section");
case IniWriteState.Closed:
throw new InvalidOperationException ("The writer is closed");
}
}
/// <summary>
/// Validates the state to determine if the item can be written.
/// </summary>
private void ValidateState ()
{
if (writeState == IniWriteState.Closed) {
throw new InvalidOperationException ("The writer is closed");
}
}
/// <summary>
/// Returns a formatted comment.
/// </summary>
private string Comment (string text)
{
return (text == null) ? "" : (" " + commentDelimiter + " " + text);
}
/// <summary>
/// Writes data to the writer.
/// </summary>
private void Write (string value)
{
textWriter.Write (indentationBuffer.ToString () + value);
}
/// <summary>
/// Writes a full line to the writer.
/// </summary>
private void WriteLine (string value)
{
Write (value + eol);
}
/// <summary>
/// Fixes the incoming value to prevent illegal characters from
/// hurting the integrity of the INI file.
/// </summary>
private string MassageValue (string text)
{
return text.Replace ("\n", "");
}
#endregion
}
}
| |
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Remarks: This file is imported from the SixPack library. This is ok because
// the copyright holder has agreed to redistribute this file under the license
// used in YamlDotNet.
using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace YamlDotNet.Serialization.Utilities
{
/// <summary>
/// Performs type conversions using every standard provided by the .NET library.
/// </summary>
public static class TypeConverter
{
/// <summary>
/// Converts the specified value.
/// </summary>
/// <typeparam name="T">The type to which the value is to be converted.</typeparam>
/// <param name="value">The value to convert.</param>
/// <returns></returns>
public static T ChangeType<T>(object value)
{
return (T)ChangeType(value, typeof(T));
}
/// <summary>
/// Converts the specified value.
/// </summary>
/// <typeparam name="T">The type to which the value is to be converted.</typeparam>
/// <param name="value">The value to convert.</param>
/// <param name="provider">The provider.</param>
/// <returns></returns>
public static T ChangeType<T>(object value, IFormatProvider provider)
{
return (T)ChangeType(value, typeof(T), provider);
}
/// <summary>
/// Converts the specified value.
/// </summary>
/// <typeparam name="T">The type to which the value is to be converted.</typeparam>
/// <param name="value">The value to convert.</param>
/// <param name="culture">The culture.</param>
/// <returns></returns>
public static T ChangeType<T>(object value, CultureInfo culture)
{
return (T)ChangeType(value, typeof(T), culture);
}
/// <summary>
/// Converts the specified value using the invariant culture.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="destinationType">The type to which the value is to be converted.</param>
/// <returns></returns>
public static object ChangeType(object value, Type destinationType)
{
return ChangeType(value, destinationType, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the specified value.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="destinationType">The type to which the value is to be converted.</param>
/// <param name="provider">The format provider.</param>
/// <returns></returns>
public static object ChangeType(object value, Type destinationType, IFormatProvider provider)
{
return ChangeType(value, destinationType, new CultureInfoAdapter(CultureInfo.CurrentCulture, provider));
}
/// <summary>
/// Converts the specified value.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="destinationType">The type to which the value is to be converted.</param>
/// <param name="culture">The culture.</param>
/// <returns></returns>
public static object ChangeType(object value, Type destinationType, CultureInfo culture)
{
// Handle null and DBNull
if (value == null || value is DBNull)
{
return destinationType.IsValueType() ? Activator.CreateInstance(destinationType) : null;
}
var sourceType = value.GetType();
// If the source type is compatible with the destination type, no conversion is needed
if (destinationType.IsAssignableFrom(sourceType))
{
return value;
}
// Nullable types get a special treatment
if (destinationType.IsGenericType())
{
var genericTypeDefinition = destinationType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
var innerType = destinationType.GetGenericArguments()[0];
var convertedValue = ChangeType(value, innerType, culture);
return Activator.CreateInstance(destinationType, convertedValue);
}
}
// Enums also require special handling
if (destinationType.IsEnum())
{
var valueText = value as string;
return valueText != null ? Enum.Parse(destinationType, valueText, true) : value;
}
// Special case for booleans to support parsing "1" and "0". This is
// necessary for compatibility with XML Schema.
if (destinationType == typeof(bool))
{
if ("0".Equals(value))
return false;
if ("1".Equals(value))
return true;
}
// Try with the source type's converter
var sourceConverter = TypeDescriptor.GetConverter(value);
if (sourceConverter != null && sourceConverter.CanConvertTo(destinationType))
{
return sourceConverter.ConvertTo(null, culture, value, destinationType);
}
// Try with the destination type's converter
var destinationConverter = TypeDescriptor.GetConverter(destinationType);
if (destinationConverter != null && destinationConverter.CanConvertFrom(sourceType))
{
return destinationConverter.ConvertFrom(null, culture, value);
}
// Try to find a casting operator in the source or destination type
foreach (var type in new[] { sourceType, destinationType })
{
foreach (var method in type.GetPublicStaticMethods())
{
var isCastingOperator =
method.IsSpecialName &&
(method.Name == "op_Implicit" || method.Name == "op_Explicit") &&
destinationType.IsAssignableFrom(method.ReturnParameter.ParameterType);
if (isCastingOperator)
{
var parameters = method.GetParameters();
var isCompatible =
parameters.Length == 1 &&
parameters[0].ParameterType.IsAssignableFrom(sourceType);
if (isCompatible)
{
try
{
return method.Invoke(null, new[] { value });
}
catch (TargetInvocationException ex)
{
throw ex.Unwrap();
}
}
}
}
}
// If source type is string, try to find a Parse or TryParse method
if (sourceType == typeof(string))
{
try
{
// Try with - public static T Parse(string, IFormatProvider)
var parseMethod = destinationType.GetPublicStaticMethod("Parse", typeof(string), typeof(IFormatProvider));
if (parseMethod != null)
{
return parseMethod.Invoke(null, new object[] { value, culture });
}
// Try with - public static T Parse(string)
parseMethod = destinationType.GetPublicStaticMethod("Parse", typeof(string));
if (parseMethod != null)
{
return parseMethod.Invoke(null, new object[] { value });
}
}
catch (TargetInvocationException ex)
{
throw ex.Unwrap();
}
}
// Handle TimeSpan
if (destinationType == typeof(TimeSpan))
{
return TimeSpan.Parse((string)ChangeType(value, typeof(string), CultureInfo.InvariantCulture));
}
// Default to the Convert class
return Convert.ChangeType(value, destinationType, CultureInfo.InvariantCulture);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace System.IO.FileSystem.Tests
{
public class DirectoryInfo_CreateSubDirectory : FileSystemTest
{
#region UniversalTests
[Fact]
public void NullAsPath_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(null));
}
[Fact]
public void EmptyAsPath_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(string.Empty));
}
[Fact]
public void PathAlreadyExistsAsFile()
{
string path = GetTestFileName();
File.Create(Path.Combine(TestDirectory, path)).Dispose();
Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(path));
Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(IOServices.AddTrailingSlashIfNeeded(path)));
Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(IOServices.RemoveTrailingSlash(path)));
}
[Theory]
[InlineData(FileAttributes.Hidden)]
[InlineData(FileAttributes.ReadOnly)]
[InlineData(FileAttributes.Normal)]
public void PathAlreadyExistsAsDirectory(FileAttributes attributes)
{
string path = GetTestFileName();
DirectoryInfo testDir = Directory.CreateDirectory(Path.Combine(TestDirectory, path));
FileAttributes original = testDir.Attributes;
try
{
testDir.Attributes = attributes;
Assert.Equal(testDir.FullName, new DirectoryInfo(TestDirectory).CreateSubdirectory(path).FullName);
}
finally
{
testDir.Attributes = original;
}
}
[Fact]
public void DotIsCurrentDirectory()
{
string path = GetTestFileName();
DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(path, "."));
Assert.Equal(IOServices.RemoveTrailingSlash(Path.Combine(TestDirectory, path)), result.FullName);
result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(path, ".") + Path.DirectorySeparatorChar);
Assert.Equal(IOServices.AddTrailingSlashIfNeeded(Path.Combine(TestDirectory, path)), result.FullName);
}
[Fact]
public void Conflicting_Parent_Directory()
{
string path = Path.Combine(TestDirectory, GetTestFileName(), "c");
Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(path));
}
[Fact]
public void DotDotIsParentDirectory()
{
DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(GetTestFileName(), ".."));
Assert.Equal(IOServices.RemoveTrailingSlash(TestDirectory), result.FullName);
result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(GetTestFileName(), "..") + Path.DirectorySeparatorChar);
Assert.Equal(IOServices.AddTrailingSlashIfNeeded(TestDirectory), result.FullName);
}
[Fact]
public void ValidPathWithTrailingSlash()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
var components = IOInputs.GetValidPathComponentNames();
Assert.All(components, (component) =>
{
string path = IOServices.AddTrailingSlashIfNeeded(component);
DirectoryInfo result = new DirectoryInfo(testDir.FullName).CreateSubdirectory(path);
Assert.Equal(Path.Combine(testDir.FullName, path), result.FullName);
Assert.True(Directory.Exists(result.FullName));
});
}
[Fact]
public void ValidPathWithoutTrailingSlash()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
var components = IOInputs.GetValidPathComponentNames();
Assert.All(components, (component) =>
{
string path = component;
DirectoryInfo result = new DirectoryInfo(testDir.FullName).CreateSubdirectory(path);
Assert.Equal(Path.Combine(testDir.FullName, path), result.FullName);
Assert.True(Directory.Exists(result.FullName));
});
}
[Fact]
public void ValidPathWithMultipleSubdirectories()
{
string dirName = Path.Combine(GetTestFileName(), "Test", "Test", "Test");
DirectoryInfo dir = new DirectoryInfo(TestDirectory).CreateSubdirectory(dirName);
Assert.Equal(dir.FullName, Path.Combine(TestDirectory, dirName));
}
[Fact]
public void AllowedSymbols()
{
string dirName = Path.GetRandomFileName() + "!@#$%^&";
DirectoryInfo dir = new DirectoryInfo(TestDirectory).CreateSubdirectory(dirName);
Assert.Equal(dir.FullName, Path.Combine(TestDirectory, dirName));
}
#endregion
#region PlatformSpecific
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void WindowsControWhiteSpace()
{
// CreateSubdirectory will throw when passed a path with control whitespace e.g. "\t"
var components = IOInputs.GetControlWhiteSpace();
Assert.All(components, (component) =>
{
string path = IOServices.RemoveTrailingSlash(GetTestFileName());
Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(component));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void WindowsSimpleWhiteSpace()
{
// CreateSubdirectory trims all simple whitespace, returning us the parent directory
// that called CreateSubdirectory
var components = IOInputs.GetSimpleWhiteSpace();
Assert.All(components, (component) =>
{
string path = IOServices.RemoveTrailingSlash(GetTestFileName());
DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(component);
Assert.True(Directory.Exists(result.FullName));
Assert.Equal(TestDirectory, IOServices.RemoveTrailingSlash(result.FullName));
});
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void UnixWhiteSpaceAsPath_Allowed()
{
var paths = IOInputs.GetWhiteSpace();
Assert.All(paths, (path) =>
{
new DirectoryInfo(TestDirectory).CreateSubdirectory(path);
Assert.True(Directory.Exists(Path.Combine(TestDirectory, path)));
});
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void UnixNonSignificantTrailingWhiteSpace()
{
// Unix treats trailing/prename whitespace as significant and a part of the name.
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
var components = IOInputs.GetWhiteSpace();
Assert.All(components, (component) =>
{
string path = IOServices.RemoveTrailingSlash(testDir.Name) + component;
DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(path);
Assert.True(Directory.Exists(result.FullName));
Assert.NotEqual(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void ExtendedPathSubdirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath());
Assert.True(testDir.Exists);
DirectoryInfo subDir = testDir.CreateSubdirectory("Foo");
Assert.True(subDir.Exists);
Assert.StartsWith(IOInputs.ExtendedPrefix, subDir.FullName);
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // UNC shares
public void UNCPathWithOnlySlashes()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.Throws<ArgumentException>(() => testDir.CreateSubdirectory("//"));
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Drawing;
using KMLib.Abstract;
namespace KMLib
{
public class Style : AStyleSelector
{
private string m_Id;
[XmlAttribute("id")]
public string Id
{
get
{
return m_Id;
}
set
{
m_Id = value;
}
}
public void Add(Style style)
{
if (m_Style == null)
{
m_Style = new List<Style>();
}
m_Style.Add(style);
}
private List<Style> m_Style;
//[XmlElement(ElementName = "BallonStyle", Type = typeof(BallonStyle))]
[XmlElement(ElementName = "IconStyle", Type = typeof(IconStyle))]
[XmlElement(ElementName = "LabelStyle", Type = typeof(LabelStyle))]
[XmlElement(ElementName = "LineStyle", Type = typeof(LineStyle))]
//[XmlElement(ElementName = "ListStyle", Type = typeof(ListStyle))]
[XmlElement(ElementName = "PolyStyle", Type = typeof(PolyStyle))]
public List<Style> Lists
{
get
{
return m_Style;
}
set
{
m_Style = value;
}
}
[XmlIgnore()]
private bool StyleSpecified = false;
}
public class ColorStyle : Style
{
public enum ColorMode { normal, random };
public ColorStyle(Color color)
{
m_Color = color;
}
public ColorStyle() { }
private ColorKML m_Color;
[XmlElement("color")]
public ColorKML Color
{
get
{
return m_Color;
}
set
{
m_Color = value;
}
}
private ColorMode m_colorMode;
[XmlElement("colorMode")]
public ColorMode colorMode
{
get
{
return m_colorMode;
}
set
{
m_colorMode = value;
colorModeSpecified = true;
}
}
[XmlIgnore()]
public bool colorModeSpecified = false;
}
public class PolyStyle : ColorStyle
{
}
public class LineStyle : ColorStyle
{
public LineStyle(Color color)
{
Color = color;
}
public LineStyle(Color color, float width)
{
Color = color;
m_Width = width;
}
public LineStyle() { }
private float m_Width = 1.0f;
[XmlElement("width")]
public float Width
{
get
{
return m_Width;
}
set
{
m_Width = value;
WidthSpecified = true;
}
}
[XmlIgnore()]
public bool WidthSpecified = false;
}
public class IconStyle : PolyStyle
{
public IconStyle(Color color)
{
Color = color;
}
public IconStyle(Icon icon)
{
m_Icon = icon;
}
public IconStyle(Color color, float scale, Icon icon)
{
Color = color;
m_scale = scale;
m_Icon = icon;
}
public IconStyle() { }
private Icon m_Icon;
[XmlElement("Icon")]
public Icon Icon
{
get
{
return m_Icon;
}
set
{
m_Icon = value;
IconSpecified = true;
}
}
[XmlIgnore()]
public bool IconSpecified = false;
private float m_scale = 1.0f;
[XmlElement("scale")]
public float scale
{
get
{
return m_scale;
}
set
{
m_scale = value;
scaleSpecified = true;
}
}
[XmlIgnore()]
public bool scaleSpecified = false;
}
public class LabelStyle : ColorStyle
{
public LabelStyle() { }
public LabelStyle(Color color)
{
Color = color;
}
public LabelStyle(float scale)
{
m_scale = scale;
}
public LabelStyle(Color color, float scale)
{
Color = color;
m_scale = scale;
}
public LabelStyle(Color color, float scale, ColorMode newColorMode)
{
Color = color;
m_scale = scale;
colorMode = newColorMode;
}
private float m_scale = 1.0f;
[XmlElement("scale")]
public float scale
{
get
{
return m_scale;
}
set
{
m_scale = value;
scaleSpecified = true;
}
}
[XmlIgnore()]
private bool scaleSpecified = false;
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Configuration;
using System.Web;
using System.Web.Configuration;
using System.Web.Hosting;
using System.Web.Routing;
using System.Web.Security;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Security;
namespace Umbraco.Core.Configuration
{
//NOTE: Do not expose this class ever until we cleanup all configuration including removal of static classes, etc...
// we have this two tasks logged:
// http://issues.umbraco.org/issue/U4-58
// http://issues.umbraco.org/issue/U4-115
//TODO: Replace checking for if the app settings exist and returning an empty string, instead return the defaults!
/// <summary>
/// The GlobalSettings Class contains general settings information for the entire Umbraco instance based on information from web.config appsettings
/// </summary>
internal class GlobalSettings
{
#region Private static fields
private static readonly object Locker = new object();
//make this volatile so that we can ensure thread safety with a double check lock
private static volatile string _reservedUrlsCache;
private static string _reservedPathsCache;
private static HashSet<string> _reservedList = new HashSet<string>();
private static string _reservedPaths;
private static string _reservedUrls;
//ensure the built on (non-changeable) reserved paths are there at all times
private const string StaticReservedPaths = "~/app_plugins/,~/install/,";
private const string StaticReservedUrls = "~/config/splashes/booting.aspx,~/config/splashes/noNodes.aspx,~/VSEnterpriseHelper.axd,";
#endregion
/// <summary>
/// Used in unit testing to reset all config items that were set with property setters (i.e. did not come from config)
/// </summary>
private static void ResetInternal()
{
_reservedUrlsCache = null;
_reservedPaths = null;
_reservedUrls = null;
HasSmtpServer = null;
}
/// <summary>
/// Resets settings that were set programmatically, to their initial values.
/// </summary>
/// <remarks>To be used in unit tests.</remarks>
internal static void Reset()
{
ResetInternal();
}
public static bool HasSmtpServerConfigured(string appPath)
{
if (HasSmtpServer.HasValue) return HasSmtpServer.Value;
var config = WebConfigurationManager.OpenWebConfiguration(appPath);
var settings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");
if (settings == null || settings.Smtp == null) return false;
if (settings.Smtp.SpecifiedPickupDirectory != null && string.IsNullOrEmpty(settings.Smtp.SpecifiedPickupDirectory.PickupDirectoryLocation) == false)
return true;
if (settings.Smtp.Network != null && string.IsNullOrEmpty(settings.Smtp.Network.Host) == false)
return true;
return false;
}
/// <summary>
/// For testing only
/// </summary>
internal static bool? HasSmtpServer { get; set; }
/// <summary>
/// Gets the reserved urls from web.config.
/// </summary>
/// <value>The reserved urls.</value>
public static string ReservedUrls
{
get
{
if (_reservedUrls == null)
{
var urls = ConfigurationManager.AppSettings.ContainsKey("umbracoReservedUrls")
? ConfigurationManager.AppSettings["umbracoReservedUrls"]
: string.Empty;
//ensure the built on (non-changeable) reserved paths are there at all times
_reservedUrls = StaticReservedUrls + urls;
}
return _reservedUrls;
}
internal set { _reservedUrls = value; }
}
/// <summary>
/// Gets the reserved paths from web.config
/// </summary>
/// <value>The reserved paths.</value>
public static string ReservedPaths
{
get
{
if (_reservedPaths == null)
{
var reservedPaths = StaticReservedPaths;
//always add the umbraco path to the list
if (ConfigurationManager.AppSettings.ContainsKey("umbracoPath")
&& !ConfigurationManager.AppSettings["umbracoPath"].IsNullOrWhiteSpace())
{
reservedPaths += ConfigurationManager.AppSettings["umbracoPath"].EnsureEndsWith(',');
}
var allPaths = ConfigurationManager.AppSettings.ContainsKey("umbracoReservedPaths")
? ConfigurationManager.AppSettings["umbracoReservedPaths"]
: string.Empty;
_reservedPaths = reservedPaths + allPaths;
}
return _reservedPaths;
}
internal set { _reservedPaths = value; }
}
/// <summary>
/// Gets the name of the content XML file.
/// </summary>
/// <value>The content XML.</value>
/// <remarks>
/// Defaults to ~/App_Data/umbraco.config
/// </remarks>
public static string ContentXmlFile
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoContentXML")
? ConfigurationManager.AppSettings["umbracoContentXML"]
: "~/App_Data/umbraco.config";
}
}
/// <summary>
/// Gets the path to the storage directory (/data by default).
/// </summary>
/// <value>The storage directory.</value>
public static string StorageDirectory
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoStorageDirectory")
? ConfigurationManager.AppSettings["umbracoStorageDirectory"]
: "~/App_Data";
}
}
/// <summary>
/// Gets the path to umbraco's root directory (/umbraco by default).
/// </summary>
/// <value>The path.</value>
public static string Path
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoPath")
? IOHelper.ResolveUrl(ConfigurationManager.AppSettings["umbracoPath"])
: string.Empty;
}
}
/// <summary>
/// This returns the string of the MVC Area route.
/// </summary>
/// <remarks>
/// THIS IS TEMPORARY AND SHOULD BE REMOVED WHEN WE MIGRATE/UPDATE THE CONFIG SETTINGS TO BE A REAL CONFIG SECTION
/// AND SHOULD PROBABLY BE HANDLED IN A MORE ROBUST WAY.
///
/// This will return the MVC area that we will route all custom routes through like surface controllers, etc...
/// We will use the 'Path' (default ~/umbraco) to create it but since it cannot contain '/' and people may specify a path of ~/asdf/asdf/admin
/// we will convert the '/' to '-' and use that as the path. its a bit lame but will work.
///
/// We also make sure that the virtual directory (SystemDirectories.Root) is stripped off first, otherwise we'd end up with something
/// like "MyVirtualDirectory-Umbraco" instead of just "Umbraco".
/// </remarks>
public static string UmbracoMvcArea
{
get
{
if (Path.IsNullOrWhiteSpace())
{
throw new InvalidOperationException("Cannot create an MVC Area path without the umbracoPath specified");
}
var path = Path;
if (path.StartsWith(SystemDirectories.Root)) // beware of TrimStart, see U4-2518
path = path.Substring(SystemDirectories.Root.Length);
return path.TrimStart('~').TrimStart('/').Replace('/', '-').Trim().ToLower();
}
}
/// <summary>
/// Gets the path to umbraco's client directory (/umbraco_client by default).
/// This is a relative path to the Umbraco Path as it always must exist beside the 'umbraco'
/// folder since the CSS paths to images depend on it.
/// </summary>
/// <value>The path.</value>
public static string ClientPath
{
get
{
return Path + "/../umbraco_client";
}
}
/// <summary>
/// Gets the database connection string
/// </summary>
/// <value>The database connection string.</value>
[Obsolete("Use System.Configuration.ConfigurationManager.ConnectionStrings[\"umbracoDbDSN\"] instead")]
public static string DbDsn
{
get
{
var settings = ConfigurationManager.ConnectionStrings[Constants.System.UmbracoConnectionName];
var connectionString = string.Empty;
if (settings != null)
{
connectionString = settings.ConnectionString;
// The SqlCe connectionString is formatted slightly differently, so we need to update it
if (settings.ProviderName.Contains("SqlServerCe"))
connectionString = string.Format("datalayer=SQLCE4Umbraco.SqlCEHelper,SQLCE4Umbraco;{0}", connectionString);
}
return connectionString;
}
set
{
if (DbDsn != value)
{
if (value.ToLower().Contains("SQLCE4Umbraco.SqlCEHelper".ToLower()))
{
ApplicationContext.Current.DatabaseContext.ConfigureEmbeddedDatabaseConnection();
}
else
{
ApplicationContext.Current.DatabaseContext.ConfigureDatabaseConnection(value);
}
}
}
}
/// <summary>
/// Gets or sets the configuration status. This will return the version number of the currently installed umbraco instance.
/// </summary>
/// <value>The configuration status.</value>
public static string ConfigurationStatus
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoConfigurationStatus")
? ConfigurationManager.AppSettings["umbracoConfigurationStatus"]
: string.Empty;
}
set
{
SaveSetting("umbracoConfigurationStatus", value);
}
}
/// <summary>
/// Gets or sets the Umbraco members membership providers' useLegacyEncoding state. This will return a boolean
/// </summary>
/// <value>The useLegacyEncoding status.</value>
public static bool UmbracoMembershipProviderLegacyEncoding
{
get
{
return IsConfiguredMembershipProviderUsingLegacyEncoding(Constants.Conventions.Member.UmbracoMemberProviderName);
}
set
{
SetMembershipProvidersLegacyEncoding(Constants.Conventions.Member.UmbracoMemberProviderName, value);
}
}
/// <summary>
/// Gets or sets the Umbraco users membership providers' useLegacyEncoding state. This will return a boolean
/// </summary>
/// <value>The useLegacyEncoding status.</value>
public static bool UmbracoUsersMembershipProviderLegacyEncoding
{
get
{
return IsConfiguredMembershipProviderUsingLegacyEncoding(UmbracoConfig.For.UmbracoSettings().Providers.DefaultBackOfficeUserProvider);
}
set
{
SetMembershipProvidersLegacyEncoding(UmbracoConfig.For.UmbracoSettings().Providers.DefaultBackOfficeUserProvider, value);
}
}
/// <summary>
/// Saves a setting into the configuration file.
/// </summary>
/// <param name="key">Key of the setting to be saved.</param>
/// <param name="value">Value of the setting to be saved.</param>
internal static void SaveSetting(string key, string value)
{
var fileName = IOHelper.MapPath(string.Format("{0}/web.config", SystemDirectories.Root));
var xml = XDocument.Load(fileName, LoadOptions.PreserveWhitespace);
var appSettings = xml.Root.DescendantsAndSelf("appSettings").Single();
// Update appSetting if it exists, or else create a new appSetting for the given key and value
var setting = appSettings.Descendants("add").FirstOrDefault(s => s.Attribute("key").Value == key);
if (setting == null)
appSettings.Add(new XElement("add", new XAttribute("key", key), new XAttribute("value", value)));
else
setting.Attribute("value").Value = value;
xml.Save(fileName, SaveOptions.DisableFormatting);
ConfigurationManager.RefreshSection("appSettings");
}
/// <summary>
/// Removes a setting from the configuration file.
/// </summary>
/// <param name="key">Key of the setting to be removed.</param>
internal static void RemoveSetting(string key)
{
var fileName = IOHelper.MapPath(string.Format("{0}/web.config", SystemDirectories.Root));
var xml = XDocument.Load(fileName, LoadOptions.PreserveWhitespace);
var appSettings = xml.Root.DescendantsAndSelf("appSettings").Single();
var setting = appSettings.Descendants("add").FirstOrDefault(s => s.Attribute("key").Value == key);
if (setting != null)
{
setting.Remove();
xml.Save(fileName, SaveOptions.DisableFormatting);
ConfigurationManager.RefreshSection("appSettings");
}
}
private static void SetMembershipProvidersLegacyEncoding(string providerName, bool useLegacyEncoding)
{
//check if this can even be configured.
var membershipProvider = Membership.Providers[providerName] as MembershipProviderBase;
if (membershipProvider == null)
{
return;
}
if (membershipProvider.GetType().Namespace == "umbraco.providers.members")
{
//its the legacy one, this cannot be changed
return;
}
var webConfigFilename = IOHelper.MapPath(string.Format("{0}/web.config", SystemDirectories.Root));
var webConfigXml = XDocument.Load(webConfigFilename, LoadOptions.PreserveWhitespace);
var membershipConfigs = webConfigXml.XPathSelectElements("configuration/system.web/membership/providers/add").ToList();
if (membershipConfigs.Any() == false)
return;
var provider = membershipConfigs.SingleOrDefault(c => c.Attribute("name") != null && c.Attribute("name").Value == providerName);
if (provider == null)
return;
provider.SetAttributeValue("useLegacyEncoding", useLegacyEncoding);
webConfigXml.Save(webConfigFilename, SaveOptions.DisableFormatting);
}
private static bool IsConfiguredMembershipProviderUsingLegacyEncoding(string providerName)
{
//check if this can even be configured.
var membershipProvider = Membership.Providers[providerName] as MembershipProviderBase;
if (membershipProvider == null)
{
return false;
}
return membershipProvider.UseLegacyEncoding;
}
/// <summary>
/// Gets the full path to root.
/// </summary>
/// <value>The fullpath to root.</value>
public static string FullpathToRoot
{
get { return IOHelper.GetRootDirectorySafe(); }
}
/// <summary>
/// Gets a value indicating whether umbraco is running in [debug mode].
/// </summary>
/// <value><c>true</c> if [debug mode]; otherwise, <c>false</c>.</value>
public static bool DebugMode
{
get
{
try
{
if (HttpContext.Current != null)
{
return HttpContext.Current.IsDebuggingEnabled;
}
//go and get it from config directly
var section = ConfigurationManager.GetSection("system.web/compilation") as CompilationSection;
return section != null && section.Debug;
}
catch
{
return false;
}
}
}
/// <summary>
/// Gets a value indicating whether the current version of umbraco is configured.
/// </summary>
/// <value><c>true</c> if configured; otherwise, <c>false</c>.</value>
[Obsolete("Do not use this, it is no longer in use and will be removed from the codebase in future versions")]
internal static bool Configured
{
get
{
try
{
string configStatus = ConfigurationStatus;
string currentVersion = UmbracoVersion.GetSemanticVersion().ToSemanticString();
if (currentVersion != configStatus)
{
LogHelper.Debug<GlobalSettings>("CurrentVersion different from configStatus: '" + currentVersion + "','" + configStatus + "'");
}
return (configStatus == currentVersion);
}
catch
{
return false;
}
}
}
/// <summary>
/// Gets the time out in minutes.
/// </summary>
/// <value>The time out in minutes.</value>
public static int TimeOutInMinutes
{
get
{
try
{
return int.Parse(ConfigurationManager.AppSettings["umbracoTimeOutInMinutes"]);
}
catch
{
return 20;
}
}
}
/// <summary>
/// Gets a value indicating whether umbraco uses directory urls.
/// </summary>
/// <value><c>true</c> if umbraco uses directory urls; otherwise, <c>false</c>.</value>
public static bool UseDirectoryUrls
{
get
{
try
{
return bool.Parse(ConfigurationManager.AppSettings["umbracoUseDirectoryUrls"]);
}
catch
{
return false;
}
}
}
/// <summary>
/// Returns the number of days that should take place between version checks.
/// </summary>
/// <value>The version check period in days (0 = never).</value>
public static int VersionCheckPeriod
{
get
{
try
{
return int.Parse(ConfigurationManager.AppSettings["umbracoVersionCheckPeriod"]);
}
catch
{
return 7;
}
}
}
/// <summary>
/// Returns a string value to determine if umbraco should disbable xslt extensions
/// </summary>
/// <value><c>"true"</c> if version xslt extensions are disabled, otherwise, <c>"false"</c></value>
[Obsolete("This is no longer used and will be removed from the codebase in future releases")]
public static string DisableXsltExtensions
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoDisableXsltExtensions")
? ConfigurationManager.AppSettings["umbracoDisableXsltExtensions"]
: "false";
}
}
internal static bool ContentCacheXmlStoredInCodeGen
{
get { return LocalTempStorageLocation == LocalTempStorage.AspNetTemp; }
}
/// <summary>
/// This is the location type to store temporary files such as cache files or other localized files for a given machine
/// </summary>
/// <remarks>
/// Currently used for the xml cache file and the plugin cache files
/// </remarks>
internal static LocalTempStorage LocalTempStorageLocation
{
get
{
//there's a bunch of backwards compat config checks here....
//This is the current one
if (ConfigurationManager.AppSettings.ContainsKey("umbracoLocalTempStorage"))
{
return Enum<LocalTempStorage>.Parse(ConfigurationManager.AppSettings["umbracoLocalTempStorage"]);
}
//This one is old
if (ConfigurationManager.AppSettings.ContainsKey("umbracoContentXMLStorage"))
{
return Enum<LocalTempStorage>.Parse(ConfigurationManager.AppSettings["umbracoContentXMLStorage"]);
}
//This one is older
if (ConfigurationManager.AppSettings.ContainsKey("umbracoContentXMLUseLocalTemp"))
{
return bool.Parse(ConfigurationManager.AppSettings["umbracoContentXMLUseLocalTemp"])
? LocalTempStorage.AspNetTemp
: LocalTempStorage.Default;
}
return LocalTempStorage.Default;
}
}
/// <summary>
/// Returns a string value to determine if umbraco should use Xhtml editing mode in the wysiwyg editor
/// </summary>
/// <value><c>"true"</c> if Xhtml mode is enable, otherwise, <c>"false"</c></value>
[Obsolete("This is no longer used and will be removed from the codebase in future releases")]
public static string EditXhtmlMode
{
get { return "true"; }
}
/// <summary>
/// Gets the default UI language.
/// </summary>
/// <value>The default UI language.</value>
public static string DefaultUILanguage
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoDefaultUILanguage")
? ConfigurationManager.AppSettings["umbracoDefaultUILanguage"]
: string.Empty;
}
}
/// <summary>
/// Gets the profile URL.
/// </summary>
/// <value>The profile URL.</value>
public static string ProfileUrl
{
get
{
//the default will be 'profiler'
return ConfigurationManager.AppSettings.ContainsKey("umbracoProfileUrl")
? ConfigurationManager.AppSettings["umbracoProfileUrl"]
: "profiler";
}
}
/// <summary>
/// Gets a value indicating whether umbraco should hide top level nodes from generated urls.
/// </summary>
/// <value>
/// <c>true</c> if umbraco hides top level nodes from urls; otherwise, <c>false</c>.
/// </value>
public static bool HideTopLevelNodeFromPath
{
get
{
try
{
return bool.Parse(ConfigurationManager.AppSettings["umbracoHideTopLevelNodeFromPath"]);
}
catch
{
return false;
}
}
}
/// <summary>
/// Gets the current version.
/// </summary>
/// <value>The current version.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static string CurrentVersion
{
get { return UmbracoVersion.GetSemanticVersion().ToSemanticString(); }
}
/// <summary>
/// Gets the major version number.
/// </summary>
/// <value>The major version number.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static int VersionMajor
{
get
{
return UmbracoVersion.Current.Major;
}
}
/// <summary>
/// Gets the minor version number.
/// </summary>
/// <value>The minor version number.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static int VersionMinor
{
get
{
return UmbracoVersion.Current.Minor;
}
}
/// <summary>
/// Gets the patch version number.
/// </summary>
/// <value>The patch version number.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static int VersionPatch
{
get
{
return UmbracoVersion.Current.Build;
}
}
/// <summary>
/// Gets the version comment (like beta or RC).
/// </summary>
/// <value>The version comment.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static string VersionComment
{
get
{
return Umbraco.Core.Configuration.UmbracoVersion.CurrentComment;
}
}
/// <summary>
/// Requests the is in umbraco application directory structure.
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
public static bool RequestIsInUmbracoApplication(HttpContext context)
{
return context.Request.Path.ToLower().IndexOf(IOHelper.ResolveUrl(SystemDirectories.Umbraco).ToLower()) > -1;
}
public static bool RequestIsInUmbracoApplication(HttpContextBase context)
{
return context.Request.Path.ToLower().IndexOf(IOHelper.ResolveUrl(SystemDirectories.Umbraco).ToLower()) > -1;
}
/// <summary>
/// Gets a value indicating whether umbraco should force a secure (https) connection to the backoffice.
/// </summary>
/// <value><c>true</c> if [use SSL]; otherwise, <c>false</c>.</value>
public static bool UseSSL
{
get
{
try
{
return bool.Parse(ConfigurationManager.AppSettings["umbracoUseSSL"]);
}
catch
{
return false;
}
}
}
/// <summary>
/// Gets the umbraco license.
/// </summary>
/// <value>The license.</value>
public static string License
{
get
{
string license =
"<A href=\"http://umbraco.org/redir/license\" target=\"_blank\">the open source license MIT</A>. The umbraco UI is freeware licensed under the umbraco license.";
var versionDoc = new XmlDocument();
var versionReader = new XmlTextReader(IOHelper.MapPath(SystemDirectories.Umbraco + "/version.xml"));
versionDoc.Load(versionReader);
versionReader.Close();
// check for license
try
{
string licenseUrl =
versionDoc.SelectSingleNode("/version/licensing/licenseUrl").FirstChild.Value;
string licenseValidation =
versionDoc.SelectSingleNode("/version/licensing/licenseValidation").FirstChild.Value;
string licensedTo =
versionDoc.SelectSingleNode("/version/licensing/licensedTo").FirstChild.Value;
if (licensedTo != "" && licenseUrl != "")
{
license = "umbraco Commercial License<br/><b>Registered to:</b><br/>" +
licensedTo.Replace("\n", "<br/>") + "<br/><b>For use with domain:</b><br/>" +
licenseUrl;
}
}
catch
{
}
return license;
}
}
/// <summary>
/// Determines whether the current request is reserved based on the route table and
/// whether the specified URL is reserved or is inside a reserved path.
/// </summary>
/// <param name="url"></param>
/// <param name="httpContext"></param>
/// <param name="routes">The route collection to lookup the request in</param>
/// <returns></returns>
public static bool IsReservedPathOrUrl(string url, HttpContextBase httpContext, RouteCollection routes)
{
if (httpContext == null) throw new ArgumentNullException("httpContext");
if (routes == null) throw new ArgumentNullException("routes");
//check if the current request matches a route, if so then it is reserved.
var route = routes.GetRouteData(httpContext);
if (route != null)
return true;
//continue with the standard ignore routine
return IsReservedPathOrUrl(url);
}
/// <summary>
/// Determines whether the specified URL is reserved or is inside a reserved path.
/// </summary>
/// <param name="url">The URL to check.</param>
/// <returns>
/// <c>true</c> if the specified URL is reserved; otherwise, <c>false</c>.
/// </returns>
public static bool IsReservedPathOrUrl(string url)
{
if (_reservedUrlsCache == null)
{
lock (Locker)
{
if (_reservedUrlsCache == null)
{
// store references to strings to determine changes
_reservedPathsCache = GlobalSettings.ReservedPaths;
_reservedUrlsCache = GlobalSettings.ReservedUrls;
// add URLs and paths to a new list
var newReservedList = new HashSet<string>();
foreach (var reservedUrlTrimmed in _reservedUrlsCache
.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Trim().ToLowerInvariant())
.Where(x => x.IsNullOrWhiteSpace() == false)
.Select(reservedUrl => IOHelper.ResolveUrl(reservedUrl).Trim().EnsureStartsWith("/"))
.Where(reservedUrlTrimmed => reservedUrlTrimmed.IsNullOrWhiteSpace() == false))
{
newReservedList.Add(reservedUrlTrimmed);
}
foreach (var reservedPathTrimmed in _reservedPathsCache
.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Trim().ToLowerInvariant())
.Where(x => x.IsNullOrWhiteSpace() == false)
.Select(reservedPath => IOHelper.ResolveUrl(reservedPath).Trim().EnsureStartsWith("/").EnsureEndsWith("/"))
.Where(reservedPathTrimmed => reservedPathTrimmed.IsNullOrWhiteSpace() == false))
{
newReservedList.Add(reservedPathTrimmed);
}
// use the new list from now on
_reservedList = newReservedList;
}
}
}
//The url should be cleaned up before checking:
// * If it doesn't contain an '.' in the path then we assume it is a path based URL, if that is the case we should add an trailing '/' because all of our reservedPaths use a trailing '/'
// * We shouldn't be comparing the query at all
var pathPart = url.Split(new[] {'?'}, StringSplitOptions.RemoveEmptyEntries)[0].ToLowerInvariant();
if (pathPart.Contains(".") == false)
{
pathPart = pathPart.EnsureEndsWith('/');
}
// return true if url starts with an element of the reserved list
return _reservedList.Any(x => pathPart.InvariantStartsWith(x));
}
}
}
| |
using ClosedXML.Excel;
using System;
namespace ClosedXML.Examples.Misc
{
public class Sorting : IXLExample
{
public void Create(String filePath)
{
using (var wb = new XLWorkbook())
{
#region Sort Table
var wsTable = wb.Worksheets.Add("Table");
AddTestTable(wsTable);
wsTable.Row(1).InsertRowsAbove(1);
Int32 lastCo = wsTable.LastColumnUsed().ColumnNumber();
for (Int32 co = 1; co <= lastCo; co++)
wsTable.Cell(1, co).Value = "Column" + co.ToString();
var table = wsTable.RangeUsed().AsTable();
table.Sort("Column2 Desc, 1, 3 Asc");
// Sort table another way
wsTable = wb.Worksheets.Add("Table2");
AddTestTable(wsTable);
wsTable.Row(1).InsertRowsAbove(1);
lastCo = wsTable.LastColumnUsed().ColumnNumber();
for (Int32 co = 1; co <= lastCo; co++)
wsTable.Cell(1, co).Value = "Column" + co.ToString();
table = wsTable.RangeUsed().AsTable();
table.Sort("Column2", XLSortOrder.Descending, false, true);
#endregion Sort Table
#region Sort Rows
var wsRows = wb.Worksheets.Add("Rows");
AddTestTable(wsRows);
wsRows.Row(1).Sort();
wsRows.RangeUsed().Row(2).Sort();
wsRows.Rows(3, wsRows.LastRowUsed().RowNumber()).Delete();
#endregion Sort Rows
#region Sort Columns
var wsColumns = wb.Worksheets.Add("Columns");
AddTestTable(wsColumns);
wsColumns.LastColumnUsed().Delete();
wsColumns.Column(1).Sort();
wsColumns.RangeUsed().Column(2).Sort();
#endregion Sort Columns
#region Sort Mixed
var wsMixed = wb.Worksheets.Add("Mixed");
AddTestColumnMixed(wsMixed);
wsMixed.Sort();
#endregion Sort Mixed
#region Sort Numbers
var wsNumbers = wb.Worksheets.Add("Numbers");
AddTestColumnNumbers(wsNumbers);
wsNumbers.Sort();
#endregion Sort Numbers
#region Sort TimeSpans
var wsTimeSpans = wb.Worksheets.Add("TimeSpans");
AddTestColumnTimeSpans(wsTimeSpans);
wsTimeSpans.Sort();
#endregion Sort TimeSpans
#region Sort Dates
var wsDates = wb.Worksheets.Add("Dates");
AddTestColumnDates(wsDates);
wsDates.Sort();
#endregion Sort Dates
#region Do Not Ignore Blanks
var wsIncludeBlanks = wb.Worksheets.Add("Include Blanks");
AddTestTable(wsIncludeBlanks);
var rangeIncludeBlanks = wsIncludeBlanks;
rangeIncludeBlanks.SortColumns.Add(1, XLSortOrder.Ascending, false, true);
rangeIncludeBlanks.SortColumns.Add(2, XLSortOrder.Descending, false, true);
rangeIncludeBlanks.Sort();
var wsIncludeBlanksColumn = wb.Worksheets.Add("Include Blanks Column");
AddTestColumn(wsIncludeBlanksColumn);
var rangeIncludeBlanksColumn = wsIncludeBlanksColumn;
rangeIncludeBlanksColumn.SortColumns.Add(1, XLSortOrder.Ascending, false, true);
rangeIncludeBlanksColumn.Sort();
var wsIncludeBlanksColumnDesc = wb.Worksheets.Add("Include Blanks Column Desc");
AddTestColumn(wsIncludeBlanksColumnDesc);
var rangeIncludeBlanksColumnDesc = wsIncludeBlanksColumnDesc;
rangeIncludeBlanksColumnDesc.SortColumns.Add(1, XLSortOrder.Descending, false, true);
rangeIncludeBlanksColumnDesc.Sort();
#endregion Do Not Ignore Blanks
#region Case Sensitive
var wsCaseSensitive = wb.Worksheets.Add("Case Sensitive");
AddTestTable(wsCaseSensitive);
var rangeCaseSensitive = wsCaseSensitive;
rangeCaseSensitive.SortColumns.Add(1, XLSortOrder.Ascending, true, true);
rangeCaseSensitive.SortColumns.Add(2, XLSortOrder.Descending, true, true);
rangeCaseSensitive.Sort();
var wsCaseSensitiveColumn = wb.Worksheets.Add("Case Sensitive Column");
AddTestColumn(wsCaseSensitiveColumn);
var rangeCaseSensitiveColumn = wsCaseSensitiveColumn;
rangeCaseSensitiveColumn.SortColumns.Add(1, XLSortOrder.Ascending, true, true);
rangeCaseSensitiveColumn.Sort();
var wsCaseSensitiveColumnDesc = wb.Worksheets.Add("Case Sensitive Column Desc");
AddTestColumn(wsCaseSensitiveColumnDesc);
var rangeCaseSensitiveColumnDesc = wsCaseSensitiveColumnDesc;
rangeCaseSensitiveColumnDesc.SortColumns.Add(1, XLSortOrder.Descending, true, true);
rangeCaseSensitiveColumnDesc.Sort();
#endregion Case Sensitive
#region Simple Sorts
var wsSimple = wb.Worksheets.Add("Simple");
AddTestTable(wsSimple);
wsSimple.Sort();
var wsSimpleDesc = wb.Worksheets.Add("Simple Desc");
AddTestTable(wsSimpleDesc);
wsSimpleDesc.Sort("", XLSortOrder.Descending);
var wsSimpleColumns = wb.Worksheets.Add("Simple Columns");
AddTestTable(wsSimpleColumns);
wsSimpleColumns.Sort("2, A DESC, 3");
var wsSimpleColumn = wb.Worksheets.Add("Simple Column");
AddTestColumn(wsSimpleColumn);
wsSimpleColumn.Sort();
var wsSimpleColumnDesc = wb.Worksheets.Add("Simple Column Desc");
AddTestColumn(wsSimpleColumnDesc);
wsSimpleColumnDesc.Sort(1, XLSortOrder.Descending);
#endregion Simple Sorts
wb.SaveAs(filePath);
}
}
private void AddTestColumnMixed(IXLWorksheet ws)
{
ws.Cell("A1").SetValue(new DateTime(2011, 1, 30)).Style.Fill.SetBackgroundColor(XLColor.LightGreen);
ws.Cell("A2").SetValue(1.15).Style.Fill.SetBackgroundColor(XLColor.DarkTurquoise);
ws.Cell("A3").SetValue(new TimeSpan(1, 1, 12, 30)).Style.Fill.SetBackgroundColor(XLColor.BurlyWood);
ws.Cell("A4").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkGray);
ws.Cell("A5").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkSalmon);
ws.Cell("A6").SetValue(9).Style.Fill.SetBackgroundColor(XLColor.DodgerBlue);
ws.Cell("A7").SetValue(new TimeSpan(9, 4, 30)).Style.Fill.SetBackgroundColor(XLColor.IndianRed);
ws.Cell("A8").SetValue(new DateTime(2011, 4, 15)).Style.Fill.SetBackgroundColor(XLColor.DeepPink);
}
private void AddTestColumnNumbers(IXLWorksheet ws)
{
ws.Cell("A1").SetValue(1.30).Style.Fill.SetBackgroundColor(XLColor.LightGreen);
ws.Cell("A2").SetValue(1.15).Style.Fill.SetBackgroundColor(XLColor.DarkTurquoise);
ws.Cell("A3").SetValue(1230).Style.Fill.SetBackgroundColor(XLColor.BurlyWood);
ws.Cell("A4").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkGray);
ws.Cell("A5").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkSalmon);
ws.Cell("A6").SetValue(9).Style.Fill.SetBackgroundColor(XLColor.DodgerBlue);
ws.Cell("A7").SetValue(4.30).Style.Fill.SetBackgroundColor(XLColor.IndianRed);
ws.Cell("A8").SetValue(4.15).Style.Fill.SetBackgroundColor(XLColor.DeepPink);
}
private void AddTestColumnTimeSpans(IXLWorksheet ws)
{
ws.Cell("A1").SetValue(new TimeSpan(0, 12, 35, 21)).Style.Fill.SetBackgroundColor(XLColor.LightGreen);
ws.Cell("A2").SetValue(new TimeSpan(45, 1, 15)).Style.Fill.SetBackgroundColor(XLColor.DarkTurquoise);
ws.Cell("A3").SetValue(new TimeSpan(1, 1, 12, 30)).Style.Fill.SetBackgroundColor(XLColor.BurlyWood);
ws.Cell("A4").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkGray);
ws.Cell("A5").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkSalmon);
ws.Cell("A6").SetValue(new TimeSpan(0, 12, 15)).Style.Fill.SetBackgroundColor(XLColor.DodgerBlue);
ws.Cell("A7").SetValue(new TimeSpan(1, 4, 30)).Style.Fill.SetBackgroundColor(XLColor.IndianRed);
ws.Cell("A8").SetValue(new TimeSpan(1, 4, 15)).Style.Fill.SetBackgroundColor(XLColor.DeepPink);
}
private void AddTestColumnDates(IXLWorksheet ws)
{
ws.Cell("A1").SetValue(new DateTime(2011, 1, 30)).Style.Fill.SetBackgroundColor(XLColor.LightGreen);
ws.Cell("A2").SetValue(new DateTime(2011, 1, 15)).Style.Fill.SetBackgroundColor(XLColor.DarkTurquoise);
ws.Cell("A3").SetValue(new DateTime(2011, 12, 30)).Style.Fill.SetBackgroundColor(XLColor.BurlyWood);
ws.Cell("A4").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkGray);
ws.Cell("A5").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkSalmon);
ws.Cell("A6").SetValue(new DateTime(2011, 12, 15)).Style.Fill.SetBackgroundColor(XLColor.DodgerBlue);
ws.Cell("A7").SetValue(new DateTime(2011, 4, 30)).Style.Fill.SetBackgroundColor(XLColor.IndianRed);
ws.Cell("A8").SetValue(new DateTime(2011, 4, 15)).Style.Fill.SetBackgroundColor(XLColor.DeepPink);
}
private void AddTestColumn(IXLWorksheet ws)
{
ws.Cell("A1").SetValue("B").Style.Fill.SetBackgroundColor(XLColor.LightGreen);
ws.Cell("A2").SetValue("A").Style.Fill.SetBackgroundColor(XLColor.DarkTurquoise);
ws.Cell("A3").SetValue("a").Style.Fill.SetBackgroundColor(XLColor.BurlyWood);
ws.Cell("A4").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkGray);
ws.Cell("A5").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkSalmon);
ws.Cell("A6").SetValue("b").Style.Fill.SetBackgroundColor(XLColor.DodgerBlue);
ws.Cell("A7").SetValue("B").Style.Fill.SetBackgroundColor(XLColor.IndianRed);
ws.Cell("A8").SetValue("c").Style.Fill.SetBackgroundColor(XLColor.DeepPink);
}
private void AddTestTable(IXLWorksheet ws)
{
ws.Cell("A1").SetValue("B").Style.Fill.SetBackgroundColor(XLColor.LightGreen);
ws.Cell("A2").SetValue("A").Style.Fill.SetBackgroundColor(XLColor.DarkTurquoise);
ws.Cell("A3").SetValue("a").Style.Fill.SetBackgroundColor(XLColor.BurlyWood);
ws.Cell("A4").SetValue("A").Style.Fill.SetBackgroundColor(XLColor.DarkGray);
ws.Cell("A5").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkSalmon);
ws.Cell("A6").SetValue("A").Style.Fill.SetBackgroundColor(XLColor.DodgerBlue);
ws.Cell("A7").SetValue("a").Style.Fill.SetBackgroundColor(XLColor.IndianRed);
ws.Cell("A8").SetValue("B").Style.Fill.SetBackgroundColor(XLColor.DeepPink);
ws.Cell("B1").SetValue("").Style.Fill.SetBackgroundColor(XLColor.LightGreen);
ws.Cell("B2").SetValue("a").Style.Fill.SetBackgroundColor(XLColor.DarkTurquoise);
ws.Cell("B3").SetValue("B").Style.Fill.SetBackgroundColor(XLColor.BurlyWood);
ws.Cell("B4").SetValue("A").Style.Fill.SetBackgroundColor(XLColor.DarkGray);
ws.Cell("B5").SetValue("a").Style.Fill.SetBackgroundColor(XLColor.DarkSalmon);
ws.Cell("B6").SetValue("A").Style.Fill.SetBackgroundColor(XLColor.DodgerBlue);
ws.Cell("B7").SetValue("a").Style.Fill.SetBackgroundColor(XLColor.IndianRed);
ws.Cell("B8").SetValue("a").Style.Fill.SetBackgroundColor(XLColor.DeepPink);
ws.Cell("C1").SetValue("A").Style.Fill.SetBackgroundColor(XLColor.LightGreen);
ws.Cell("C2").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkTurquoise);
ws.Cell("C3").SetValue("A").Style.Fill.SetBackgroundColor(XLColor.BurlyWood);
ws.Cell("C4").SetValue("a").Style.Fill.SetBackgroundColor(XLColor.DarkGray);
ws.Cell("C5").SetValue("A").Style.Fill.SetBackgroundColor(XLColor.DarkSalmon);
ws.Cell("C6").SetValue("b").Style.Fill.SetBackgroundColor(XLColor.DodgerBlue);
ws.Cell("C7").SetValue("A").Style.Fill.SetBackgroundColor(XLColor.IndianRed);
ws.Cell("C8").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DeepPink);
}
}
}
| |
// 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;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
//
// Property Default Description
// PositiveSign '+' Character used to indicate positive values.
// NegativeSign '-' Character used to indicate negative values.
// NumberDecimalSeparator '.' The character used as the decimal separator.
// NumberGroupSeparator ',' The character used to separate groups of
// digits to the left of the decimal point.
// NumberDecimalDigits 2 The default number of decimal places.
// NumberGroupSizes 3 The number of digits in each group to the
// left of the decimal point.
// NaNSymbol "NaN" The string used to represent NaN values.
// PositiveInfinitySymbol"Infinity" The string used to represent positive
// infinities.
// NegativeInfinitySymbol"-Infinity" The string used to represent negative
// infinities.
//
//
//
// Property Default Description
// CurrencyDecimalSeparator '.' The character used as the decimal
// separator.
// CurrencyGroupSeparator ',' The character used to separate groups
// of digits to the left of the decimal
// point.
// CurrencyDecimalDigits 2 The default number of decimal places.
// CurrencyGroupSizes 3 The number of digits in each group to
// the left of the decimal point.
// CurrencyPositivePattern 0 The format of positive values.
// CurrencyNegativePattern 0 The format of negative values.
// CurrencySymbol "$" String used as local monetary symbol.
//
[System.Runtime.InteropServices.ComVisible(true)]
sealed public class NumberFormatInfo : IFormatProvider
{
// invariantInfo is constant irrespective of your current culture.
private static volatile NumberFormatInfo s_invariantInfo;
// READTHIS READTHIS READTHIS
// This class has an exact mapping onto a native structure defined in COMNumber.cpp
// DO NOT UPDATE THIS WITHOUT UPDATING THAT STRUCTURE. IF YOU ADD BOOL, ADD THEM AT THE END.
// ALSO MAKE SURE TO UPDATE mscorlib.h in the VM directory to check field offsets.
// READTHIS READTHIS READTHIS
internal int[] numberGroupSizes = new int[] { 3 };
internal int[] currencyGroupSizes = new int[] { 3 };
internal int[] percentGroupSizes = new int[] { 3 };
internal String positiveSign = "+";
internal String negativeSign = "-";
internal String numberDecimalSeparator = ".";
internal String numberGroupSeparator = ",";
internal String currencyGroupSeparator = ",";
internal String currencyDecimalSeparator = ".";
internal String currencySymbol = "\x00a4"; // U+00a4 is the symbol for International Monetary Fund.
internal String nanSymbol = "NaN";
internal String positiveInfinitySymbol = "Infinity";
internal String negativeInfinitySymbol = "-Infinity";
internal String percentDecimalSeparator = ".";
internal String percentGroupSeparator = ",";
internal String percentSymbol = "%";
internal String perMilleSymbol = "\u2030";
internal String[] nativeDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
internal int numberDecimalDigits = 2;
internal int currencyDecimalDigits = 2;
internal int currencyPositivePattern = 0;
internal int currencyNegativePattern = 0;
internal int numberNegativePattern = 1;
internal int percentPositivePattern = 0;
internal int percentNegativePattern = 0;
internal int percentDecimalDigits = 2;
internal bool isReadOnly = false;
// Is this NumberFormatInfo for invariant culture?
internal bool m_isInvariant = false;
public NumberFormatInfo() : this(null)
{
}
static private void VerifyDecimalSeparator(String decSep, String propertyName)
{
if (decSep == null)
{
throw new ArgumentNullException(propertyName,
SR.ArgumentNull_String);
}
if (decSep.Length == 0)
{
throw new ArgumentException(SR.Argument_EmptyDecString);
}
Contract.EndContractBlock();
}
static private void VerifyGroupSeparator(String groupSep, String propertyName)
{
if (groupSep == null)
{
throw new ArgumentNullException(propertyName,
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
}
internal NumberFormatInfo(CultureData cultureData)
{
if (cultureData != null)
{
// We directly use fields here since these data is coming from data table or Win32, so we
// don't need to verify their values (except for invalid parsing situations).
cultureData.GetNFIValues(this);
if (cultureData.IsInvariantCulture)
{
// For invariant culture
this.m_isInvariant = true;
}
}
}
[Pure]
private void VerifyWritable()
{
if (isReadOnly)
{
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
Contract.EndContractBlock();
}
// Returns a default NumberFormatInfo that will be universally
// supported and constant irrespective of the current culture.
// Used by FromString methods.
//
public static NumberFormatInfo InvariantInfo
{
get
{
if (s_invariantInfo == null)
{
// Lazy create the invariant info. This cannot be done in a .cctor because exceptions can
// be thrown out of a .cctor stack that will need this.
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.m_isInvariant = true;
s_invariantInfo = ReadOnly(nfi);
}
return s_invariantInfo;
}
}
public static NumberFormatInfo GetInstance(IFormatProvider formatProvider)
{
// Fast case for a regular CultureInfo
NumberFormatInfo info;
CultureInfo cultureProvider = formatProvider as CultureInfo;
if (cultureProvider != null && !cultureProvider.m_isInherited)
{
info = cultureProvider.numInfo;
if (info != null)
{
return info;
}
else
{
return cultureProvider.NumberFormat;
}
}
// Fast case for an NFI;
info = formatProvider as NumberFormatInfo;
if (info != null)
{
return info;
}
if (formatProvider != null)
{
info = formatProvider.GetFormat(typeof(NumberFormatInfo)) as NumberFormatInfo;
if (info != null)
{
return info;
}
}
return CurrentInfo;
}
public Object Clone()
{
NumberFormatInfo n = (NumberFormatInfo)MemberwiseClone();
n.isReadOnly = false;
return n;
}
public int CurrencyDecimalDigits
{
get { return currencyDecimalDigits; }
set
{
if (value < 0 || value > 99)
{
throw new ArgumentOutOfRangeException(
"CurrencyDecimalDigits",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
99));
}
Contract.EndContractBlock();
VerifyWritable();
currencyDecimalDigits = value;
}
}
public String CurrencyDecimalSeparator
{
get { return currencyDecimalSeparator; }
set
{
VerifyWritable();
VerifyDecimalSeparator(value, "CurrencyDecimalSeparator");
currencyDecimalSeparator = value;
}
}
public bool IsReadOnly
{
get
{
return isReadOnly;
}
}
//
// Check the values of the groupSize array.
//
// Every element in the groupSize array should be between 1 and 9
// excpet the last element could be zero.
//
static internal void CheckGroupSize(String propName, int[] groupSize)
{
for (int i = 0; i < groupSize.Length; i++)
{
if (groupSize[i] < 1)
{
if (i == groupSize.Length - 1 && groupSize[i] == 0)
return;
throw new ArgumentException(SR.Argument_InvalidGroupSize, propName);
}
else if (groupSize[i] > 9)
{
throw new ArgumentException(SR.Argument_InvalidGroupSize, propName);
}
}
}
public int[] CurrencyGroupSizes
{
get
{
return ((int[])currencyGroupSizes.Clone());
}
set
{
if (value == null)
{
throw new ArgumentNullException("CurrencyGroupSizes",
SR.ArgumentNull_Obj);
}
Contract.EndContractBlock();
VerifyWritable();
Int32[] inputSizes = (Int32[])value.Clone();
CheckGroupSize("CurrencyGroupSizes", inputSizes);
currencyGroupSizes = inputSizes;
}
}
public int[] NumberGroupSizes
{
get
{
return ((int[])numberGroupSizes.Clone());
}
set
{
if (value == null)
{
throw new ArgumentNullException("NumberGroupSizes",
SR.ArgumentNull_Obj);
}
Contract.EndContractBlock();
VerifyWritable();
Int32[] inputSizes = (Int32[])value.Clone();
CheckGroupSize("NumberGroupSizes", inputSizes);
numberGroupSizes = inputSizes;
}
}
public int[] PercentGroupSizes
{
get
{
return ((int[])percentGroupSizes.Clone());
}
set
{
if (value == null)
{
throw new ArgumentNullException("PercentGroupSizes",
SR.ArgumentNull_Obj);
}
Contract.EndContractBlock();
VerifyWritable();
Int32[] inputSizes = (Int32[])value.Clone();
CheckGroupSize("PercentGroupSizes", inputSizes);
percentGroupSizes = inputSizes;
}
}
public String CurrencyGroupSeparator
{
get { return currencyGroupSeparator; }
set
{
VerifyWritable();
VerifyGroupSeparator(value, "CurrencyGroupSeparator");
currencyGroupSeparator = value;
}
}
public String CurrencySymbol
{
get { return currencySymbol; }
set
{
if (value == null)
{
throw new ArgumentNullException("CurrencySymbol",
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
currencySymbol = value;
}
}
// Returns the current culture's NumberFormatInfo. Used by Parse methods.
//
public static NumberFormatInfo CurrentInfo
{
get
{
System.Globalization.CultureInfo culture = CultureInfo.CurrentCulture;
if (!culture.m_isInherited)
{
NumberFormatInfo info = culture.numInfo;
if (info != null)
{
return info;
}
}
return ((NumberFormatInfo)culture.GetFormat(typeof(NumberFormatInfo)));
}
}
public String NaNSymbol
{
get
{
return nanSymbol;
}
set
{
if (value == null)
{
throw new ArgumentNullException("NaNSymbol",
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
nanSymbol = value;
}
}
public int CurrencyNegativePattern
{
get { return currencyNegativePattern; }
set
{
if (value < 0 || value > 15)
{
throw new ArgumentOutOfRangeException(
"CurrencyNegativePattern",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
15));
}
Contract.EndContractBlock();
VerifyWritable();
currencyNegativePattern = value;
}
}
public int NumberNegativePattern
{
get { return numberNegativePattern; }
set
{
//
// NOTENOTE: the range of value should correspond to negNumberFormats[] in vm\COMNumber.cpp.
//
if (value < 0 || value > 4)
{
throw new ArgumentOutOfRangeException(
"NumberNegativePattern",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
4));
}
Contract.EndContractBlock();
VerifyWritable();
numberNegativePattern = value;
}
}
public int PercentPositivePattern
{
get { return percentPositivePattern; }
set
{
//
// NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp.
//
if (value < 0 || value > 3)
{
throw new ArgumentOutOfRangeException(
"PercentPositivePattern",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
3));
}
Contract.EndContractBlock();
VerifyWritable();
percentPositivePattern = value;
}
}
public int PercentNegativePattern
{
get { return percentNegativePattern; }
set
{
//
// NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp.
//
if (value < 0 || value > 11)
{
throw new ArgumentOutOfRangeException(
"PercentNegativePattern",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
11));
}
Contract.EndContractBlock();
VerifyWritable();
percentNegativePattern = value;
}
}
public String NegativeInfinitySymbol
{
get
{
return negativeInfinitySymbol;
}
set
{
if (value == null)
{
throw new ArgumentNullException("NegativeInfinitySymbol",
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
negativeInfinitySymbol = value;
}
}
public String NegativeSign
{
get { return negativeSign; }
set
{
if (value == null)
{
throw new ArgumentNullException("NegativeSign",
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
negativeSign = value;
}
}
public int NumberDecimalDigits
{
get { return numberDecimalDigits; }
set
{
if (value < 0 || value > 99)
{
throw new ArgumentOutOfRangeException(
"NumberDecimalDigits",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
99));
}
Contract.EndContractBlock();
VerifyWritable();
numberDecimalDigits = value;
}
}
public String NumberDecimalSeparator
{
get { return numberDecimalSeparator; }
set
{
VerifyWritable();
VerifyDecimalSeparator(value, "NumberDecimalSeparator");
numberDecimalSeparator = value;
}
}
public String NumberGroupSeparator
{
get { return numberGroupSeparator; }
set
{
VerifyWritable();
VerifyGroupSeparator(value, "NumberGroupSeparator");
numberGroupSeparator = value;
}
}
public int CurrencyPositivePattern
{
get { return currencyPositivePattern; }
set
{
if (value < 0 || value > 3)
{
throw new ArgumentOutOfRangeException(
"CurrencyPositivePattern",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
3));
}
Contract.EndContractBlock();
VerifyWritable();
currencyPositivePattern = value;
}
}
public String PositiveInfinitySymbol
{
get
{
return positiveInfinitySymbol;
}
set
{
if (value == null)
{
throw new ArgumentNullException("PositiveInfinitySymbol",
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
positiveInfinitySymbol = value;
}
}
public String PositiveSign
{
get { return positiveSign; }
set
{
if (value == null)
{
throw new ArgumentNullException("PositiveSign",
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
positiveSign = value;
}
}
public int PercentDecimalDigits
{
get { return percentDecimalDigits; }
set
{
if (value < 0 || value > 99)
{
throw new ArgumentOutOfRangeException(
"PercentDecimalDigits",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
99));
}
Contract.EndContractBlock();
VerifyWritable();
percentDecimalDigits = value;
}
}
public String PercentDecimalSeparator
{
get { return percentDecimalSeparator; }
set
{
VerifyWritable();
VerifyDecimalSeparator(value, "PercentDecimalSeparator");
percentDecimalSeparator = value;
}
}
public String PercentGroupSeparator
{
get { return percentGroupSeparator; }
set
{
VerifyWritable();
VerifyGroupSeparator(value, "PercentGroupSeparator");
percentGroupSeparator = value;
}
}
public String PercentSymbol
{
get
{
return percentSymbol;
}
set
{
if (value == null)
{
throw new ArgumentNullException("PercentSymbol",
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
percentSymbol = value;
}
}
public String PerMilleSymbol
{
get { return perMilleSymbol; }
set
{
if (value == null)
{
throw new ArgumentNullException("PerMilleSymbol",
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
perMilleSymbol = value;
}
}
public Object GetFormat(Type formatType)
{
return formatType == typeof(NumberFormatInfo) ? this : null;
}
public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi)
{
if (nfi == null)
{
throw new ArgumentNullException("nfi");
}
Contract.EndContractBlock();
if (nfi.IsReadOnly)
{
return (nfi);
}
NumberFormatInfo info = (NumberFormatInfo)(nfi.MemberwiseClone());
info.isReadOnly = true;
return info;
}
// private const NumberStyles InvalidNumberStyles = unchecked((NumberStyles) 0xFFFFFC00);
private const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite
| NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign
| NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint
| NumberStyles.AllowThousands | NumberStyles.AllowExponent
| NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier);
internal static void ValidateParseStyleInteger(NumberStyles style)
{
// Check for undefined flags
if ((style & InvalidNumberStyles) != 0)
{
throw new ArgumentException(SR.Argument_InvalidNumberStyles, "style");
}
Contract.EndContractBlock();
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // Check for hex number
if ((style & ~NumberStyles.HexNumber) != 0)
{
throw new ArgumentException(SR.Arg_InvalidHexStyle);
}
}
}
internal static void ValidateParseStyleFloatingPoint(NumberStyles style)
{
// Check for undefined flags
if ((style & InvalidNumberStyles) != 0)
{
throw new ArgumentException(SR.Argument_InvalidNumberStyles, "style");
}
Contract.EndContractBlock();
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // Check for hex number
throw new ArgumentException(SR.Arg_HexStyleNotSupported);
}
}
} // NumberFormatInfo
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using OrchardCore.Environment.Extensions.Features;
using OrchardCore.Environment.Extensions.Manifests;
using OrchardCore.Environment.Extensions.Utility;
using OrchardCore.Modules;
namespace OrchardCore.Environment.Extensions
{
public class ExtensionManager : IExtensionManager
{
private readonly IApplicationContext _applicationContext;
private readonly IEnumerable<IExtensionDependencyStrategy> _extensionDependencyStrategies;
private readonly IEnumerable<IExtensionPriorityStrategy> _extensionPriorityStrategies;
private readonly ITypeFeatureProvider _typeFeatureProvider;
private readonly IFeaturesProvider _featuresProvider;
private IDictionary<string, ExtensionEntry> _extensions;
private IEnumerable<IExtensionInfo> _extensionsInfos;
private IDictionary<string, FeatureEntry> _features;
private IFeatureInfo[] _featureInfos;
private readonly ConcurrentDictionary<string, Lazy<IEnumerable<IFeatureInfo>>> _featureDependencies
= new ConcurrentDictionary<string, Lazy<IEnumerable<IFeatureInfo>>>();
private readonly ConcurrentDictionary<string, Lazy<IEnumerable<IFeatureInfo>>> _dependentFeatures
= new ConcurrentDictionary<string, Lazy<IEnumerable<IFeatureInfo>>>();
private static readonly Func<IFeatureInfo, IFeatureInfo[], IFeatureInfo[]> GetDependentFeaturesFunc =
new Func<IFeatureInfo, IFeatureInfo[], IFeatureInfo[]>(
(currentFeature, fs) => fs
.Where(f => f.Dependencies.Any(dep => dep == currentFeature.Id))
.ToArray());
private static readonly Func<IFeatureInfo, IFeatureInfo[], IFeatureInfo[]> GetFeatureDependenciesFunc =
new Func<IFeatureInfo, IFeatureInfo[], IFeatureInfo[]>(
(currentFeature, fs) => fs
.Where(f => currentFeature.Dependencies.Any(dep => dep == f.Id))
.ToArray());
private bool _isInitialized = false;
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1);
public ExtensionManager(
IApplicationContext applicationContext,
IEnumerable<IExtensionDependencyStrategy> extensionDependencyStrategies,
IEnumerable<IExtensionPriorityStrategy> extensionPriorityStrategies,
ITypeFeatureProvider typeFeatureProvider,
IFeaturesProvider featuresProvider,
ILogger<ExtensionManager> logger)
{
_applicationContext = applicationContext;
_extensionDependencyStrategies = extensionDependencyStrategies;
_extensionPriorityStrategies = extensionPriorityStrategies;
_typeFeatureProvider = typeFeatureProvider;
_featuresProvider = featuresProvider;
L = logger;
}
public ILogger L { get; set; }
public IExtensionInfo GetExtension(string extensionId)
{
EnsureInitialized();
ExtensionEntry extension;
if (!String.IsNullOrEmpty(extensionId) && _extensions.TryGetValue(extensionId, out extension))
{
return extension.ExtensionInfo;
}
return new NotFoundExtensionInfo(extensionId);
}
public IEnumerable<IExtensionInfo> GetExtensions()
{
EnsureInitialized();
return _extensionsInfos;
}
public IEnumerable<IFeatureInfo> GetFeatures(string[] featureIdsToLoad)
{
EnsureInitialized();
var allDependencies = featureIdsToLoad
.SelectMany(featureId => GetFeatureDependencies(featureId))
.Distinct();
return _featureInfos
.Where(f => allDependencies.Any(d => d.Id == f.Id));
}
public Task<ExtensionEntry> LoadExtensionAsync(IExtensionInfo extensionInfo)
{
EnsureInitialized();
ExtensionEntry extension;
if (_extensions.TryGetValue(extensionInfo.Id, out extension))
{
return Task.FromResult(extension);
}
return Task.FromResult<ExtensionEntry>(null);
}
public async Task<IEnumerable<FeatureEntry>> LoadFeaturesAsync()
{
await EnsureInitializedAsync();
return _features.Values;
}
public async Task<IEnumerable<FeatureEntry>> LoadFeaturesAsync(string[] featureIdsToLoad)
{
await EnsureInitializedAsync();
var features = GetFeatures(featureIdsToLoad).Select(f => f.Id).ToList();
var loadedFeatures = _features.Values
.Where(f => features.Contains(f.FeatureInfo.Id));
return loadedFeatures;
}
public IEnumerable<IFeatureInfo> GetFeatureDependencies(string featureId)
{
EnsureInitialized();
return _featureDependencies.GetOrAdd(featureId, (key) => new Lazy<IEnumerable<IFeatureInfo>>(() =>
{
if (!_features.ContainsKey(key))
{
return Enumerable.Empty<IFeatureInfo>();
}
var feature = _features[key].FeatureInfo;
return GetFeatureDependencies(feature, _featureInfos);
})).Value;
}
public IEnumerable<IFeatureInfo> GetDependentFeatures(string featureId)
{
EnsureInitialized();
return _dependentFeatures.GetOrAdd(featureId, (key) => new Lazy<IEnumerable<IFeatureInfo>>(() =>
{
if (!_features.ContainsKey(key))
{
return Enumerable.Empty<IFeatureInfo>();
}
var feature = _features[key].FeatureInfo;
return GetDependentFeatures(feature, _featureInfos);
})).Value;
}
private IEnumerable<IFeatureInfo> GetFeatureDependencies(
IFeatureInfo feature,
IFeatureInfo[] features)
{
var dependencies = new HashSet<IFeatureInfo>() { feature };
var stack = new Stack<IFeatureInfo[]>();
stack.Push(GetFeatureDependenciesFunc(feature, features));
while (stack.Count > 0)
{
var next = stack.Pop();
foreach (var dependency in next.Where(dependency => !dependencies.Contains(dependency)))
{
dependencies.Add(dependency);
stack.Push(GetFeatureDependenciesFunc(dependency, features));
}
}
// Preserve the underlying order of feature infos.
return _featureInfos.Where(f => dependencies.Any(d => d.Id == f.Id));
}
private IEnumerable<IFeatureInfo> GetDependentFeatures(
IFeatureInfo feature,
IFeatureInfo[] features)
{
var dependencies = new HashSet<IFeatureInfo>() { feature };
var stack = new Stack<IFeatureInfo[]>();
stack.Push(GetDependentFeaturesFunc(feature, features));
while (stack.Count > 0)
{
var next = stack.Pop();
foreach (var dependency in next.Where(dependency => !dependencies.Contains(dependency)))
{
dependencies.Add(dependency);
stack.Push(GetDependentFeaturesFunc(dependency, features));
}
}
// Preserve the underlying order of feature infos.
return _featureInfos.Where(f => dependencies.Any(d => d.Id == f.Id));
}
public IEnumerable<IFeatureInfo> GetFeatures()
{
EnsureInitialized();
return _featureInfos;
}
private static string GetSourceFeatureNameForType(Type type, string extensionId)
{
var attribute = type.GetCustomAttributes<FeatureAttribute>(false).FirstOrDefault();
return attribute?.FeatureName ?? extensionId;
}
private void EnsureInitialized()
{
if (_isInitialized)
{
return;
}
EnsureInitializedAsync().GetAwaiter().GetResult();
}
private async Task EnsureInitializedAsync()
{
if (_isInitialized)
{
return;
}
await _semaphore.WaitAsync();
try
{
if (_isInitialized)
{
return;
}
var modules = _applicationContext.Application.Modules;
var loadedExtensions = new ConcurrentDictionary<string, ExtensionEntry>();
// Load all extensions in parallel
await modules.ForEachAsync((module) =>
{
if (!module.ModuleInfo.Exists)
{
return Task.CompletedTask;
}
var manifestInfo = new ManifestInfo(module.ModuleInfo);
var extensionInfo = new ExtensionInfo(module.SubPath, manifestInfo, (mi, ei) =>
{
return _featuresProvider.GetFeatures(ei, mi);
});
var entry = new ExtensionEntry
{
ExtensionInfo = extensionInfo,
Assembly = module.Assembly,
ExportedTypes = module.Assembly.ExportedTypes
};
loadedExtensions.TryAdd(module.Name, entry);
return Task.CompletedTask;
});
var loadedFeatures = new Dictionary<string, FeatureEntry>();
// Get all valid types from any extension
var allTypesByExtension = loadedExtensions.SelectMany(extension =>
extension.Value.ExportedTypes.Where(IsComponentType)
.Select(type => new
{
ExtensionEntry = extension.Value,
Type = type
})).ToArray();
var typesByFeature = allTypesByExtension
.GroupBy(typeByExtension => GetSourceFeatureNameForType(
typeByExtension.Type,
typeByExtension.ExtensionEntry.ExtensionInfo.Id))
.ToDictionary(
group => group.Key,
group => group.Select(typesByExtension => typesByExtension.Type).ToArray());
foreach (var loadedExtension in loadedExtensions)
{
var extension = loadedExtension.Value;
foreach (var feature in extension.ExtensionInfo.Features)
{
// Features can have no types
if (typesByFeature.TryGetValue(feature.Id, out var featureTypes))
{
foreach (var type in featureTypes)
{
_typeFeatureProvider.TryAdd(type, feature);
}
}
else
{
featureTypes = Array.Empty<Type>();
}
loadedFeatures.Add(feature.Id, new FeatureEntry(feature, featureTypes));
}
};
// Feature infos and entries are ordered by priority and dependencies.
_featureInfos = Order(loadedFeatures.Values.Select(f => f.FeatureInfo));
_features = _featureInfos.ToDictionary(f => f.Id, f => loadedFeatures[f.Id]);
// Extensions are also ordered according to the weight of their first features.
_extensionsInfos = _featureInfos.Where(f => f.Id == f.Extension.Features.First().Id)
.Select(f => f.Extension);
_extensions = _extensionsInfos.ToDictionary(e => e.Id, e => loadedExtensions[e.Id]);
_isInitialized = true;
}
finally
{
_semaphore.Release();
}
}
private bool IsComponentType(Type type)
{
return type.IsClass && !type.IsAbstract && type.IsPublic;
}
private IFeatureInfo[] Order(IEnumerable<IFeatureInfo> featuresToOrder)
{
return featuresToOrder
.OrderBy(x => x.Id)
.OrderByDependenciesAndPriorities(HasDependency, GetPriority)
.ToArray();
}
private bool HasDependency(IFeatureInfo f1, IFeatureInfo f2)
{
return _extensionDependencyStrategies.Any(s => s.HasDependency(f1, f2));
}
private int GetPriority(IFeatureInfo feature)
{
return _extensionPriorityStrategies.Sum(s => s.GetPriority(feature));
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using NServiceKit.Text.Common;
using System.Reflection;
namespace NServiceKit.Text
{
/// <summary>A CSV configuration.</summary>
public static class CsvConfig
{
/// <summary>Initializes static members of the NServiceKit.Text.CsvConfig class.</summary>
static CsvConfig()
{
Reset();
}
/// <summary>The ts item seperator string.</summary>
[ThreadStatic]
private static string tsItemSeperatorString;
/// <summary>The item seperator string.</summary>
private static string sItemSeperatorString;
/// <summary>Gets or sets the item seperator string.</summary>
/// <value>The item seperator string.</value>
public static string ItemSeperatorString
{
get
{
return tsItemSeperatorString ?? sItemSeperatorString ?? JsWriter.ItemSeperatorString;
}
set
{
tsItemSeperatorString = value;
if (sItemSeperatorString == null) sItemSeperatorString = value;
ResetEscapeStrings();
}
}
/// <summary>The ts item delimiter string.</summary>
[ThreadStatic]
private static string tsItemDelimiterString;
/// <summary>The item delimiter string.</summary>
private static string sItemDelimiterString;
/// <summary>Gets or sets the item delimiter string.</summary>
/// <value>The item delimiter string.</value>
public static string ItemDelimiterString
{
get
{
return tsItemDelimiterString ?? sItemDelimiterString ?? JsWriter.QuoteString;
}
set
{
tsItemDelimiterString = value;
if (sItemDelimiterString == null) sItemDelimiterString = value;
EscapedItemDelimiterString = value + value;
ResetEscapeStrings();
}
}
/// <summary>The default escaped item delimiter string.</summary>
private const string DefaultEscapedItemDelimiterString = JsWriter.QuoteString + JsWriter.QuoteString;
/// <summary>The ts escaped item delimiter string.</summary>
[ThreadStatic]
private static string tsEscapedItemDelimiterString;
/// <summary>The escaped item delimiter string.</summary>
private static string sEscapedItemDelimiterString;
/// <summary>Gets or sets the escaped item delimiter string.</summary>
/// <value>The escaped item delimiter string.</value>
internal static string EscapedItemDelimiterString
{
get
{
return tsEscapedItemDelimiterString ?? sEscapedItemDelimiterString ?? DefaultEscapedItemDelimiterString;
}
set
{
tsEscapedItemDelimiterString = value;
if (sEscapedItemDelimiterString == null) sEscapedItemDelimiterString = value;
}
}
/// <summary>The default escape strings.</summary>
private static readonly string[] defaultEscapeStrings = GetEscapeStrings();
/// <summary>The ts escape strings.</summary>
[ThreadStatic]
private static string[] tsEscapeStrings;
/// <summary>The escape strings.</summary>
private static string[] sEscapeStrings;
/// <summary>Gets the escape strings.</summary>
/// <value>The escape strings.</value>
public static string[] EscapeStrings
{
get
{
return tsEscapeStrings ?? sEscapeStrings ?? defaultEscapeStrings;
}
private set
{
tsEscapeStrings = value;
if (sEscapeStrings == null) sEscapeStrings = value;
}
}
/// <summary>Gets escape strings.</summary>
/// <returns>An array of string.</returns>
private static string[] GetEscapeStrings()
{
return new[] {ItemDelimiterString, ItemSeperatorString, RowSeparatorString, "\r", "\n"};
}
/// <summary>Resets the escape strings.</summary>
private static void ResetEscapeStrings()
{
EscapeStrings = GetEscapeStrings();
}
/// <summary>The ts row separator string.</summary>
[ThreadStatic]
private static string tsRowSeparatorString;
/// <summary>The row separator string.</summary>
private static string sRowSeparatorString;
/// <summary>Gets or sets the row separator string.</summary>
/// <value>The row separator string.</value>
public static string RowSeparatorString
{
get
{
return tsRowSeparatorString ?? sRowSeparatorString ?? Environment.NewLine;
}
set
{
tsRowSeparatorString = value;
if (sRowSeparatorString == null) sRowSeparatorString = value;
ResetEscapeStrings();
}
}
/// <summary>Resets this object.</summary>
public static void Reset()
{
tsItemSeperatorString = sItemSeperatorString = null;
tsItemDelimiterString = sItemDelimiterString = null;
tsEscapedItemDelimiterString = sEscapedItemDelimiterString = null;
tsRowSeparatorString = sRowSeparatorString = null;
tsEscapeStrings = sEscapeStrings = null;
}
}
/// <summary>A CSV configuration.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
public static class CsvConfig<T>
{
/// <summary>Gets or sets a value indicating whether the omit headers.</summary>
/// <value>true if omit headers, false if not.</value>
public static bool OmitHeaders { get; set; }
/// <summary>The custom headers map.</summary>
private static Dictionary<string, string> customHeadersMap;
/// <summary>Gets or sets the custom headers map.</summary>
/// <value>The custom headers map.</value>
public static Dictionary<string, string> CustomHeadersMap
{
get
{
return customHeadersMap;
}
set
{
customHeadersMap = value;
if (value == null) return;
CsvWriter<T>.ConfigureCustomHeaders(customHeadersMap);
}
}
/// <summary>Sets the custom headers.</summary>
/// <exception cref="ArgumentException">Thrown when one or more arguments have unsupported or
/// illegal values.</exception>
/// <value>The custom headers.</value>
public static object CustomHeaders
{
set
{
if (value == null) return;
if (value.GetType().IsValueType())
throw new ArgumentException("CustomHeaders is a ValueType");
var propertyInfos = value.GetType().GetPropertyInfos();
if (propertyInfos.Length == 0) return;
customHeadersMap = new Dictionary<string, string>();
foreach (var pi in propertyInfos)
{
var getMethod = pi.GetMethodInfo();
if (getMethod == null) continue;
var oValue = getMethod.Invoke(value, new object[0]);
if (oValue == null) continue;
customHeadersMap[pi.Name] = oValue.ToString();
}
CsvWriter<T>.ConfigureCustomHeaders(customHeadersMap);
}
}
/// <summary>Resets this object.</summary>
public static void Reset()
{
OmitHeaders = false;
CsvWriter<T>.Reset();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
namespace Synergy.Contracts
{
static partial class Fail
{
// TODO:mace (from:mace @ 22-10-2016) public static void IfCollectionDoesNotContain<T>([CanBeNull, AssertionCondition(AssertionConditionType.IS_NOT_NULL)] IEnumerable<T> collection,)
#region Fail.IfCollectionEmpty()
/// <summary>
/// Throws exception when the collection is <see langword="null" /> or empty.
/// </summary>
/// <param name="collection">Collection to check against being <see langword="null" /> or empty.</param>
/// <param name="collectionName">Name of the collection.</param>
[AssertionMethod]
[ContractAnnotation("collection: null => halt")]
public static void IfCollectionEmpty(
[CanBeNull, AssertionCondition(AssertionConditionType.IS_NOT_NULL)]
IEnumerable collection,
[NotNull] [System.Diagnostics.CodeAnalysis.NotNull] string collectionName
)
{
collection.OrFailIfCollectionEmpty(collectionName);
}
/// <summary>
/// Throws exception when the collection is <see langword="null" /> or empty.
/// </summary>
/// <param name="collection">Collection to check against being <see langword="null" /> or empty.</param>
/// <param name="message">Message that will be passed to <see cref="DesignByContractViolationException"/> when the check fails.</param>
[AssertionMethod]
[ContractAnnotation("collection: null => halt")]
public static void IfCollectionEmpty(
[CanBeNull, AssertionCondition(AssertionConditionType.IS_NOT_NULL)]
IEnumerable collection,
Violation message
)
{
collection.OrFailIfCollectionEmpty(message);
}
#endregion
#region variable.OrFailIfCollectionEmpty()
/// <summary>
/// Throws exception when the collection is <see langword="null" /> or empty.
/// </summary>
/// <typeparam name="T">Type of the collection</typeparam>
/// <param name="collection">Collection to be checked against emptiness</param>
/// <param name="collectionName">Collection name</param>
/// <returns>The same collection as provided</returns>
[NotNull] [return: System.Diagnostics.CodeAnalysis.NotNull]
[AssertionMethod]
[ContractAnnotation("collection: null => halt")]
public static T OrFailIfCollectionEmpty<T>(
[CanBeNull, AssertionCondition(AssertionConditionType.IS_NOT_NULL)]
this T collection,
[NotNull] [System.Diagnostics.CodeAnalysis.NotNull] string collectionName
)
where T : IEnumerable
{
Fail.RequiresCollectionName(collectionName);
if (collection == null)
throw Fail.Because(Violation.WhenCollectionIsNull(collectionName));
if (collection.IsEmpty())
throw Fail.Because(Violation.WhenCollectionIsEmpty(collectionName));
return collection;
}
/// <summary>
/// Throws exception when the collection is <see langword="null" /> or empty.
/// </summary>
/// <typeparam name="T">Type of the collection</typeparam>
/// <param name="collection">Collection to be checked against emptiness</param>
/// <param name="message">Collection name</param>
/// <returns>The same collection as provided</returns>
[NotNull] [return: System.Diagnostics.CodeAnalysis.NotNull]
[AssertionMethod]
[ContractAnnotation("collection: null => halt")]
public static T OrFailIfCollectionEmpty<T>(
[CanBeNull, AssertionCondition(AssertionConditionType.IS_NOT_NULL)]
this T collection,
Violation message
)
where T : IEnumerable
{
if (collection == null)
throw Fail.Because(message);
if (collection.IsEmpty())
throw Fail.Because(message);
return collection;
}
[MustUseReturnValue]
private static bool IsEmpty([NotNull] [System.Diagnostics.CodeAnalysis.NotNull] this IEnumerable source)
{
if (source is ICollection collection)
return collection.Count == 0;
return source.GetEnumerator()
.MoveNext() == false;
}
#endregion
#region Fail.IfCollectionContainsNull()
/// <summary>
/// Throws exception when the collection contains null.
/// <para>REMARKS: The provided collection CANNOT by <see langword="null"/> as it will throw the exception.</para>
/// </summary>
/// <typeparam name="T">Type of the collection element.</typeparam>
/// <param name="collection">Collection to investigate whether contains null.</param>
/// <param name="collectionName">Name of the collection</param>
[AssertionMethod]
[ContractAnnotation("collection: null => halt")]
public static void IfCollectionContainsNull<T>(
[CanBeNull, AssertionCondition(AssertionConditionType.IS_NOT_NULL)]
IEnumerable<T> collection,
[NotNull] [System.Diagnostics.CodeAnalysis.NotNull] string collectionName
)
where T : class
{
Fail.RequiresCollectionName(collectionName);
if (collection == null)
throw Fail.Because(Violation.WhenCollectionIsNull(collectionName));
if (collection.Contains(null))
throw Fail.Because(Violation.WhenCollectionContainsNull(collectionName));
}
#endregion
#region Fail.IfCollectionContains()
/// <summary>
/// Throws the exception when collection contains element meeting specified criteria.
/// <para>REMARKS: The provided collection CANNOT by <see langword="null"/> as it will throw the exception.</para>
/// </summary>
/// <typeparam name="T">Type of the collection element.</typeparam>
/// <param name="collection">Collection to investigate whether contains specific element.</param>
/// <param name="func">Function with criteria that at least one element must meet.</param>
/// <param name="message">Message that will be passed to <see cref="DesignByContractViolationException"/> when the check fails.</param>
[AssertionMethod]
[ContractAnnotation("collection: null => halt")]
public static void IfCollectionContains<T>(
[CanBeNull, AssertionCondition(AssertionConditionType.IS_NOT_NULL)]
IEnumerable<T> collection,
[NotNull] [System.Diagnostics.CodeAnalysis.NotNull] Func<T, bool> func,
Violation message
)
{
Fail.IfArgumentNull(collection, nameof(collection));
T element = collection.FirstOrDefault(func);
Fail.IfNotNull(element, message);
}
#endregion
#region Fail.IfCollectionsAreNotEquivalent()
/// <summary>
/// Throws exception when the specified collections are not equivalent. Equivalent collection contain the same elements in any order.
/// <para>REMARKS: The provided collection CANNOT by <see langword="null"/> as it will throw the exception.</para>
/// </summary>
/// <typeparam name="T">Type of the collection element.</typeparam>
/// <param name="collection1">First collection to compare.</param>
/// <param name="collection2">Second collection to compare.</param>
/// <param name="message">Message that will be passed to <see cref="DesignByContractViolationException"/> when the check fails.</param>
[AssertionMethod]
[ContractAnnotation("collection1: null => halt; collection2: null => halt")]
public static void IfCollectionsAreNotEquivalent<T>(
[CanBeNull, AssertionCondition(AssertionConditionType.IS_NOT_NULL)]
IEnumerable<T> collection1,
[CanBeNull, AssertionCondition(AssertionConditionType.IS_NOT_NULL)]
IEnumerable<T> collection2,
Violation message
)
{
Fail.IfArgumentNull(collection1, nameof(collection1));
Fail.IfArgumentNull(collection2, nameof(collection2));
IEnumerable<T> list1 = collection1 as IList<T> ?? collection1.ToList();
IEnumerable<T> list2 = collection2 as IList<T> ?? collection2.ToList();
int collection1Count = list1.Count();
int collection2Count = list2.Count();
if (collection1Count != collection2Count)
throw Fail.Because(message);
bool areEquivalent = list1.Intersect(list2)
.Count() == collection1Count;
Fail.IfFalse(areEquivalent, message);
}
#endregion
/// <summary>
/// Checks if collection name was provided.
/// </summary>
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
private static void RequiresCollectionName([NotNull] [System.Diagnostics.CodeAnalysis.NotNull] string collectionName)
{
if (string.IsNullOrWhiteSpace(collectionName))
throw new ArgumentNullException(nameof(collectionName));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.AppService.Fluent
{
using Microsoft.Azure.Management.AppService.Fluent.Models;
using Microsoft.Azure.Management.AppService.Fluent.AppServiceDomain.Definition;
using Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition;
internal partial class DomainContactImpl
{
Models.Contact DomainContact.Definition.IWithAttach<AppServiceDomain.Definition.IWithCreate>.Build
{
get
{
return this.Build();
}
}
DomainContact.Definition.IWithAttach<AppServiceDomain.Definition.IWithCreate> DomainContact.Definition.IWithJobTitle<AppServiceDomain.Definition.IWithCreate>.WithJobTitle(string jobTitle)
{
return this.WithJobTitle(jobTitle);
}
/// <summary>
/// Specifies the city of the address.
/// </summary>
/// <param name="city">The city of the address.</param>
/// <return>The next stage of the definition.</return>
DomainContact.Definition.IWithStateOrProvince<AppServiceDomain.Definition.IWithCreate> DomainContact.Definition.IWithCity<AppServiceDomain.Definition.IWithCreate>.WithCity(string city)
{
return this.WithCity(city);
}
/// <summary>
/// Gets contact's mailing address.
/// </summary>
Models.Address Microsoft.Azure.Management.AppService.Fluent.IDomainContact.AddressMailing
{
get
{
return this.AddressMailing();
}
}
/// <summary>
/// Gets contact's phone number.
/// </summary>
string Microsoft.Azure.Management.AppService.Fluent.IDomainContact.Phone
{
get
{
return this.Phone();
}
}
/// <summary>
/// Gets contact's fax number.
/// </summary>
string Microsoft.Azure.Management.AppService.Fluent.IDomainContact.Fax
{
get
{
return this.Fax();
}
}
/// <summary>
/// Gets contact's last name.
/// </summary>
string Microsoft.Azure.Management.AppService.Fluent.IDomainContact.LastName
{
get
{
return this.LastName();
}
}
/// <summary>
/// Gets contact's email address.
/// </summary>
string Microsoft.Azure.Management.AppService.Fluent.IDomainContact.Email
{
get
{
return this.Email();
}
}
/// <summary>
/// Gets contact's job title.
/// </summary>
string Microsoft.Azure.Management.AppService.Fluent.IDomainContact.JobTitle
{
get
{
return this.JobTitle();
}
}
/// <summary>
/// Gets contact's organization.
/// </summary>
string Microsoft.Azure.Management.AppService.Fluent.IDomainContact.Organization
{
get
{
return this.Organization();
}
}
/// <summary>
/// Gets contact's middle name.
/// </summary>
string Microsoft.Azure.Management.AppService.Fluent.IDomainContact.MiddleName
{
get
{
return this.MiddleName();
}
}
/// <summary>
/// Gets contact's first name.
/// </summary>
string Microsoft.Azure.Management.AppService.Fluent.IDomainContact.FirstName
{
get
{
return this.FirstName();
}
}
/// <summary>
/// Specifies the postal code or zip code of the address.
/// </summary>
/// <param name="postalCode">The postal code of the address.</param>
/// <return>The next stage of the definition.</return>
DomainContact.Definition.IWithPhoneCountryCode<AppServiceDomain.Definition.IWithCreate> DomainContact.Definition.IWithPostalCode<AppServiceDomain.Definition.IWithCreate>.WithPostalCode(string postalCode)
{
return this.WithPostalCode(postalCode);
}
/// <summary>
/// Specifies the 1st line of the address.
/// </summary>
/// <param name="addressLine1">The 1st line of the address.</param>
/// <return>The next stage of the definition.</return>
DomainContact.Definition.IWithAddressLine2<AppServiceDomain.Definition.IWithCreate> DomainContact.Definition.IWithAddressLine1<AppServiceDomain.Definition.IWithCreate>.WithAddressLine1(string addressLine1)
{
return this.WithAddressLine1(addressLine1);
}
DomainContact.Definition.IWithAttach<AppServiceDomain.Definition.IWithCreate> DomainContact.Definition.IWithFaxNumber<AppServiceDomain.Definition.IWithCreate>.WithFaxNumber(string faxNumber)
{
return this.WithFaxNumber(faxNumber);
}
/// <summary>
/// Attaches the child definition to the parent resource definiton.
/// </summary>
/// <return>The next stage of the parent definition.</return>
AppServiceDomain.Definition.IWithCreate Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition.IInDefinition<AppServiceDomain.Definition.IWithCreate>.Attach()
{
return this.Attach();
}
/// <summary>
/// Specifies the 2nd line of the address.
/// </summary>
/// <param name="addressLine2">The 2nd line of the address.</param>
/// <return>The next stage of the definition.</return>
DomainContact.Definition.IWithCity<AppServiceDomain.Definition.IWithCreate> DomainContact.Definition.IWithAddressLine2<AppServiceDomain.Definition.IWithCreate>.WithAddressLine2(string addressLine2)
{
return this.WithAddressLine2(addressLine2);
}
/// <summary>
/// Specifies the country of the address.
/// </summary>
/// <param name="country">The country of the address.</param>
/// <return>The next stage of the definition.</return>
DomainContact.Definition.IWithPostalCode<AppServiceDomain.Definition.IWithCreate> DomainContact.Definition.IWithCountry<AppServiceDomain.Definition.IWithCreate>.WithCountry(CountryISOCode country)
{
return this.WithCountry(country);
}
/// <summary>
/// Specifies the email.
/// </summary>
/// <param name="email">Contact's email address.</param>
/// <return>The next stage of the definition.</return>
DomainContact.Definition.IWithAddressLine1<AppServiceDomain.Definition.IWithCreate> DomainContact.Definition.IWithEmail<AppServiceDomain.Definition.IWithCreate>.WithEmail(string email)
{
return this.WithEmail(email);
}
/// <summary>
/// Specifies the last name.
/// </summary>
/// <param name="lastName">The last name.</param>
/// <return>The next stage of the definition.</return>
DomainContact.Definition.IWithEmail<AppServiceDomain.Definition.IWithCreate> DomainContact.Definition.IWithLastName<AppServiceDomain.Definition.IWithCreate>.WithLastName(string lastName)
{
return this.WithLastName(lastName);
}
DomainContact.Definition.IWithAttach<AppServiceDomain.Definition.IWithCreate> DomainContact.Definition.IWithOrganization<AppServiceDomain.Definition.IWithCreate>.WithOrganization(string organziation)
{
return this.WithOrganization(organziation);
}
/// <summary>
/// Specifies the first name.
/// </summary>
/// <param name="firstName">The first name.</param>
/// <return>The next stage of the definition.</return>
DomainContact.Definition.IWithMiddleName<AppServiceDomain.Definition.IWithCreate> DomainContact.Definition.IWithFirstName<AppServiceDomain.Definition.IWithCreate>.WithFirstName(string firstName)
{
return this.WithFirstName(firstName);
}
/// <summary>
/// Specifies the country code of the phone number.
/// </summary>
/// <param name="code">The country code.</param>
/// <return>The next stage of the definition.</return>
DomainContact.Definition.IWithPhoneNumber<AppServiceDomain.Definition.IWithCreate> DomainContact.Definition.IWithPhoneCountryCode<AppServiceDomain.Definition.IWithCreate>.WithPhoneCountryCode(CountryPhoneCode code)
{
return this.WithPhoneCountryCode(code);
}
/// <summary>
/// Specifies the middle name.
/// </summary>
/// <param name="middleName">The middle name.</param>
/// <return>The next stage of the definition.</return>
DomainContact.Definition.IWithLastName<AppServiceDomain.Definition.IWithCreate> DomainContact.Definition.IWithMiddleName<AppServiceDomain.Definition.IWithCreate>.WithMiddleName(string middleName)
{
return this.WithMiddleName(middleName);
}
/// <summary>
/// Gets the name of the resource.
/// </summary>
string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasName.Name
{
get
{
return this.Name();
}
}
/// <summary>
/// Specifies the phone number.
/// </summary>
/// <param name="phoneNumber">Phone number.</param>
/// <return>The next stage of the definition.</return>
DomainContact.Definition.IWithAttach<AppServiceDomain.Definition.IWithCreate> DomainContact.Definition.IWithPhoneNumber<AppServiceDomain.Definition.IWithCreate>.WithPhoneNumber(string phoneNumber)
{
return this.WithPhoneNumber(phoneNumber);
}
/// <summary>
/// Specifies the state or province of the address.
/// </summary>
/// <param name="stateOrProvince">The state or province of the address.</param>
/// <return>The next stage of the definition.</return>
DomainContact.Definition.IWithCountry<AppServiceDomain.Definition.IWithCreate> DomainContact.Definition.IWithStateOrProvince<AppServiceDomain.Definition.IWithCreate>.WithStateOrProvince(string stateOrProvince)
{
return this.WithStateOrProvince(stateOrProvince);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Xunit;
namespace System.Tests
{
public static class CharTests
{
[Theory]
[InlineData('h', 'h', 0)]
[InlineData('h', 'a', 1)]
[InlineData('h', 'z', -1)]
[InlineData('h', null, 1)]
public static void CompareTo(char c, object value, int expected)
{
if (value is char)
{
Assert.Equal(expected, Math.Sign(c.CompareTo((char)value)));
}
IComparable comparable = c;
Assert.Equal(expected, Math.Sign(comparable.CompareTo(value)));
}
[Fact]
public static void CompareTo_ObjectNotChar_ThrowsArgumentException()
{
IComparable comparable = 'h';
Assert.Throws<ArgumentException>(null, () => comparable.CompareTo("H")); // Value not a char
}
public static IEnumerable<object[]> ConvertFromUtf32_TestData()
{
yield return new object[] { 0x10000, "\uD800\uDC00" };
yield return new object[] { 0x103FF, "\uD800\uDFFF" };
yield return new object[] { 0xFFFFF, "\uDBBF\uDFFF" };
yield return new object[] { 0x10FC00, "\uDBFF\uDC00" };
yield return new object[] { 0x10FFFF, "\uDBFF\uDFFF" };
yield return new object[] { 0, "\0" };
yield return new object[] { 0x3FF, "\u03FF" };
yield return new object[] { 0xE000, "\uE000" };
yield return new object[] { 0xFFFF, "\uFFFF" };
}
[Theory]
[MemberData(nameof(ConvertFromUtf32_TestData))]
public static void ConvertFromUtf32(int utf32, string expected)
{
Assert.Equal(expected, char.ConvertFromUtf32(utf32));
}
[Theory]
[InlineData(0xD800)]
[InlineData(0xDC00)]
[InlineData(0xDFFF)]
[InlineData(0x110000)]
[InlineData(-1)]
[InlineData(int.MaxValue)]
[InlineData(int.MinValue)]
public static void ConvertFromUtf32_InvalidUtf32_ThrowsArgumentOutOfRangeException(int utf32)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("utf32", () => char.ConvertFromUtf32(utf32));
}
public static IEnumerable<object[]> ConvertToUtf32_String_Int_TestData()
{
yield return new object[] { "\uD800\uDC00", 0, 0x10000 };
yield return new object[] { "\uDBBF\uDFFF", 0, 0xFFFFF };
yield return new object[] { "\uDBBF\uDFFF", 0, 0xFFFFF };
yield return new object[] { "\uDBFF\uDC00", 0, 0x10FC00 };
yield return new object[] { "\uDBFF\uDFFF", 0, 0x10FFFF };
yield return new object[] { "\u0000\u0001", 0, 0 };
yield return new object[] { "\u0000\u0001", 1, 1 };
yield return new object[] { "\u0000", 0, 0 };
yield return new object[] { "\u0020\uD7FF", 0, 32 };
yield return new object[] { "\u0020\uD7FF", 1, 0xD7FF };
yield return new object[] { "abcde", 4, 'e' };
// Invalid unicode
yield return new object[] { "\uD800\uD800\uDFFF", 1, 0x103FF };
yield return new object[] { "\uD800\uD7FF", 1, 0xD7FF }; // High, non-surrogate
yield return new object[] { "\uD800\u0000", 1, 0 }; // High, non-surrogate
yield return new object[] { "\uDF01\u0000", 1, 0 }; // Low, non-surrogate
}
[Theory]
[MemberData(nameof(ConvertToUtf32_String_Int_TestData))]
public static void ConvertToUtf32_String_Int(string s, int index, int expected)
{
Assert.Equal(expected, char.ConvertToUtf32(s, index));
}
[Fact]
public static void ConvertToUtf32_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.ConvertToUtf32(null, 0)); // String is null
AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\uD800", 0)); // High, high
AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\uD800", 1)); // High, high
AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\uD7FF", 0)); // High, non-surrogate
AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\u0000", 0)); // High, non-surrogate
AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDC01\uD940", 0)); // Low, high
AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDC01\uD940", 1)); // Low, high
AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDD00\uDE00", 0)); // Low, low
AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDD00\uDE00", 1)); // Low, hig
AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDF01\u0000", 0)); // Low, non-surrogateh
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.ConvertToUtf32("abcde", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.ConvertToUtf32("abcde", 5)); // Index >= string.Length
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.ConvertToUtf32("", 0)); // Index >= string.Length
}
public static IEnumerable<object[]> ConvertToUtf32_Char_Char_TestData()
{
yield return new object[] { '\uD800', '\uDC00', 0x10000 };
yield return new object[] { '\uD800', '\uDC00', 0x10000 };
yield return new object[] { '\uD800', '\uDFFF', 0x103FF };
yield return new object[] { '\uDBBF', '\uDFFF', 0xFFFFF };
yield return new object[] { '\uDBFF', '\uDC00', 0x10FC00 };
yield return new object[] { '\uDBFF', '\uDFFF', 0x10FFFF };
}
[Theory]
[MemberData(nameof(ConvertToUtf32_Char_Char_TestData))]
public static void ConvertToUtf32_Char_Char(char highSurrogate, char lowSurrogate, int expected)
{
Assert.Equal(expected, char.ConvertToUtf32(highSurrogate, lowSurrogate));
}
[Fact]
public static void ConvertToUtf32_Char_Char_Invalid()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("lowSurrogate", () => char.ConvertToUtf32('\uD800', '\uD800')); // High, high
AssertExtensions.Throws<ArgumentOutOfRangeException>("lowSurrogate", () => char.ConvertToUtf32('\uD800', '\uD7FF')); // High, non-surrogate
AssertExtensions.Throws<ArgumentOutOfRangeException>("lowSurrogate", () => char.ConvertToUtf32('\uD800', '\u0000')); // High, non-surrogate
AssertExtensions.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\uDD00', '\uDE00')); // Low, low
AssertExtensions.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\uDC01', '\uD940')); // Low, high
AssertExtensions.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\uDF01', '\u0000')); // Low, non-surrogate
AssertExtensions.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\u0032', '\uD7FF')); // Non-surrogate, non-surrogate
AssertExtensions.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\u0000', '\u0000')); // Non-surrogate, non-surrogate
}
[Theory]
[InlineData('a', 'a', true)]
[InlineData('a', 'A', false)]
[InlineData('a', 'b', false)]
[InlineData('a', (int)'a', false)]
[InlineData('a', "a", false)]
[InlineData('a', null, false)]
public static void Equals(char c, object obj, bool expected)
{
if (obj is char)
{
Assert.Equal(expected, c.Equals((char)obj));
Assert.Equal(expected, c.GetHashCode().Equals(obj.GetHashCode()));
}
Assert.Equal(expected, c.Equals(obj));
}
[Theory]
[InlineData('0', 0)]
[InlineData('9', 9)]
[InlineData('T', -1)]
public static void GetNumericValue_Char(char c, int expected)
{
Assert.Equal(expected, char.GetNumericValue(c));
}
[Theory]
[InlineData("\uD800\uDD07", 0, 1)]
[InlineData("9", 0, 9)]
[InlineData("99", 1, 9)]
[InlineData(" 7 ", 1, 7)]
[InlineData("Test 7", 5, 7)]
[InlineData("T", 0, -1)]
public static void GetNumericValue_String_Int(string s, int index, int expected)
{
Assert.Equal(expected, char.GetNumericValue(s, index));
}
[Fact]
public static void GetNumericValue_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.GetNumericValue(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.GetNumericValue("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.GetNumericValue("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsControl_Char()
{
foreach (char c in GetTestChars(UnicodeCategory.Control))
Assert.True(char.IsControl(c));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.Control))
Assert.False(char.IsControl(c));
}
[Fact]
public static void IsControl_String_Int()
{
foreach (char c in GetTestChars(UnicodeCategory.Control))
Assert.True(char.IsControl(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.Control))
Assert.False(char.IsControl(c.ToString(), 0));
}
[Fact]
public static void IsControl_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsControl(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsControl("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsControl("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsDigit_Char()
{
foreach (char c in GetTestChars(UnicodeCategory.DecimalDigitNumber))
Assert.True(char.IsDigit(c));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber))
Assert.False(char.IsDigit(c));
}
[Fact]
public static void IsDigit_String_Int()
{
foreach (char c in GetTestChars(UnicodeCategory.DecimalDigitNumber))
Assert.True(char.IsDigit(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber))
Assert.False(char.IsDigit(c.ToString(), 0));
}
[Fact]
public static void IsDigit_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsDigit(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsDigit("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsDigit("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsLetter_Char()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsLetter(c));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsLetter(c));
}
[Fact]
public static void IsLetter_String_Int()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsLetter(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsLetter(c.ToString(), 0));
}
[Fact]
public static void IsLetter_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsLetter(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetter("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetter("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsLetterOrDigit_Char()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter,
UnicodeCategory.DecimalDigitNumber
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsLetterOrDigit(c));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsLetterOrDigit(c));
}
[Fact]
public static void IsLetterOrDigit_String_Int()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter,
UnicodeCategory.DecimalDigitNumber
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsLetterOrDigit(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsLetterOrDigit(c.ToString(), 0));
}
[Fact]
public static void IsLetterOrDigit_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsLetterOrDigit(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetterOrDigit("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetterOrDigit("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsLower_Char()
{
foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter))
Assert.True(char.IsLower(c));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter))
Assert.False(char.IsLower(c));
}
[Fact]
public static void IsLower_String_Int()
{
foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter))
Assert.True(char.IsLower(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter))
Assert.False(char.IsLower(c.ToString(), 0));
}
[Fact]
public static void IsLower_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsLower(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLower("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLower("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsNumber_Char()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.DecimalDigitNumber,
UnicodeCategory.LetterNumber,
UnicodeCategory.OtherNumber
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsNumber(c));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsNumber(c));
}
[Fact]
public static void IsNumber_String_Int()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.DecimalDigitNumber,
UnicodeCategory.LetterNumber,
UnicodeCategory.OtherNumber
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsNumber(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsNumber(c.ToString(), 0));
}
[Fact]
public static void IsNumber_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsNumber(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsNumber("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsNumber("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsPunctuation_Char()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.ConnectorPunctuation,
UnicodeCategory.DashPunctuation,
UnicodeCategory.OpenPunctuation,
UnicodeCategory.ClosePunctuation,
UnicodeCategory.InitialQuotePunctuation,
UnicodeCategory.FinalQuotePunctuation,
UnicodeCategory.OtherPunctuation
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsPunctuation(c));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsPunctuation(c));
}
[Fact]
public static void IsPunctuation_String_Int()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.ConnectorPunctuation,
UnicodeCategory.DashPunctuation,
UnicodeCategory.OpenPunctuation,
UnicodeCategory.ClosePunctuation,
UnicodeCategory.InitialQuotePunctuation,
UnicodeCategory.FinalQuotePunctuation,
UnicodeCategory.OtherPunctuation
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsPunctuation(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsPunctuation(c.ToString(), 0));
}
[Fact]
public static void IsPunctuation_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsPunctuation(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsPunctuation("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsPunctuation("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsSeparator_Char()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsSeparator(c));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsSeparator(c));
}
[Fact]
public static void IsSeparator_String_Int()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsSeparator(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsSeparator(c.ToString(), 0));
}
[Fact]
public static void IsSeparator_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsSeparator(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSeparator("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSeparator("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsLowSurrogate_Char()
{
foreach (char c in s_lowSurrogates)
Assert.True(char.IsLowSurrogate(c));
foreach (char c in s_highSurrogates)
Assert.False(char.IsLowSurrogate(c));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsLowSurrogate(c));
}
[Fact]
public static void IsLowSurrogate_String_Int()
{
foreach (char c in s_lowSurrogates)
Assert.True(char.IsLowSurrogate(c.ToString(), 0));
foreach (char c in s_highSurrogates)
Assert.False(char.IsLowSurrogate(c.ToString(), 0));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsLowSurrogate(c.ToString(), 0));
}
[Fact]
public static void IsLowSurrogate_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsLowSurrogate(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLowSurrogate("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLowSurrogate("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsHighSurrogate_Char()
{
foreach (char c in s_highSurrogates)
Assert.True(char.IsHighSurrogate(c));
foreach (char c in s_lowSurrogates)
Assert.False(char.IsHighSurrogate(c));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsHighSurrogate(c));
}
[Fact]
public static void IsHighSurrogate_String_Int()
{
foreach (char c in s_highSurrogates)
Assert.True(char.IsHighSurrogate(c.ToString(), 0));
foreach (char c in s_lowSurrogates)
Assert.False(char.IsHighSurrogate(c.ToString(), 0));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsHighSurrogate(c.ToString(), 0));
}
[Fact]
public static void IsHighSurrogate_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsHighSurrogate(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsHighSurrogate("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsHighSurrogate("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsSurrogate_Char()
{
foreach (char c in s_highSurrogates)
Assert.True(char.IsSurrogate(c));
foreach (char c in s_lowSurrogates)
Assert.True(char.IsSurrogate(c));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsSurrogate(c));
}
[Fact]
public static void IsSurrogate_String_Int()
{
foreach (char c in s_highSurrogates)
Assert.True(char.IsSurrogate(c.ToString(), 0));
foreach (char c in s_lowSurrogates)
Assert.True(char.IsSurrogate(c.ToString(), 0));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsSurrogate(c.ToString(), 0));
}
[Fact]
public static void IsSurrogate_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsSurrogate(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogate("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogate("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsSurrogatePair_Char()
{
foreach (char hs in s_highSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.True(char.IsSurrogatePair(hs, ls));
foreach (char hs in s_nonSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.False(char.IsSurrogatePair(hs, ls));
foreach (char hs in s_highSurrogates)
foreach (char ls in s_nonSurrogates)
Assert.False(char.IsSurrogatePair(hs, ls));
}
[Fact]
public static void IsSurrogatePair_String_Int()
{
foreach (char hs in s_highSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.True(char.IsSurrogatePair(hs.ToString() + ls, 0));
foreach (char hs in s_nonSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.False(char.IsSurrogatePair(hs.ToString() + ls, 0));
foreach (char hs in s_highSurrogates)
foreach (char ls in s_nonSurrogates)
Assert.False(char.IsSurrogatePair(hs.ToString() + ls, 0));
Assert.False(char.IsSurrogatePair("\ud800\udc00", 1)); // Index + 1 >= s.Length
}
[Fact]
public static void IsSurrogatePair_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsSurrogatePair(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogatePair("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogatePair("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsSymbol_Char()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.MathSymbol,
UnicodeCategory.ModifierSymbol,
UnicodeCategory.CurrencySymbol,
UnicodeCategory.OtherSymbol
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsSymbol(c));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsSymbol(c));
}
[Fact]
public static void IsSymbol_String_Int()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.MathSymbol,
UnicodeCategory.ModifierSymbol,
UnicodeCategory.CurrencySymbol,
UnicodeCategory.OtherSymbol
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsSymbol(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(categories))
Assert.False(char.IsSymbol(c.ToString(), 0));
}
[Fact]
public static void IsSymbol_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsSymbol(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSymbol("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSymbol("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsUpper_Char()
{
foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter))
Assert.True(char.IsUpper(c));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter))
Assert.False(char.IsUpper(c));
}
[Fact]
public static void IsUpper_String_Int()
{
foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter))
Assert.True(char.IsUpper(c.ToString(), 0));
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter))
Assert.False(char.IsUpper(c.ToString(), 0));
}
[Fact]
public static void IsUpper_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsUpper(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsUpper("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsUpper("abc", 3)); // Index >= string.Length
}
[Fact]
public static void IsWhitespace_Char()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsWhiteSpace(c));
foreach (char c in GetTestCharsNotInCategory(categories))
{
// Need to special case some control chars that are treated as whitespace
if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') continue;
Assert.False(char.IsWhiteSpace(c));
}
}
[Fact]
public static void IsWhiteSpace_String_Int()
{
var categories = new UnicodeCategory[]
{
UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator
};
foreach (char c in GetTestChars(categories))
Assert.True(char.IsWhiteSpace(c.ToString(), 0));
// Some control chars are also considered whitespace for legacy reasons.
// if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085')
Assert.True(char.IsWhiteSpace("\u000b", 0));
Assert.True(char.IsWhiteSpace("\u0085", 0));
foreach (char c in GetTestCharsNotInCategory(categories))
{
// Need to special case some control chars that are treated as whitespace
if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') continue;
Assert.False(char.IsWhiteSpace(c.ToString(), 0));
}
}
[Fact]
public static void IsWhiteSpace_String_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsWhiteSpace(null, 0)); // String is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsWhiteSpace("abc", -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsWhiteSpace("abc", 3)); // Index >= string.Length
}
[Fact]
public static void MaxValue()
{
Assert.Equal(0xffff, char.MaxValue);
}
[Fact]
public static void MinValue()
{
Assert.Equal(0, char.MinValue);
}
[Fact]
public static void ToLower()
{
Assert.Equal('a', char.ToLower('A'));
Assert.Equal('a', char.ToLower('a'));
foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter))
{
char lc = char.ToLower(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsLower(lc));
}
// TitlecaseLetter can have a lower case form (e.g. \u01C8 'Lj' letter which will be 'lj')
// LetterNumber can have a lower case form (e.g. \u2162 'III' letter which will be 'iii')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
Assert.Equal(c, char.ToLower(c));
}
}
[Fact]
public static void ToLowerInvariant()
{
Assert.Equal('a', char.ToLowerInvariant('A'));
Assert.Equal('a', char.ToLowerInvariant('a'));
foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter))
{
char lc = char.ToLowerInvariant(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsLower(lc));
}
// TitlecaseLetter can have a lower case form (e.g. \u01C8 'Lj' letter which will be 'lj')
// LetterNumber can have a lower case form (e.g. \u2162 'III' letter which will be 'iii')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
Assert.Equal(c, char.ToLowerInvariant(c));
}
}
[Theory]
[InlineData('a', "a")]
[InlineData('\uabcd', "\uabcd")]
public static void ToString(char c, string expected)
{
Assert.Equal(expected, c.ToString());
Assert.Equal(expected, char.ToString(c));
}
[Fact]
public static void ToUpper()
{
Assert.Equal('A', char.ToUpper('A'));
Assert.Equal('A', char.ToUpper('a'));
foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter))
{
char lc = char.ToUpper(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsUpper(lc));
}
// TitlecaseLetter can have a uppercase form (e.g. \u01C8 'Lj' letter which will be 'LJ')
// LetterNumber can have a uppercase form (e.g. \u2172 'iii' letter which will be 'III')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
Assert.Equal(c, char.ToUpper(c));
}
}
[Fact]
public static void ToUpperInvariant()
{
Assert.Equal('A', char.ToUpperInvariant('A'));
Assert.Equal('A', char.ToUpperInvariant('a'));
foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter))
{
char lc = char.ToUpperInvariant(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsUpper(lc));
}
// TitlecaseLetter can have a uppercase form (e.g. \u01C8 'Lj' letter which will be 'LJ')
// LetterNumber can have a uppercase form (e.g. \u2172 'iii' letter which will be 'III')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
Assert.Equal(c, char.ToUpperInvariant(c));
}
}
public static IEnumerable<object[]> Parse_TestData()
{
yield return new object[] { "a", 'a' };
yield return new object[] { "4", '4' };
yield return new object[] { " ", ' ' };
yield return new object[] { "\n", '\n' };
yield return new object[] { "\0", '\0' };
yield return new object[] { "\u0135", '\u0135' };
yield return new object[] { "\u05d9", '\u05d9' };
yield return new object[] { "\ue001", '\ue001' }; // Private use codepoint
// Lone surrogate
yield return new object[] { "\ud801", '\ud801' }; // High surrogate
yield return new object[] { "\udc01", '\udc01' }; // Low surrogate
}
[Theory]
[MemberData(nameof(Parse_TestData))]
public static void Parse(string s, char expected)
{
char c;
Assert.True(char.TryParse(s, out c));
Assert.Equal(expected, c);
Assert.Equal(expected, char.Parse(s));
}
[Theory]
[InlineData(null, typeof(ArgumentNullException))]
[InlineData("", typeof(FormatException))]
[InlineData("\n\r", typeof(FormatException))]
[InlineData("kj", typeof(FormatException))]
[InlineData(" a", typeof(FormatException))]
[InlineData("a ", typeof(FormatException))]
[InlineData("\\u0135", typeof(FormatException))]
[InlineData("\u01356", typeof(FormatException))]
[InlineData("\ud801\udc01", typeof(FormatException))] // Surrogate pair
public static void Parse_Invalid(string s, Type exceptionType)
{
char c;
Assert.False(char.TryParse(s, out c));
Assert.Equal(default(char), c);
Assert.Throws(exceptionType, () => char.Parse(s));
}
private static IEnumerable<char> GetTestCharsNotInCategory(params UnicodeCategory[] categories)
{
Assert.Equal(s_latinTestSet.Length, s_unicodeTestSet.Length);
for (int i = 0; i < s_latinTestSet.Length; i++)
{
if (Array.Exists(categories, uc => uc == (UnicodeCategory)i))
continue;
char[] latinSet = s_latinTestSet[i];
for (int j = 0; j < latinSet.Length; j++)
yield return latinSet[j];
char[] unicodeSet = s_unicodeTestSet[i];
for (int k = 0; k < unicodeSet.Length; k++)
yield return unicodeSet[k];
}
}
private static IEnumerable<char> GetTestChars(params UnicodeCategory[] categories)
{
for (int i = 0; i < categories.Length; i++)
{
char[] latinSet = s_latinTestSet[(int)categories[i]];
for (int j = 0; j < latinSet.Length; j++)
yield return latinSet[j];
char[] unicodeSet = s_unicodeTestSet[(int)categories[i]];
for (int k = 0; k < unicodeSet.Length; k++)
yield return unicodeSet[k];
}
}
private static char[][] s_latinTestSet = new char[][]
{
new char[] {'\u0047','\u004c','\u0051','\u0056','\u00c0','\u00c5','\u00ca','\u00cf','\u00d4','\u00da'}, // UnicodeCategory.UppercaseLetter
new char[] {'\u0062','\u0068','\u006e','\u0074','\u007a','\u00e1','\u00e7','\u00ed','\u00f3','\u00fa'}, // UnicodeCategory.LowercaseLetter
new char[] {}, // UnicodeCategory.TitlecaseLetter
new char[] {}, // UnicodeCategory.ModifierLetter
new char[] {}, // UnicodeCategory.OtherLetter
new char[] {}, // UnicodeCategory.NonSpacingMark
new char[] {}, // UnicodeCategory.SpacingCombiningMark
new char[] {}, // UnicodeCategory.EnclosingMark
new char[] {'\u0030','\u0031','\u0032','\u0033','\u0034','\u0035','\u0036','\u0037','\u0038','\u0039'}, // UnicodeCategory.DecimalDigitNumber
new char[] {}, // UnicodeCategory.LetterNumber
new char[] {'\u00b2','\u00b3','\u00b9','\u00bc','\u00bd','\u00be'}, // UnicodeCategory.OtherNumber
new char[] {'\u0020','\u00a0'}, // UnicodeCategory.SpaceSeparator
new char[] {}, // UnicodeCategory.LineSeparator
new char[] {}, // UnicodeCategory.ParagraphSeparator
new char[] {'\u0005','\u000b','\u0011','\u0017','\u001d','\u0082','\u0085','\u008e','\u0094','\u009a'}, // UnicodeCategory.Control
new char[] {}, // UnicodeCategory.Format
new char[] {}, // UnicodeCategory.Surrogate
new char[] {}, // UnicodeCategory.PrivateUse
new char[] {'\u005f'}, // UnicodeCategory.ConnectorPunctuation
new char[] {'\u002d','\u00ad'}, // UnicodeCategory.DashPunctuation
new char[] {'\u0028','\u005b','\u007b'}, // UnicodeCategory.OpenPunctuation
new char[] {'\u0029','\u005d','\u007d'}, // UnicodeCategory.ClosePunctuation
new char[] {'\u00ab'}, // UnicodeCategory.InitialQuotePunctuation
new char[] {'\u00bb'}, // UnicodeCategory.FinalQuotePunctuation
new char[] {'\u002e','\u002f','\u003a','\u003b','\u003f','\u0040','\u005c','\u00a1','\u00b7','\u00bf'}, // UnicodeCategory.OtherPunctuation
new char[] {'\u002b','\u003c','\u003d','\u003e','\u007c','\u007e','\u00ac','\u00b1','\u00d7','\u00f7'}, // UnicodeCategory.MathSymbol
new char[] {'\u0024','\u00a2','\u00a3','\u00a4','\u00a5'}, // UnicodeCategory.CurrencySymbol
new char[] {'\u005e','\u0060','\u00a8','\u00af','\u00b4','\u00b8'}, // UnicodeCategory.ModifierSymbol
new char[] {'\u00a6','\u00a7','\u00a9','\u00ae','\u00b0','\u00b6'}, // UnicodeCategory.OtherSymbol
new char[] {}, // UnicodeCategory.OtherNotAssigned
};
private static char[][] s_unicodeTestSet = new char[][]
{
new char[] {'\u0102','\u01ac','\u0392','\u0428','\u0508','\u10c4','\u1eb4','\u1fba','\u2c28','\ua668'}, // UnicodeCategory.UppercaseLetter
new char[] { '\u0107', '\u012D', '\u0140', '\u0151', '\u013A', '\u01A1', '\u01F9', '\u022D', '\u1E09','\uFF45' }, // UnicodeCategory.LowercaseLetter
new char[] {'\u01c8','\u1f88','\u1f8b','\u1f8e','\u1f99','\u1f9c','\u1f9f','\u1faa','\u1fad','\u1fbc'}, // UnicodeCategory.TitlecaseLetter
new char[] {'\u02b7','\u02cd','\u07f4','\u1d2f','\u1d41','\u1d53','\u1d9d','\u1daf','\u2091','\u30fe'}, // UnicodeCategory.ModifierLetter
new char[] {'\u01c0','\u37be','\u4970','\u5b6c','\u6d1e','\u7ed0','\u9082','\ua271','\ub985','\ucb37'}, // UnicodeCategory.OtherLetter
new char[] {'\u0303','\u034e','\u05b5','\u0738','\u0a4d','\u0e49','\u0fad','\u180b','\u1dd5','\u2dfd'}, // UnicodeCategory.NonSpacingMark
new char[] {'\u0982','\u0b03','\u0c41','\u0d40','\u0df3','\u1083','\u1925','\u1b44','\ua8b5' }, // UnicodeCategory.SpacingCombiningMark
new char[] {'\u20dd','\u20de','\u20df','\u20e0','\u20e2','\u20e3','\u20e4','\ua670','\ua671','\ua672'}, // UnicodeCategory.EnclosingMark
new char[] {'\u0660','\u0966','\u0ae6','\u0c66','\u0e50','\u1040','\u1810','\u1b50','\u1c50','\ua900'}, // UnicodeCategory.DecimalDigitNumber
new char[] {'\u2162','\u2167','\u216c','\u2171','\u2176','\u217b','\u2180','\u2187','\u3023','\u3028'}, // UnicodeCategory.LetterNumber
new char[] {'\u0c78','\u136b','\u17f7','\u2158','\u2471','\u248a','\u24f1','\u2780','\u3220','\u3280'}, // UnicodeCategory.OtherNumber
new char[] {'\u2004','\u2005','\u2006','\u2007','\u2008','\u2009','\u200a','\u202f','\u205f','\u3000'}, // UnicodeCategory.SpaceSeparator
new char[] {'\u2028'}, // UnicodeCategory.LineSeparator
new char[] {'\u2029'}, // UnicodeCategory.ParagraphSeparator
new char[] {}, // UnicodeCategory.Control
new char[] {'\u0603','\u17b4','\u200c','\u200f','\u202c','\u2060','\u2063','\u206b','\u206e','\ufff9'}, // UnicodeCategory.Format
new char[] {'\ud808','\ud8d4','\ud9a0','\uda6c','\udb38','\udc04','\udcd0','\udd9c','\ude68','\udf34'}, // UnicodeCategory.Surrogate
new char[] {'\ue000','\ue280','\ue500','\ue780','\uea00','\uec80','\uef00','\uf180','\uf400','\uf680'}, // UnicodeCategory.PrivateUse
new char[] {'\u203f','\u2040','\u2054','\ufe33','\ufe34','\ufe4d','\ufe4e','\ufe4f','\uff3f'}, // UnicodeCategory.ConnectorPunctuation
new char[] {'\u2e17','\u2e1a','\u301c','\u3030','\u30a0','\ufe31','\ufe32','\ufe58','\ufe63','\uff0d'}, // UnicodeCategory.DashPunctuation
new char[] {'\u2768','\u2774','\u27ee','\u298d','\u29d8','\u2e28','\u3014','\ufe17','\ufe3f','\ufe5d'}, // UnicodeCategory.OpenPunctuation
new char[] {'\u276b','\u27c6','\u2984','\u2990','\u29db','\u3009','\u3017','\ufe18','\ufe40','\ufe5e'}, // UnicodeCategory.ClosePunctuation
new char[] {'\u201b','\u201c','\u201f','\u2039','\u2e02','\u2e04','\u2e09','\u2e0c','\u2e1c','\u2e20'}, // UnicodeCategory.InitialQuotePunctuation
new char[] {'\u2019','\u201d','\u203a','\u2e03','\u2e05','\u2e0a','\u2e0d','\u2e1d','\u2e21'}, // UnicodeCategory.FinalQuotePunctuation
new char[] {'\u0589','\u0709','\u0f10','\u16ec','\u1b5b','\u2034','\u2058','\u2e16','\ua8cf','\ufe55'}, // UnicodeCategory.OtherPunctuation
new char[] {'\u2052','\u2234','\u2290','\u22ec','\u27dd','\u2943','\u29b5','\u2a17','\u2a73','\u2acf'}, // UnicodeCategory.MathSymbol
new char[] {'\u17db','\u20a2','\u20a5','\u20a8','\u20ab','\u20ae','\u20b1','\u20b4','\ufe69','\uffe1'}, // UnicodeCategory.CurrencySymbol
new char[] {'\u02c5','\u02da','\u02e8','\u02f3','\u02fc','\u1fc0','\u1fee','\ua703','\ua70c','\ua715'}, // UnicodeCategory.ModifierSymbol
new char[] {'\u0bf3','\u2316','\u24ac','\u25b2','\u26af','\u285c','\u2e8f','\u2f8c','\u3292','\u3392'}, // UnicodeCategory.OtherSymbol
new char[] {'\u09c6','\u0dfa','\u2e5c'}, // UnicodeCategory.OtherNotAssigned
};
private static char[] s_highSurrogates = new char[] { '\ud800', '\udaaa', '\udbff' }; // Range from '\ud800' to '\udbff'
private static char[] s_lowSurrogates = new char[] { '\udc00', '\udeee', '\udfff' }; // Range from '\udc00' to '\udfff'
private static char[] s_nonSurrogates = new char[] { '\u0000', '\ud7ff', '\ue000', '\uffff' };
private static readonly UnicodeCategory[] s_categoryForLatin1 =
{
UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0000 - 0007
UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0008 - 000F
UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0010 - 0017
UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0018 - 001F
UnicodeCategory.SpaceSeparator, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.CurrencySymbol, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, // 0020 - 0027
UnicodeCategory.OpenPunctuation, UnicodeCategory.ClosePunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.MathSymbol, UnicodeCategory.OtherPunctuation, UnicodeCategory.DashPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, // 0028 - 002F
UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, // 0030 - 0037
UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.MathSymbol, UnicodeCategory.MathSymbol, UnicodeCategory.MathSymbol, UnicodeCategory.OtherPunctuation, // 0038 - 003F
UnicodeCategory.OtherPunctuation, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, // 0040 - 0047
UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, // 0048 - 004F
UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, // 0050 - 0057
UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.OpenPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.ClosePunctuation, UnicodeCategory.ModifierSymbol, UnicodeCategory.ConnectorPunctuation, // 0058 - 005F
UnicodeCategory.ModifierSymbol, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 0060 - 0067
UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 0068 - 006F
UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 0070 - 0077
UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.OpenPunctuation, UnicodeCategory.MathSymbol, UnicodeCategory.ClosePunctuation, UnicodeCategory.MathSymbol, UnicodeCategory.Control, // 0078 - 007F
UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0080 - 0087
UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0088 - 008F
UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0090 - 0097
UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0098 - 009F
UnicodeCategory.SpaceSeparator, UnicodeCategory.OtherPunctuation, UnicodeCategory.CurrencySymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.OtherSymbol, UnicodeCategory.OtherSymbol, // 00A0 - 00A7
UnicodeCategory.ModifierSymbol, UnicodeCategory.OtherSymbol, UnicodeCategory.LowercaseLetter, UnicodeCategory.InitialQuotePunctuation, UnicodeCategory.MathSymbol, UnicodeCategory.DashPunctuation, UnicodeCategory.OtherSymbol, UnicodeCategory.ModifierSymbol, // 00A8 - 00AF
UnicodeCategory.OtherSymbol, UnicodeCategory.MathSymbol, UnicodeCategory.OtherNumber, UnicodeCategory.OtherNumber, UnicodeCategory.ModifierSymbol, UnicodeCategory.LowercaseLetter, UnicodeCategory.OtherSymbol, UnicodeCategory.OtherPunctuation, // 00B0 - 00B7
UnicodeCategory.ModifierSymbol, UnicodeCategory.OtherNumber, UnicodeCategory.LowercaseLetter, UnicodeCategory.FinalQuotePunctuation, UnicodeCategory.OtherNumber, UnicodeCategory.OtherNumber, UnicodeCategory.OtherNumber, UnicodeCategory.OtherPunctuation, // 00B8 - 00BF
UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, // 00C0 - 00C7
UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, // 00C8 - 00CF
UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.MathSymbol, // 00D0 - 00D7
UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, // 00D8 - 00DF
UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 00E0 - 00E7
UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 00E8 - 00EF
UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.MathSymbol, // 00F0 - 00F7
UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 00F8 - 00FF
};
public static IEnumerable<object[]> UpperLowerCasing_TestData()
{
// lower upper Culture
yield return new object[] { 'a', 'A', "en-US" };
yield return new object[] { 'i', 'I', "en-US" };
yield return new object[] { '\u0131', 'I', "tr-TR" };
yield return new object[] { 'i', '\u0130', "tr-TR" };
yield return new object[] { '\u0660', '\u0660', "en-US" };
}
[Fact]
public static void LatinRangeTest()
{
StringBuilder sb = new StringBuilder(256);
string latineString = sb.ToString();
for (int i=0; i < latineString.Length; i++)
{
Assert.Equal(s_categoryForLatin1[i], Char.GetUnicodeCategory(latineString[i]));
Assert.Equal(s_categoryForLatin1[i], Char.GetUnicodeCategory(latineString, i));
}
}
[Fact]
public static void NonLatinRangeTest()
{
for (int i=256; i <= 0xFFFF; i++)
{
Assert.Equal(CharUnicodeInfo.GetUnicodeCategory((char)i), Char.GetUnicodeCategory((char)i));
}
string nonLatinString = "\u0100\u0200\u0300\u0400\u0500\u0600\u0700\u0800\u0900\u0A00\u0B00\u0C00\u0D00\u0E00\u0F00" +
"\u1000\u2000\u3000\u4000\u5000\u6000\u7000\u8000\u9000\uA000\uB000\uC000\uD000\uE000\uF000";
for (int i=0; i < nonLatinString.Length; i++)
{
Assert.Equal(CharUnicodeInfo.GetUnicodeCategory(nonLatinString[i]), Char.GetUnicodeCategory(nonLatinString, i));
}
}
[Theory]
[MemberData(nameof(UpperLowerCasing_TestData))]
public static void CasingTest(char lowerForm, char upperForm, string cultureName)
{
CultureInfo ci = CultureInfo.GetCultureInfo(cultureName);
Assert.Equal(lowerForm, char.ToLower(upperForm, ci));
Assert.Equal(upperForm, char.ToUpper(lowerForm, ci));
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="BusinessBase.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>This is the base class from which most business objects</summary>
//-----------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Reflection;
using Csla.Properties;
using Csla.Core;
using Csla.Reflection;
using System.Threading.Tasks;
namespace Csla
{
/// <summary>
/// This is the base class from which most business objects
/// will be derived.
/// </summary>
/// <remarks>
/// <para>
/// This class is the core of the CSLA .NET framework. To create
/// a business object, inherit from this class.
/// </para><para>
/// Please refer to 'Expert C# 2008 Business Objects' for
/// full details on the use of this base class to create business
/// objects.
/// </para>
/// </remarks>
/// <typeparam name="T">Type of the business object being defined.</typeparam>
[Serializable]
public abstract class BusinessBase<T> :
Core.BusinessBase, Core.ISavable, Core.ISavable<T>, IBusinessBase where T : BusinessBase<T>
{
#region Object ID Value
/// <summary>
/// Override this method to return a unique identifying
/// value for this object.
/// </summary>
protected virtual object GetIdValue()
{
return null;
}
#endregion
#region System.Object Overrides
/// <summary>
/// Returns a text representation of this object by
/// returning the <see cref="GetIdValue"/> value
/// in text form.
/// </summary>
public override string ToString()
{
object id = GetIdValue();
if (id == null)
return base.ToString();
else
return id.ToString();
}
#endregion
#region Clone
/// <summary>
/// Creates a clone of the object.
/// </summary>
/// <returns>
/// A new object containing the exact data of the original object.
/// </returns>
public T Clone()
{
return (T)GetClone();
}
#endregion
#region Data Access
/// <summary>
/// Saves the object to the database.
/// </summary>
/// <remarks>
/// <para>
/// Calling this method starts the save operation, causing the object
/// to be inserted, updated or deleted within the database based on the
/// object's current state.
/// </para><para>
/// If <see cref="Core.BusinessBase.IsDeleted" /> is true
/// the object will be deleted. Otherwise, if <see cref="Core.BusinessBase.IsNew" />
/// is true the object will be inserted.
/// Otherwise the object's data will be updated in the database.
/// </para><para>
/// All this is contingent on <see cref="Core.BusinessBase.IsDirty" />. If
/// this value is false, no data operation occurs.
/// It is also contingent on <see cref="Core.BusinessBase.IsValid" />.
/// If this value is false an
/// exception will be thrown to indicate that the UI attempted to save an
/// invalid object.
/// </para><para>
/// It is important to note that this method returns a new version of the
/// business object that contains any data updated during the save operation.
/// You MUST update all object references to use this new version of the
/// business object in order to have access to the correct object data.
/// </para><para>
/// You can override this method to add your own custom behaviors to the save
/// operation. For instance, you may add some security checks to make sure
/// the user can save the object. If all security checks pass, you would then
/// invoke the base Save method via <c>base.Save()</c>.
/// </para>
/// </remarks>
/// <returns>A new object containing the saved values.</returns>
public T Save()
{
try
{
return SaveAsync(false, null, true).Result;
}
catch (AggregateException ex)
{
if (ex.InnerExceptions.Count > 0)
throw ex.InnerExceptions[0];
else
throw;
}
}
/// <summary>
/// Saves the object to the database.
/// </summary>
public async System.Threading.Tasks.Task<T> SaveAsync()
{
return await SaveAsync(false);
}
/// <summary>
/// Saves the object to the database.
/// </summary>
/// <param name="forceUpdate">
/// If true, triggers overriding IsNew and IsDirty.
/// If false then it is the same as calling Save().
/// </param>
public async System.Threading.Tasks.Task<T> SaveAsync(bool forceUpdate)
{
return await SaveAsync(forceUpdate, null, false);
}
/// <summary>
/// Saves the object to the database.
/// </summary>
/// <param name="forceUpdate">
/// If true, triggers overriding IsNew and IsDirty.
/// If false then it is the same as calling Save().
/// </param>
/// <param name="userState">User state data.</param>
/// <param name="isSync">True if the save operation should be synchronous.</param>
protected async virtual System.Threading.Tasks.Task<T> SaveAsync(bool forceUpdate, object userState, bool isSync)
{
if (forceUpdate && IsNew)
{
// mark the object as old - which makes it
// not dirty
MarkOld();
// now mark the object as dirty so it can save
MarkDirty(true);
}
T result;
if (this.IsChild)
throw new InvalidOperationException(Resources.NoSaveChildException);
if (EditLevel > 0)
throw new InvalidOperationException(Resources.NoSaveEditingException);
if (!IsValid && !IsDeleted)
throw new Rules.ValidationException(Resources.NoSaveInvalidException);
if (IsBusy)
throw new InvalidOperationException(Resources.BusyObjectsMayNotBeSaved);
if (IsDirty)
{
if (isSync)
{
result = DataPortal.Update<T>((T)this);
}
else
{
MarkBusy();
try
{
result = await DataPortal.UpdateAsync<T>((T)this);
}
finally
{
MarkIdle();
}
}
}
else
{
result = (T)this;
}
OnSaved(result, null, userState);
return result;
}
/// <summary>
/// Saves the object to the database, forcing
/// IsNew to false and IsDirty to True.
/// </summary>
/// <param name="forceUpdate">
/// If true, triggers overriding IsNew and IsDirty.
/// If false then it is the same as calling Save().
/// </param>
/// <returns>A new object containing the saved values.</returns>
/// <remarks>
/// This overload is designed for use in web applications
/// when implementing the Update method in your
/// data wrapper object.
/// </remarks>
public T Save(bool forceUpdate)
{
if (forceUpdate && IsNew)
{
// mark the object as old - which makes it
// not dirty
MarkOld();
// now mark the object as dirty so it can save
MarkDirty(true);
}
return this.Save();
}
/// <summary>
/// Saves the object to the database, merging
/// any resulting updates into the existing
/// object graph.
/// </summary>
public async Task SaveAndMergeAsync()
{
await SaveAndMergeAsync(false);
}
/// <summary>
/// Saves the object to the database, merging
/// any resulting updates into the existing
/// object graph.
/// </summary>
/// <param name="forceUpdate">
/// If true, triggers overriding IsNew and IsDirty.
/// If false then it is the same as calling SaveAndMergeAsync().
/// </param>
public async Task SaveAndMergeAsync(bool forceUpdate)
{
new GraphMerger().MergeGraph(this, await SaveAsync(forceUpdate));
}
/// <summary>
/// Starts an async operation to save the object to the database.
/// </summary>
[Obsolete]
public void BeginSave()
{
BeginSave(null);
}
/// <summary>
/// Starts an async operation to save the object to the database.
/// </summary>
/// <param name="userState">User state data.</param>
[Obsolete]
public void BeginSave(object userState)
{
BeginSave(false, null, userState);
}
/// <summary>
/// Starts an async operation to save the object to the database.
/// </summary>
/// <param name="handler">
/// Method called when the operation is complete.
/// </param>
[Obsolete]
public void BeginSave(EventHandler<SavedEventArgs> handler)
{
BeginSave(false, handler, null);
}
/// <summary>
/// Starts an async operation to save the object to the database.
/// </summary>
/// <param name="forceUpdate">
/// If true, triggers overriding IsNew and IsDirty.
/// If false then it is the same as calling Save().
/// </param>
/// <param name="handler">
/// Method called when the operation is complete.
/// </param>
/// <param name="userState">User state data.</param>
[Obsolete]
public async void BeginSave(bool forceUpdate, EventHandler<SavedEventArgs> handler, object userState)
{
T result = default(T);
Exception error = null;
try
{
result = await SaveAsync(forceUpdate, userState, false);
}
catch (AggregateException ex)
{
if (ex.InnerExceptions.Count > 0)
error = ex.InnerExceptions[0];
else
error = ex;
}
catch (Exception ex)
{
error = ex;
}
if (error != null)
OnSaved(null, error, userState);
handler?.Invoke(this, new SavedEventArgs(result, error, userState));
}
/// <summary>
/// Starts an async operation to save the object to the database.
/// </summary>
/// <param name="forceUpdate">
/// If true, triggers overriding IsNew and IsDirty.
/// If false then it is the same as calling Save().
/// </param>
/// <remarks>
/// This overload is designed for use in web applications
/// when implementing the Update method in your
/// data wrapper object.
/// </remarks>
[Obsolete]
public void BeginSave(bool forceUpdate)
{
this.BeginSave(forceUpdate, null);
}
/// <summary>
/// Starts an async operation to save the object to the database.
/// </summary>
/// <param name="forceUpdate">
/// If true, triggers overriding IsNew and IsDirty.
/// If false then it is the same as calling Save().
/// </param>
/// <param name="handler">
/// Delegate reference to a callback handler that will
/// be invoked when the async operation is complete.
/// </param>
/// <remarks>
/// This overload is designed for use in web applications
/// when implementing the Update method in your
/// data wrapper object.
/// </remarks>
[Obsolete]
public void BeginSave(bool forceUpdate, EventHandler<SavedEventArgs> handler)
{
this.BeginSave(forceUpdate, handler, null);
}
/// <summary>
/// Saves the object to the database, forcing
/// IsNew to false and IsDirty to True.
/// </summary>
/// <param name="handler">
/// Delegate reference to a callback handler that will
/// be invoked when the async operation is complete.
/// </param>
/// <param name="userState">User state data.</param>
/// <remarks>
/// This overload is designed for use in web applications
/// when implementing the Update method in your
/// data wrapper object.
/// </remarks>
[Obsolete]
public void BeginSave(EventHandler<SavedEventArgs> handler, object userState)
{
this.BeginSave(false, handler, userState);
}
#endregion
#region ISavable Members
void Csla.Core.ISavable.SaveComplete(object newObject)
{
OnSaved((T)newObject, null, null);
}
void Csla.Core.ISavable<T>.SaveComplete(T newObject)
{
OnSaved(newObject, null, null);
}
object Csla.Core.ISavable.Save()
{
return Save();
}
object Csla.Core.ISavable.Save(bool forceUpdate)
{
return Save(forceUpdate);
}
[NonSerialized]
[NotUndoable]
private EventHandler<Csla.Core.SavedEventArgs> _nonSerializableSavedHandlers;
[NotUndoable]
private EventHandler<Csla.Core.SavedEventArgs> _serializableSavedHandlers;
/// <summary>
/// Event raised when an object has been saved.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design",
"CA1062:ValidateArgumentsOfPublicMethods")]
public event EventHandler<Csla.Core.SavedEventArgs> Saved
{
add
{
if (value.Method.IsPublic &&
(value.Method.DeclaringType.IsSerializable ||
value.Method.IsStatic))
_serializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>)
System.Delegate.Combine(_serializableSavedHandlers, value);
else
_nonSerializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>)
System.Delegate.Combine(_nonSerializableSavedHandlers, value);
}
remove
{
if (value.Method.IsPublic &&
(value.Method.DeclaringType.IsSerializable ||
value.Method.IsStatic))
_serializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>)
System.Delegate.Remove(_serializableSavedHandlers, value);
else
_nonSerializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>)
System.Delegate.Remove(_nonSerializableSavedHandlers, value);
}
}
async Task<object> ISavable.SaveAsync()
{
return await SaveAsync();
}
async Task<object> ISavable.SaveAsync(bool forceUpdate)
{
return await SaveAsync(forceUpdate);
}
/// <summary>
/// Raises the Saved event, indicating that the
/// object has been saved, and providing a reference
/// to the new object instance.
/// </summary>
/// <param name="newObject">The new object instance.</param>
/// <param name="e">Exception that occurred during operation.</param>
/// <param name="userState">User state object.</param>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnSaved(T newObject, Exception e, object userState)
{
Csla.Core.SavedEventArgs args = new Csla.Core.SavedEventArgs(newObject, e, userState);
if (_nonSerializableSavedHandlers != null)
_nonSerializableSavedHandlers.Invoke(this, args);
if (_serializableSavedHandlers != null)
_serializableSavedHandlers.Invoke(this, args);
}
#endregion
#region Register Properties/Methods
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">
/// Type of property.
/// </typeparam>
/// <param name="info">
/// PropertyInfo object for the property.
/// </param>
/// <returns>
/// The provided IPropertyInfo object.
/// </returns>
protected static PropertyInfo<P> RegisterProperty<P>(PropertyInfo<P> info)
{
return Core.FieldManager.PropertyInfoManager.RegisterProperty<P>(typeof(T), info);
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyName">Property name from nameof()</param>
/// <returns></returns>
protected static PropertyInfo<P> RegisterProperty<P>(string propertyName)
{
return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName));
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyLambdaExpression">Property Expression</param>
/// <returns></returns>
protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression)
{
PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression);
return RegisterProperty<P>(reflectedPropertyInfo.Name);
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyLambdaExpression">Property Expression</param>
/// <param name="defaultValue">Default Value for the property</param>
/// <returns></returns>
[Obsolete]
protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, P defaultValue)
{
PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression);
return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), reflectedPropertyInfo.Name, string.Empty, defaultValue));
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyName">Property name from nameof()</param>
/// <param name="relationship">Relationship with property value.</param>
/// <returns></returns>
protected static PropertyInfo<P> RegisterProperty<P>(string propertyName, RelationshipTypes relationship)
{
return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName, string.Empty, relationship));
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyLambdaExpression">Property Expression</param>
/// <param name="relationship">Relationship with property value.</param>
/// <returns></returns>
protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, RelationshipTypes relationship)
{
PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression);
return RegisterProperty<P>(reflectedPropertyInfo.Name, relationship);
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyName">Property name from nameof()</param>
/// <param name="friendlyName">Friendly description for a property to be used in databinding</param>
/// <returns></returns>
protected static PropertyInfo<P> RegisterProperty<P>(string propertyName, string friendlyName)
{
return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName, friendlyName));
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyLambdaExpression">Property Expression</param>
/// <param name="friendlyName">Friendly description for a property to be used in databinding</param>
/// <returns></returns>
protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, string friendlyName)
{
PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression);
return RegisterProperty<P>(reflectedPropertyInfo.Name, friendlyName);
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyLambdaExpression">Property Expression</param>
/// <param name="friendlyName">Friendly description for a property to be used in databinding</param>
/// <param name="relationship">Relationship with property value.</param>
/// <returns></returns>
[Obsolete]
protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, string friendlyName, RelationshipTypes relationship)
{
PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression);
return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), reflectedPropertyInfo.Name, friendlyName, relationship));
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyName">Property name from nameof()</param>
/// <param name="friendlyName">Friendly description for a property to be used in databinding</param>
/// <param name="defaultValue">Default Value for the property</param>
/// <returns></returns>
protected static PropertyInfo<P> RegisterProperty<P>(string propertyName, string friendlyName, P defaultValue)
{
return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName, friendlyName, defaultValue));
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyLambdaExpression">Property Expression</param>
/// <param name="friendlyName">Friendly description for a property to be used in databinding</param>
/// <param name="defaultValue">Default Value for the property</param>
/// <returns></returns>
protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, string friendlyName, P defaultValue)
{
PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression);
return RegisterProperty(reflectedPropertyInfo.Name, friendlyName, defaultValue);
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyName">Property name from nameof()</param>
/// <param name="friendlyName">Friendly description for a property to be used in databinding</param>
/// <param name="defaultValue">Default Value for the property</param>
/// <param name="relationship">Relationship with property value.</param>
/// <returns></returns>
protected static PropertyInfo<P> RegisterProperty<P>(string propertyName, string friendlyName, P defaultValue, RelationshipTypes relationship)
{
return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName, friendlyName, defaultValue, relationship));
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyLambdaExpression">Property Expression</param>
/// <param name="friendlyName">Friendly description for a property to be used in databinding</param>
/// <param name="defaultValue">Default Value for the property</param>
/// <param name="relationship">Relationship with property value.</param>
/// <returns></returns>
protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, string friendlyName, P defaultValue, RelationshipTypes relationship)
{
PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression);
return RegisterProperty(reflectedPropertyInfo.Name, friendlyName, defaultValue, relationship);
}
/// <summary>
/// Registers a method for use in Authorization.
/// </summary>
/// <param name="methodName">Method name from nameof()</param>
/// <returns></returns>
protected static MethodInfo RegisterMethod(string methodName)
{
return RegisterMethod(typeof(T), methodName);
}
/// <summary>
/// Registers a method for use in Authorization.
/// </summary>
/// <param name="methodLambdaExpression">The method lambda expression.</param>
/// <returns></returns>
protected static MethodInfo RegisterMethod(Expression<Action<T>> methodLambdaExpression)
{
System.Reflection.MethodInfo reflectedMethodInfo = Reflect<T>.GetMethod(methodLambdaExpression);
return RegisterMethod(reflectedMethodInfo.Name);
}
#endregion
}
}
| |
/*
* ******************************************************************************
* Copyright 2014-2016 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class ImportTapeSpectraS3Request : Ds3Request
{
public string TapeId { get; private set; }
private ImportConflictResolutionMode? _conflictResolutionMode;
public ImportConflictResolutionMode? ConflictResolutionMode
{
get { return _conflictResolutionMode; }
set { WithConflictResolutionMode(value); }
}
private string _dataPolicyId;
public string DataPolicyId
{
get { return _dataPolicyId; }
set { WithDataPolicyId(value); }
}
private Priority? _priority;
public Priority? Priority
{
get { return _priority; }
set { WithPriority(value); }
}
private string _storageDomainId;
public string StorageDomainId
{
get { return _storageDomainId; }
set { WithStorageDomainId(value); }
}
private string _userId;
public string UserId
{
get { return _userId; }
set { WithUserId(value); }
}
private Priority? _verifyDataAfterImport;
public Priority? VerifyDataAfterImport
{
get { return _verifyDataAfterImport; }
set { WithVerifyDataAfterImport(value); }
}
private bool? _verifyDataPriorToImport;
public bool? VerifyDataPriorToImport
{
get { return _verifyDataPriorToImport; }
set { WithVerifyDataPriorToImport(value); }
}
public ImportTapeSpectraS3Request WithConflictResolutionMode(ImportConflictResolutionMode? conflictResolutionMode)
{
this._conflictResolutionMode = conflictResolutionMode;
if (conflictResolutionMode != null)
{
this.QueryParams.Add("conflict_resolution_mode", conflictResolutionMode.ToString());
}
else
{
this.QueryParams.Remove("conflict_resolution_mode");
}
return this;
}
public ImportTapeSpectraS3Request WithDataPolicyId(Guid? dataPolicyId)
{
this._dataPolicyId = dataPolicyId.ToString();
if (dataPolicyId != null)
{
this.QueryParams.Add("data_policy_id", dataPolicyId.ToString());
}
else
{
this.QueryParams.Remove("data_policy_id");
}
return this;
}
public ImportTapeSpectraS3Request WithDataPolicyId(string dataPolicyId)
{
this._dataPolicyId = dataPolicyId;
if (dataPolicyId != null)
{
this.QueryParams.Add("data_policy_id", dataPolicyId);
}
else
{
this.QueryParams.Remove("data_policy_id");
}
return this;
}
public ImportTapeSpectraS3Request WithPriority(Priority? priority)
{
this._priority = priority;
if (priority != null)
{
this.QueryParams.Add("priority", priority.ToString());
}
else
{
this.QueryParams.Remove("priority");
}
return this;
}
public ImportTapeSpectraS3Request WithStorageDomainId(Guid? storageDomainId)
{
this._storageDomainId = storageDomainId.ToString();
if (storageDomainId != null)
{
this.QueryParams.Add("storage_domain_id", storageDomainId.ToString());
}
else
{
this.QueryParams.Remove("storage_domain_id");
}
return this;
}
public ImportTapeSpectraS3Request WithStorageDomainId(string storageDomainId)
{
this._storageDomainId = storageDomainId;
if (storageDomainId != null)
{
this.QueryParams.Add("storage_domain_id", storageDomainId);
}
else
{
this.QueryParams.Remove("storage_domain_id");
}
return this;
}
public ImportTapeSpectraS3Request WithUserId(Guid? userId)
{
this._userId = userId.ToString();
if (userId != null)
{
this.QueryParams.Add("user_id", userId.ToString());
}
else
{
this.QueryParams.Remove("user_id");
}
return this;
}
public ImportTapeSpectraS3Request WithUserId(string userId)
{
this._userId = userId;
if (userId != null)
{
this.QueryParams.Add("user_id", userId);
}
else
{
this.QueryParams.Remove("user_id");
}
return this;
}
public ImportTapeSpectraS3Request WithVerifyDataAfterImport(Priority? verifyDataAfterImport)
{
this._verifyDataAfterImport = verifyDataAfterImport;
if (verifyDataAfterImport != null)
{
this.QueryParams.Add("verify_data_after_import", verifyDataAfterImport.ToString());
}
else
{
this.QueryParams.Remove("verify_data_after_import");
}
return this;
}
public ImportTapeSpectraS3Request WithVerifyDataPriorToImport(bool? verifyDataPriorToImport)
{
this._verifyDataPriorToImport = verifyDataPriorToImport;
if (verifyDataPriorToImport != null)
{
this.QueryParams.Add("verify_data_prior_to_import", verifyDataPriorToImport.ToString());
}
else
{
this.QueryParams.Remove("verify_data_prior_to_import");
}
return this;
}
public ImportTapeSpectraS3Request(Guid tapeId)
{
this.TapeId = tapeId.ToString();
this.QueryParams.Add("operation", "import");
}
public ImportTapeSpectraS3Request(string tapeId)
{
this.TapeId = tapeId;
this.QueryParams.Add("operation", "import");
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.PUT;
}
}
internal override string Path
{
get
{
return "/_rest_/tape/" + TapeId.ToString();
}
}
}
}
| |
#if MONO
using System.Collections.Generic;
using System.Windows.Forms;
#endif
namespace SharpGMad
{
partial class Main
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
#if MONO
// There seems to be an error with how GDI+ disposes stuff related to resource bitmaps
// in these ToolStripItem (and derived) objects.
if (cmsFileEntry != null && !cmsFileEntry.IsDisposed)
{
List<ToolStripItem> items = new List<ToolStripItem>(cmsFileEntry.Items.Count);
foreach (ToolStripItem item in cmsFileEntry.Items)
items.Add(item);
foreach (ToolStripItem item in items)
if (item != null && !item.IsDisposed)
item.Dispose();
cmsFileEntry.Dispose();
components.Remove(cmsFileEntry);
items.Clear();
}
if (tsddbLegacy != null && tsddbLegacy.HasDropDownItems && !tsddbLegacy.IsDisposed)
{
List<ToolStripItem> items = new List<ToolStripItem>(tsddbLegacy.DropDownItems.Count);
foreach (ToolStripItem item in tsddbLegacy.DropDownItems)
items.Add(item);
foreach (ToolStripItem item in items)
if (item != null && !item.IsDisposed)
item.Dispose();
tsddbLegacy.Dispose();
items.Clear();
}
if (tsddbViewOptions != null && tsddbViewOptions.HasDropDownItems && !tsddbViewOptions.IsDisposed)
{
List<ToolStripItem> items = new List<ToolStripItem>(tsddbViewOptions.DropDownItems.Count);
foreach (ToolStripItem item in tsddbViewOptions.DropDownItems)
items.Add(item);
foreach (ToolStripItem item in items)
if (item != null && !item.IsDisposed)
item.Dispose();
tsddbViewOptions.Dispose();
items.Clear();
}
#endif
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.lstFiles = new System.Windows.Forms.ListView();
this.chFilename = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.chFileType = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.chSize = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.ofdAddon = new System.Windows.Forms.OpenFileDialog();
this.tsFileOperations = new System.Windows.Forms.ToolStrip();
this.tsbAddFile = new System.Windows.Forms.ToolStripButton();
this.tssExportHeaderSeparator = new System.Windows.Forms.ToolStripSeparator();
this.tsbPullAll = new System.Windows.Forms.ToolStripButton();
this.tsbDropAll = new System.Windows.Forms.ToolStripButton();
this.tsddbViewOptions = new System.Windows.Forms.ToolStripDropDownButton();
this.tsmiViewLargeIcons = new System.Windows.Forms.ToolStripMenuItem();
this.tsmiViewSmallIcons = new System.Windows.Forms.ToolStripMenuItem();
this.tsmiViewDetails = new System.Windows.Forms.ToolStripMenuItem();
this.tsmiViewList = new System.Windows.Forms.ToolStripMenuItem();
this.tsmiViewTiles = new System.Windows.Forms.ToolStripMenuItem();
this.tssViewSeparator = new System.Windows.Forms.ToolStripSeparator();
this.tsmiViewShowAllFiles = new System.Windows.Forms.ToolStripMenuItem();
this.tsmiViewShowFolderTree = new System.Windows.Forms.ToolStripMenuItem();
this.tsmiViewShowSubfolders = new System.Windows.Forms.ToolStripMenuItem();
this.pnlLeftSide = new System.Windows.Forms.Panel();
this.spcFoldersAndFiles = new System.Windows.Forms.SplitContainer();
this.tvFolders = new System.Windows.Forms.TreeView();
this.pnlFileOpsToolbar = new System.Windows.Forms.Panel();
this.ssStatus = new System.Windows.Forms.StatusStrip();
this.tsslStatus = new System.Windows.Forms.ToolStripStatusLabel();
this.pnlForm = new System.Windows.Forms.Panel();
this.pnlRightSide = new System.Windows.Forms.Panel();
this.txtMetadataDescription = new System.Windows.Forms.TextBox();
this.tsMetadata = new System.Windows.Forms.ToolStrip();
this.tsbUpdateMetadata = new System.Windows.Forms.ToolStripButton();
this.tsbDiscardMetadataChanges = new System.Windows.Forms.ToolStripButton();
this.lblDescription = new System.Windows.Forms.Label();
this.cmbMetadataTag1 = new System.Windows.Forms.ComboBox();
this.cmbMetadataTag2 = new System.Windows.Forms.ComboBox();
this.lblTags = new System.Windows.Forms.Label();
this.cmbMetadataType = new System.Windows.Forms.ComboBox();
this.lblType = new System.Windows.Forms.Label();
this.txtMetadataTitle = new System.Windows.Forms.TextBox();
this.lblTitle = new System.Windows.Forms.Label();
this.tsToolbar = new System.Windows.Forms.ToolStrip();
this.tsbCreateAddon = new System.Windows.Forms.ToolStripButton();
this.tsbOpenAddon = new System.Windows.Forms.ToolStripButton();
this.tsbSaveAddon = new System.Windows.Forms.ToolStripButton();
this.tssAddonSeparator = new System.Windows.Forms.ToolStripSeparator();
this.tsddbLegacy = new System.Windows.Forms.ToolStripDropDownButton();
this.tsmiLegacyCreate = new System.Windows.Forms.ToolStripMenuItem();
this.tsmiLegacyExtract = new System.Windows.Forms.ToolStripMenuItem();
this.ofdAddFile = new System.Windows.Forms.OpenFileDialog();
this.sfdAddon = new System.Windows.Forms.SaveFileDialog();
this.sfdExportFile = new System.Windows.Forms.SaveFileDialog();
this.tssExportSeparator = new System.Windows.Forms.ToolStripSeparator();
this.cmsFileEntry = new System.Windows.Forms.ContextMenuStrip(this.components);
this.tsmFileRemove = new System.Windows.Forms.ToolStripMenuItem();
this.tsmFileExtract = new System.Windows.Forms.ToolStripMenuItem();
this.tsmFileShellExec = new System.Windows.Forms.ToolStripMenuItem();
this.tsmFileExportTo = new System.Windows.Forms.ToolStripMenuItem();
this.tsmFilePull = new System.Windows.Forms.ToolStripMenuItem();
this.tsmFileOpenExport = new System.Windows.Forms.ToolStripMenuItem();
this.tsmFileDropExport = new System.Windows.Forms.ToolStripMenuItem();
this.fbdFileExtractMulti = new System.Windows.Forms.FolderBrowserDialog();
this.tsFileOperations.SuspendLayout();
this.pnlLeftSide.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.spcFoldersAndFiles)).BeginInit();
this.spcFoldersAndFiles.Panel1.SuspendLayout();
this.spcFoldersAndFiles.Panel2.SuspendLayout();
this.spcFoldersAndFiles.SuspendLayout();
this.pnlFileOpsToolbar.SuspendLayout();
this.ssStatus.SuspendLayout();
this.pnlForm.SuspendLayout();
this.pnlRightSide.SuspendLayout();
this.tsMetadata.SuspendLayout();
this.tsToolbar.SuspendLayout();
this.cmsFileEntry.SuspendLayout();
this.SuspendLayout();
//
// lstFiles
//
this.lstFiles.AllowDrop = true;
this.lstFiles.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.chFilename,
this.chFileType,
this.chSize});
this.lstFiles.Dock = System.Windows.Forms.DockStyle.Fill;
this.lstFiles.Location = new System.Drawing.Point(0, 0);
this.lstFiles.Name = "lstFiles";
this.lstFiles.ShowGroups = false;
this.lstFiles.ShowItemToolTips = true;
this.lstFiles.Size = new System.Drawing.Size(383, 412);
this.lstFiles.TabIndex = 0;
this.lstFiles.TileSize = new System.Drawing.Size(150, 50);
this.lstFiles.UseCompatibleStateImageBehavior = false;
this.lstFiles.SelectedIndexChanged += new System.EventHandler(this.lstFiles_SelectedIndexChanged);
this.lstFiles.DragDrop += new System.Windows.Forms.DragEventHandler(this.lstFiles_DragDrop);
this.lstFiles.DragEnter += new System.Windows.Forms.DragEventHandler(this.lstFiles_DragEnter);
this.lstFiles.KeyDown += new System.Windows.Forms.KeyEventHandler(this.lstFiles_KeyDown);
this.lstFiles.MouseClick += new System.Windows.Forms.MouseEventHandler(this.lstFiles_MouseClick);
this.lstFiles.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.lstFiles_MouseDoubleClick);
//
// chFilename
//
this.chFilename.Text = "Filename";
this.chFilename.Width = 182;
//
// chFileType
//
this.chFileType.Text = "Type";
this.chFileType.Width = 113;
//
// chSize
//
this.chSize.Text = "Size";
this.chSize.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.chSize.Width = 75;
//
// ofdAddon
//
this.ofdAddon.Filter = "Garry\'s Mod Addons|*.gma";
this.ofdAddon.Title = "Open addon file";
//
// tsFileOperations
//
this.tsFileOperations.Dock = System.Windows.Forms.DockStyle.Fill;
this.tsFileOperations.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.tsFileOperations.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsbAddFile,
this.tssExportHeaderSeparator,
this.tsbPullAll,
this.tsbDropAll,
this.tsddbViewOptions});
this.tsFileOperations.Location = new System.Drawing.Point(0, 0);
this.tsFileOperations.Name = "tsFileOperations";
this.tsFileOperations.Size = new System.Drawing.Size(552, 26);
this.tsFileOperations.TabIndex = 0;
//
// tsbAddFile
//
this.tsbAddFile.AutoToolTip = false;
this.tsbAddFile.Enabled = false;
this.tsbAddFile.Image = global::SharpGMad.Properties.Resources.add;
this.tsbAddFile.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbAddFile.Name = "tsbAddFile";
this.tsbAddFile.Size = new System.Drawing.Size(68, 23);
this.tsbAddFile.Text = "Add file";
this.tsbAddFile.Click += new System.EventHandler(this.tsbAddFile_Click);
//
// tssExportHeaderSeparator
//
this.tssExportHeaderSeparator.Name = "tssExportHeaderSeparator";
this.tssExportHeaderSeparator.Size = new System.Drawing.Size(6, 26);
//
// tsbPullAll
//
this.tsbPullAll.AutoToolTip = false;
this.tsbPullAll.Enabled = false;
this.tsbPullAll.Image = global::SharpGMad.Properties.Resources.pull_all;
this.tsbPullAll.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbPullAll.Name = "tsbPullAll";
this.tsbPullAll.Size = new System.Drawing.Size(138, 23);
this.tsbPullAll.Text = "Update exported files";
this.tsbPullAll.ToolTipText = "Updates all changes from external files into the addon";
this.tsbPullAll.Click += new System.EventHandler(this.tsbPullAll_Click);
//
// tsbDropAll
//
this.tsbDropAll.AutoToolTip = false;
this.tsbDropAll.Enabled = false;
this.tsbDropAll.Image = global::SharpGMad.Properties.Resources.drop_all;
this.tsbDropAll.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbDropAll.Name = "tsbDropAll";
this.tsbDropAll.Size = new System.Drawing.Size(94, 23);
this.tsbDropAll.Text = "Drop exports";
this.tsbDropAll.ToolTipText = "Deletes all exported files";
this.tsbDropAll.Click += new System.EventHandler(this.tsbDropAll_Click);
//
// tsddbViewOptions
//
this.tsddbViewOptions.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.tsddbViewOptions.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsmiViewLargeIcons,
this.tsmiViewSmallIcons,
this.tsmiViewDetails,
this.tsmiViewList,
this.tsmiViewTiles,
this.tssViewSeparator,
this.tsmiViewShowAllFiles,
this.tsmiViewShowFolderTree,
this.tsmiViewShowSubfolders});
this.tsddbViewOptions.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsddbViewOptions.Name = "tsddbViewOptions";
this.tsddbViewOptions.Size = new System.Drawing.Size(45, 23);
this.tsddbViewOptions.Text = "View";
this.tsddbViewOptions.ToolTipText = "Change the view of the file list";
//
// tsmiViewLargeIcons
//
this.tsmiViewLargeIcons.Image = global::SharpGMad.Properties.Resources.view_largeicons;
this.tsmiViewLargeIcons.Name = "tsmiViewLargeIcons";
this.tsmiViewLargeIcons.Size = new System.Drawing.Size(134, 22);
this.tsmiViewLargeIcons.Text = "Large Icons";
this.tsmiViewLargeIcons.Click += new System.EventHandler(this.tsmiViewElements_changeView);
//
// tsmiViewSmallIcons
//
this.tsmiViewSmallIcons.Image = global::SharpGMad.Properties.Resources.view_smallicons;
this.tsmiViewSmallIcons.Name = "tsmiViewSmallIcons";
this.tsmiViewSmallIcons.Size = new System.Drawing.Size(134, 22);
this.tsmiViewSmallIcons.Text = "Small Icons";
this.tsmiViewSmallIcons.Click += new System.EventHandler(this.tsmiViewElements_changeView);
//
// tsmiViewDetails
//
this.tsmiViewDetails.Image = global::SharpGMad.Properties.Resources.view_details;
this.tsmiViewDetails.Name = "tsmiViewDetails";
this.tsmiViewDetails.Size = new System.Drawing.Size(134, 22);
this.tsmiViewDetails.Text = "Details";
this.tsmiViewDetails.Click += new System.EventHandler(this.tsmiViewElements_changeView);
//
// tsmiViewList
//
this.tsmiViewList.Image = global::SharpGMad.Properties.Resources.view_list;
this.tsmiViewList.Name = "tsmiViewList";
this.tsmiViewList.Size = new System.Drawing.Size(134, 22);
this.tsmiViewList.Text = "List";
this.tsmiViewList.Click += new System.EventHandler(this.tsmiViewElements_changeView);
//
// tsmiViewTiles
//
this.tsmiViewTiles.Image = global::SharpGMad.Properties.Resources.view_tiles;
this.tsmiViewTiles.Name = "tsmiViewTiles";
this.tsmiViewTiles.Size = new System.Drawing.Size(134, 22);
this.tsmiViewTiles.Text = "Tiles";
this.tsmiViewTiles.Click += new System.EventHandler(this.tsmiViewElements_changeView);
//
// tssViewSeparator
//
this.tssViewSeparator.Name = "tssViewSeparator";
this.tssViewSeparator.Size = new System.Drawing.Size(131, 6);
//
// tsmiViewShowAllFiles
//
this.tsmiViewShowAllFiles.Image = global::SharpGMad.Properties.Resources.allfiles;
this.tsmiViewShowAllFiles.Name = "tsmiViewShowAllFiles";
this.tsmiViewShowAllFiles.Size = new System.Drawing.Size(134, 22);
this.tsmiViewShowAllFiles.Text = "All files";
this.tsmiViewShowAllFiles.ToolTipText = "Whether or not the file list view should show all files, not just current folder";
this.tsmiViewShowAllFiles.Click += new System.EventHandler(this.tsmiViewShowAllFiles_Click);
//
// tsmiViewShowFolderTree
//
this.tsmiViewShowFolderTree.Checked = true;
this.tsmiViewShowFolderTree.CheckState = System.Windows.Forms.CheckState.Checked;
this.tsmiViewShowFolderTree.Image = global::SharpGMad.Properties.Resources.foldertree;
this.tsmiViewShowFolderTree.Name = "tsmiViewShowFolderTree";
this.tsmiViewShowFolderTree.Size = new System.Drawing.Size(134, 22);
this.tsmiViewShowFolderTree.Text = "Folder tree";
this.tsmiViewShowFolderTree.Click += new System.EventHandler(this.tsmiViewShowFolderTree_Click);
//
// tsmiViewShowSubfolders
//
this.tsmiViewShowSubfolders.Checked = true;
this.tsmiViewShowSubfolders.CheckState = System.Windows.Forms.CheckState.Checked;
this.tsmiViewShowSubfolders.Image = global::SharpGMad.Properties.Resources.folder_s;
this.tsmiViewShowSubfolders.Name = "tsmiViewShowSubfolders";
this.tsmiViewShowSubfolders.Size = new System.Drawing.Size(134, 22);
this.tsmiViewShowSubfolders.Text = "Subfolders";
this.tsmiViewShowSubfolders.ToolTipText = "Switch whether the file list should show subfolders or not";
this.tsmiViewShowSubfolders.Click += new System.EventHandler(this.tsmiViewShowSubfolders_Click);
//
// pnlLeftSide
//
this.pnlLeftSide.Controls.Add(this.spcFoldersAndFiles);
this.pnlLeftSide.Controls.Add(this.pnlFileOpsToolbar);
this.pnlLeftSide.Controls.Add(this.ssStatus);
this.pnlLeftSide.Dock = System.Windows.Forms.DockStyle.Fill;
this.pnlLeftSide.Location = new System.Drawing.Point(0, 0);
this.pnlLeftSide.Name = "pnlLeftSide";
this.pnlLeftSide.Size = new System.Drawing.Size(552, 443);
this.pnlLeftSide.TabIndex = 11;
//
// spcFoldersAndFiles
//
this.spcFoldersAndFiles.Dock = System.Windows.Forms.DockStyle.Fill;
this.spcFoldersAndFiles.Location = new System.Drawing.Point(0, 26);
this.spcFoldersAndFiles.Name = "spcFoldersAndFiles";
//
// spcFoldersAndFiles.Panel1
//
this.spcFoldersAndFiles.Panel1.Controls.Add(this.tvFolders);
//
// spcFoldersAndFiles.Panel2
//
this.spcFoldersAndFiles.Panel2.Controls.Add(this.lstFiles);
this.spcFoldersAndFiles.Size = new System.Drawing.Size(552, 412);
this.spcFoldersAndFiles.SplitterDistance = 165;
this.spcFoldersAndFiles.TabIndex = 5;
//
// tvFolders
//
this.tvFolders.Dock = System.Windows.Forms.DockStyle.Fill;
this.tvFolders.Location = new System.Drawing.Point(0, 0);
this.tvFolders.Name = "tvFolders";
this.tvFolders.PathSeparator = "/";
this.tvFolders.ShowRootLines = false;
this.tvFolders.Size = new System.Drawing.Size(165, 412);
this.tvFolders.TabIndex = 4;
this.tvFolders.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tvFolders_AfterSelect);
//
// pnlFileOpsToolbar
//
this.pnlFileOpsToolbar.Controls.Add(this.tsFileOperations);
this.pnlFileOpsToolbar.Dock = System.Windows.Forms.DockStyle.Top;
this.pnlFileOpsToolbar.Location = new System.Drawing.Point(0, 0);
this.pnlFileOpsToolbar.Name = "pnlFileOpsToolbar";
this.pnlFileOpsToolbar.Size = new System.Drawing.Size(552, 26);
this.pnlFileOpsToolbar.TabIndex = 0;
//
// ssStatus
//
this.ssStatus.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsslStatus});
this.ssStatus.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.Flow;
this.ssStatus.Location = new System.Drawing.Point(0, 438);
this.ssStatus.Name = "ssStatus";
this.ssStatus.Size = new System.Drawing.Size(552, 5);
this.ssStatus.SizingGrip = false;
this.ssStatus.TabIndex = 3;
//
// tsslStatus
//
this.tsslStatus.Name = "tsslStatus";
this.tsslStatus.Size = new System.Drawing.Size(0, 0);
//
// pnlForm
//
this.pnlForm.Controls.Add(this.pnlLeftSide);
this.pnlForm.Controls.Add(this.pnlRightSide);
this.pnlForm.Dock = System.Windows.Forms.DockStyle.Fill;
this.pnlForm.Location = new System.Drawing.Point(0, 25);
this.pnlForm.Name = "pnlForm";
this.pnlForm.Size = new System.Drawing.Size(759, 443);
this.pnlForm.TabIndex = 12;
//
// pnlRightSide
//
this.pnlRightSide.Controls.Add(this.txtMetadataDescription);
this.pnlRightSide.Controls.Add(this.tsMetadata);
this.pnlRightSide.Controls.Add(this.lblDescription);
this.pnlRightSide.Controls.Add(this.cmbMetadataTag1);
this.pnlRightSide.Controls.Add(this.cmbMetadataTag2);
this.pnlRightSide.Controls.Add(this.lblTags);
this.pnlRightSide.Controls.Add(this.cmbMetadataType);
this.pnlRightSide.Controls.Add(this.lblType);
this.pnlRightSide.Controls.Add(this.txtMetadataTitle);
this.pnlRightSide.Controls.Add(this.lblTitle);
this.pnlRightSide.Dock = System.Windows.Forms.DockStyle.Right;
this.pnlRightSide.Location = new System.Drawing.Point(552, 0);
this.pnlRightSide.Name = "pnlRightSide";
this.pnlRightSide.Size = new System.Drawing.Size(207, 443);
this.pnlRightSide.TabIndex = 12;
//
// txtMetadataDescription
//
this.txtMetadataDescription.AcceptsTab = true;
this.txtMetadataDescription.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.txtMetadataDescription.Location = new System.Drawing.Point(20, 153);
this.txtMetadataDescription.Multiline = true;
this.txtMetadataDescription.Name = "txtMetadataDescription";
this.txtMetadataDescription.ReadOnly = true;
this.txtMetadataDescription.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtMetadataDescription.Size = new System.Drawing.Size(184, 278);
this.txtMetadataDescription.TabIndex = 7;
//
// tsMetadata
//
this.tsMetadata.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.tsMetadata.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsbUpdateMetadata,
this.tsbDiscardMetadataChanges});
this.tsMetadata.Location = new System.Drawing.Point(0, 0);
this.tsMetadata.Name = "tsMetadata";
this.tsMetadata.Size = new System.Drawing.Size(207, 25);
this.tsMetadata.TabIndex = 10;
//
// tsbUpdateMetadata
//
this.tsbUpdateMetadata.AutoToolTip = false;
this.tsbUpdateMetadata.Enabled = false;
this.tsbUpdateMetadata.Image = global::SharpGMad.Properties.Resources.metadata;
this.tsbUpdateMetadata.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbUpdateMetadata.Name = "tsbUpdateMetadata";
this.tsbUpdateMetadata.Size = new System.Drawing.Size(118, 22);
this.tsbUpdateMetadata.Text = "Update metadata";
this.tsbUpdateMetadata.Click += new System.EventHandler(this.tsbUpdateMetadata_Click);
//
// tsbDiscardMetadataChanges
//
this.tsbDiscardMetadataChanges.Enabled = false;
this.tsbDiscardMetadataChanges.Image = global::SharpGMad.Properties.Resources.discard;
this.tsbDiscardMetadataChanges.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbDiscardMetadataChanges.Name = "tsbDiscardMetadataChanges";
this.tsbDiscardMetadataChanges.Size = new System.Drawing.Size(66, 22);
this.tsbDiscardMetadataChanges.Text = "Discard";
this.tsbDiscardMetadataChanges.ToolTipText = "Discard metadata changes";
this.tsbDiscardMetadataChanges.Visible = false;
this.tsbDiscardMetadataChanges.Click += new System.EventHandler(this.tsbDiscardMetadataChanges_Click);
//
// lblDescription
//
this.lblDescription.AutoSize = true;
this.lblDescription.Location = new System.Drawing.Point(6, 136);
this.lblDescription.Name = "lblDescription";
this.lblDescription.Size = new System.Drawing.Size(63, 13);
this.lblDescription.TabIndex = 6;
this.lblDescription.Text = "Description:";
//
// cmbMetadataTag1
//
this.cmbMetadataTag1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbMetadataTag1.Enabled = false;
this.cmbMetadataTag1.FormattingEnabled = true;
this.cmbMetadataTag1.Location = new System.Drawing.Point(20, 113);
this.cmbMetadataTag1.Name = "cmbMetadataTag1";
this.cmbMetadataTag1.Size = new System.Drawing.Size(92, 21);
this.cmbMetadataTag1.Sorted = true;
this.cmbMetadataTag1.TabIndex = 12;
//
// cmbMetadataTag2
//
this.cmbMetadataTag2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbMetadataTag2.Enabled = false;
this.cmbMetadataTag2.FormattingEnabled = true;
this.cmbMetadataTag2.Location = new System.Drawing.Point(112, 113);
this.cmbMetadataTag2.Name = "cmbMetadataTag2";
this.cmbMetadataTag2.Size = new System.Drawing.Size(92, 21);
this.cmbMetadataTag2.Sorted = true;
this.cmbMetadataTag2.TabIndex = 13;
//
// lblTags
//
this.lblTags.AutoSize = true;
this.lblTags.Location = new System.Drawing.Point(6, 97);
this.lblTags.Name = "lblTags";
this.lblTags.Size = new System.Drawing.Size(34, 13);
this.lblTags.TabIndex = 4;
this.lblTags.Text = "Tags:";
//
// cmbMetadataType
//
this.cmbMetadataType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbMetadataType.Enabled = false;
this.cmbMetadataType.FormattingEnabled = true;
this.cmbMetadataType.Location = new System.Drawing.Point(20, 73);
this.cmbMetadataType.Name = "cmbMetadataType";
this.cmbMetadataType.Size = new System.Drawing.Size(184, 21);
this.cmbMetadataType.Sorted = true;
this.cmbMetadataType.TabIndex = 11;
//
// lblType
//
this.lblType.AutoSize = true;
this.lblType.Location = new System.Drawing.Point(6, 58);
this.lblType.Name = "lblType";
this.lblType.Size = new System.Drawing.Size(34, 13);
this.lblType.TabIndex = 2;
this.lblType.Text = "Type:";
//
// txtMetadataTitle
//
this.txtMetadataTitle.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.txtMetadataTitle.Location = new System.Drawing.Point(20, 42);
this.txtMetadataTitle.Name = "txtMetadataTitle";
this.txtMetadataTitle.ReadOnly = true;
this.txtMetadataTitle.Size = new System.Drawing.Size(184, 13);
this.txtMetadataTitle.TabIndex = 1;
//
// lblTitle
//
this.lblTitle.AutoSize = true;
this.lblTitle.Location = new System.Drawing.Point(6, 26);
this.lblTitle.Name = "lblTitle";
this.lblTitle.Size = new System.Drawing.Size(30, 13);
this.lblTitle.TabIndex = 0;
this.lblTitle.Text = "Title:";
//
// tsToolbar
//
this.tsToolbar.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.tsToolbar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsbCreateAddon,
this.tsbOpenAddon,
this.tsbSaveAddon,
this.tssAddonSeparator,
this.tsddbLegacy});
this.tsToolbar.Location = new System.Drawing.Point(0, 0);
this.tsToolbar.Name = "tsToolbar";
this.tsToolbar.Size = new System.Drawing.Size(759, 25);
this.tsToolbar.TabIndex = 13;
//
// tsbCreateAddon
//
this.tsbCreateAddon.AutoToolTip = false;
this.tsbCreateAddon.Image = global::SharpGMad.Properties.Resources.newaddon;
this.tsbCreateAddon.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbCreateAddon.Name = "tsbCreateAddon";
this.tsbCreateAddon.Size = new System.Drawing.Size(86, 22);
this.tsbCreateAddon.Text = "Create new";
this.tsbCreateAddon.Click += new System.EventHandler(this.tsbCreateAddon_Click);
//
// tsbOpenAddon
//
this.tsbOpenAddon.AutoToolTip = false;
this.tsbOpenAddon.Image = global::SharpGMad.Properties.Resources.open;
this.tsbOpenAddon.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbOpenAddon.Name = "tsbOpenAddon";
this.tsbOpenAddon.Size = new System.Drawing.Size(56, 22);
this.tsbOpenAddon.Text = "Open";
this.tsbOpenAddon.Click += new System.EventHandler(this.tsbOpenAddon_Click);
//
// tsbSaveAddon
//
this.tsbSaveAddon.AutoToolTip = false;
this.tsbSaveAddon.Enabled = false;
this.tsbSaveAddon.Image = global::SharpGMad.Properties.Resources.save;
this.tsbSaveAddon.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbSaveAddon.Name = "tsbSaveAddon";
this.tsbSaveAddon.Size = new System.Drawing.Size(51, 22);
this.tsbSaveAddon.Text = "Save";
this.tsbSaveAddon.Click += new System.EventHandler(this.tsbSaveAddon_Click);
//
// tssAddonSeparator
//
this.tssAddonSeparator.Name = "tssAddonSeparator";
this.tssAddonSeparator.Size = new System.Drawing.Size(6, 25);
//
// tsddbLegacy
//
this.tsddbLegacy.AutoToolTip = false;
this.tsddbLegacy.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsmiLegacyCreate,
this.tsmiLegacyExtract});
this.tsddbLegacy.Image = global::SharpGMad.Properties.Resources.legacy;
this.tsddbLegacy.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsddbLegacy.Name = "tsddbLegacy";
this.tsddbLegacy.Size = new System.Drawing.Size(132, 22);
this.tsddbLegacy.Text = "Legacy operations";
this.tsddbLegacy.ToolTipText = "Access the legacy wrapper windows";
//
// tsmiLegacyCreate
//
this.tsmiLegacyCreate.Image = global::SharpGMad.Properties.Resources.create;
this.tsmiLegacyCreate.Name = "tsmiLegacyCreate";
this.tsmiLegacyCreate.Size = new System.Drawing.Size(171, 22);
this.tsmiLegacyCreate.Text = "Create from folder";
this.tsmiLegacyCreate.ToolTipText = "Use the legacy method to compile a folder into an addon";
this.tsmiLegacyCreate.Click += new System.EventHandler(this.tsmiLegacyCreate_Click);
//
// tsmiLegacyExtract
//
this.tsmiLegacyExtract.Image = global::SharpGMad.Properties.Resources.extract;
this.tsmiLegacyExtract.Name = "tsmiLegacyExtract";
this.tsmiLegacyExtract.Size = new System.Drawing.Size(171, 22);
this.tsmiLegacyExtract.Text = "Extract to folder";
this.tsmiLegacyExtract.ToolTipText = "Use the legacy method to fully unpack an addon to a folder";
this.tsmiLegacyExtract.Click += new System.EventHandler(this.tsmiLegacyExtract_Click);
//
// ofdAddFile
//
this.ofdAddFile.Title = "Add file";
//
// sfdAddon
//
this.sfdAddon.DefaultExt = "gma";
this.sfdAddon.Filter = "Garry\'s Mod Addons|*.gma";
this.sfdAddon.Title = "Create new addon as";
//
// sfdExportFile
//
this.sfdExportFile.Filter = "All files|*.*";
//
// tssExportSeparator
//
this.tssExportSeparator.Name = "tssExportSeparator";
this.tssExportSeparator.Size = new System.Drawing.Size(149, 6);
//
// cmsFileEntry
//
this.cmsFileEntry.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsmFileShellExec,
this.tsmFileExtract,
this.tsmFileRemove,
this.tssExportSeparator,
this.tsmFileExportTo,
this.tsmFilePull,
this.tsmFileOpenExport,
this.tsmFileDropExport});
this.cmsFileEntry.Name = "cmsFileEntry";
this.cmsFileEntry.Size = new System.Drawing.Size(153, 186);
//
// tsmFileRemove
//
this.tsmFileRemove.Image = global::SharpGMad.Properties.Resources.drop;
this.tsmFileRemove.Name = "tsmFileRemove";
this.tsmFileRemove.Size = new System.Drawing.Size(152, 22);
this.tsmFileRemove.Text = "Remove";
this.tsmFileRemove.Click += new System.EventHandler(this.tsmFileRemove_Click);
//
// tsmFileExtract
//
this.tsmFileExtract.Image = global::SharpGMad.Properties.Resources.extract;
this.tsmFileExtract.Name = "tsmFileExtract";
this.tsmFileExtract.Size = new System.Drawing.Size(152, 22);
this.tsmFileExtract.Text = "Extract";
this.tsmFileExtract.ToolTipText = "Save the selected file somewhere on your computer";
this.tsmFileExtract.Click += new System.EventHandler(this.tsmFileExtract_Click);
//
// tsmFileShellExec
//
this.tsmFileShellExec.Image = global::SharpGMad.Properties.Resources.execute;
this.tsmFileShellExec.Name = "tsmFileShellExec";
this.tsmFileShellExec.Size = new System.Drawing.Size(152, 22);
this.tsmFileShellExec.Text = "Shell execute";
this.tsmFileShellExec.ToolTipText = "Run the selected file like it was opened in Explorer";
this.tsmFileShellExec.Click += new System.EventHandler(this.tsmFileShellExec_Click);
//
// tsmFileExportTo
//
this.tsmFileExportTo.Image = global::SharpGMad.Properties.Resources.export;
this.tsmFileExportTo.Name = "tsmFileExportTo";
this.tsmFileExportTo.Size = new System.Drawing.Size(152, 22);
this.tsmFileExportTo.Text = "Export to...";
this.tsmFileExportTo.ToolTipText = "Export the selected file to somewhere on your computer and set up a realtime chan" +
"ge-watch. Changed files will be purple.";
this.tsmFileExportTo.Click += new System.EventHandler(this.tsmFileExportTo_Click);
//
// tsmFilePull
//
this.tsmFilePull.Image = global::SharpGMad.Properties.Resources.pull;
this.tsmFilePull.Name = "tsmFilePull";
this.tsmFilePull.Size = new System.Drawing.Size(152, 22);
this.tsmFilePull.Text = "Update";
this.tsmFilePull.ToolTipText = "Update this file with the changes from the exported file on your computer";
this.tsmFilePull.Click += new System.EventHandler(this.tsmFilePull_Click);
//
// tsmFileOpenExport
//
this.tsmFileOpenExport.Image = global::SharpGMad.Properties.Resources.open_export;
this.tsmFileOpenExport.Name = "tsmFileOpenExport";
this.tsmFileOpenExport.Size = new System.Drawing.Size(152, 22);
this.tsmFileOpenExport.Text = "Open export";
this.tsmFileOpenExport.ToolTipText = "Opens the exported file from your filesystem";
this.tsmFileOpenExport.Click += new System.EventHandler(this.tsmFileOpenExport_Click);
//
// tsmFileDropExport
//
this.tsmFileDropExport.Image = global::SharpGMad.Properties.Resources.drop_export;
this.tsmFileDropExport.Name = "tsmFileDropExport";
this.tsmFileDropExport.Size = new System.Drawing.Size(152, 22);
this.tsmFileDropExport.Text = "Drop export";
this.tsmFileDropExport.ToolTipText = "Delete the exported file from your computer";
this.tsmFileDropExport.Click += new System.EventHandler(this.tsmFileDropExport_Click);
//
// Main
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(759, 468);
this.Controls.Add(this.pnlForm);
this.Controls.Add(this.tsToolbar);
this.Name = "Main";
this.Text = "SharpGMad";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Main_FormClosing);
this.Load += new System.EventHandler(this.Main_Load);
this.Resize += new System.EventHandler(this.Main_Resize);
this.tsFileOperations.ResumeLayout(false);
this.tsFileOperations.PerformLayout();
this.pnlLeftSide.ResumeLayout(false);
this.pnlLeftSide.PerformLayout();
this.spcFoldersAndFiles.Panel1.ResumeLayout(false);
this.spcFoldersAndFiles.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.spcFoldersAndFiles)).EndInit();
this.spcFoldersAndFiles.ResumeLayout(false);
this.pnlFileOpsToolbar.ResumeLayout(false);
this.pnlFileOpsToolbar.PerformLayout();
this.ssStatus.ResumeLayout(false);
this.ssStatus.PerformLayout();
this.pnlForm.ResumeLayout(false);
this.pnlRightSide.ResumeLayout(false);
this.pnlRightSide.PerformLayout();
this.tsMetadata.ResumeLayout(false);
this.tsMetadata.PerformLayout();
this.tsToolbar.ResumeLayout(false);
this.tsToolbar.PerformLayout();
this.cmsFileEntry.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ListView lstFiles;
private System.Windows.Forms.OpenFileDialog ofdAddon;
private System.Windows.Forms.ToolStrip tsFileOperations;
private System.Windows.Forms.Panel pnlLeftSide;
private System.Windows.Forms.Panel pnlFileOpsToolbar;
private System.Windows.Forms.Panel pnlForm;
private System.Windows.Forms.Panel pnlRightSide;
private System.Windows.Forms.ToolStrip tsToolbar;
private System.Windows.Forms.ToolStripButton tsbCreateAddon;
private System.Windows.Forms.ToolStripButton tsbOpenAddon;
private System.Windows.Forms.ToolStripButton tsbSaveAddon;
private System.Windows.Forms.ToolStripSeparator tssAddonSeparator;
private System.Windows.Forms.ToolStripDropDownButton tsddbLegacy;
private System.Windows.Forms.ToolStripMenuItem tsmiLegacyCreate;
private System.Windows.Forms.ToolStripMenuItem tsmiLegacyExtract;
private System.Windows.Forms.ToolStripButton tsbAddFile;
private System.Windows.Forms.Label lblTitle;
private System.Windows.Forms.TextBox txtMetadataTitle;
private System.Windows.Forms.TextBox txtMetadataDescription;
private System.Windows.Forms.Label lblDescription;
private System.Windows.Forms.ComboBox cmbMetadataTag1;
private System.Windows.Forms.ComboBox cmbMetadataTag2;
private System.Windows.Forms.Label lblTags;
private System.Windows.Forms.ComboBox cmbMetadataType;
private System.Windows.Forms.Label lblType;
private System.Windows.Forms.ToolStrip tsMetadata;
private System.Windows.Forms.ToolStripButton tsbUpdateMetadata;
private System.Windows.Forms.OpenFileDialog ofdAddFile;
private System.Windows.Forms.SaveFileDialog sfdAddon;
private System.Windows.Forms.ToolStripButton tsbPullAll;
private System.Windows.Forms.SaveFileDialog sfdExportFile;
private System.Windows.Forms.ToolStripSeparator tssExportHeaderSeparator;
private System.Windows.Forms.ToolStripButton tsbDropAll;
private System.Windows.Forms.ToolStripMenuItem tsmFileRemove;
private System.Windows.Forms.ToolStripSeparator tssExportSeparator;
private System.Windows.Forms.ToolStripMenuItem tsmFileExportTo;
private System.Windows.Forms.ToolStripMenuItem tsmFilePull;
private System.Windows.Forms.ToolStripMenuItem tsmFileDropExport;
private System.Windows.Forms.ContextMenuStrip cmsFileEntry;
private System.Windows.Forms.ToolStripMenuItem tsmFileExtract;
private System.Windows.Forms.FolderBrowserDialog fbdFileExtractMulti;
private System.Windows.Forms.ToolStripMenuItem tsmFileShellExec;
private System.Windows.Forms.ToolStripButton tsbDiscardMetadataChanges;
private System.Windows.Forms.StatusStrip ssStatus;
private System.Windows.Forms.ToolStripStatusLabel tsslStatus;
private System.Windows.Forms.TreeView tvFolders;
private System.Windows.Forms.SplitContainer spcFoldersAndFiles;
private System.Windows.Forms.ToolStripDropDownButton tsddbViewOptions;
private System.Windows.Forms.ToolStripMenuItem tsmiViewLargeIcons;
private System.Windows.Forms.ToolStripMenuItem tsmiViewSmallIcons;
private System.Windows.Forms.ToolStripMenuItem tsmiViewDetails;
private System.Windows.Forms.ToolStripMenuItem tsmiViewList;
private System.Windows.Forms.ToolStripMenuItem tsmiViewTiles;
private System.Windows.Forms.ToolStripSeparator tssViewSeparator;
private System.Windows.Forms.ToolStripMenuItem tsmiViewShowSubfolders;
private System.Windows.Forms.ColumnHeader chFilename;
private System.Windows.Forms.ColumnHeader chFileType;
private System.Windows.Forms.ColumnHeader chSize;
private System.Windows.Forms.ToolStripMenuItem tsmiViewShowFolderTree;
private System.Windows.Forms.ToolStripMenuItem tsmiViewShowAllFiles;
private System.Windows.Forms.ToolStripMenuItem tsmFileOpenExport;
}
}
| |
#define USE_TRACING
#define DEBUG
using System;
using System.Collections;
using System.Configuration;
using System.IO;
using System.Xml;
using NUnit.Framework;
namespace Google.GData.Client.UnitTests
{
[TestFixture]
public class BaseTestClass
{
/// <summary>the setup method</summary>
[SetUp]
public virtual void InitTest()
{
Tracing.InitTracing();
defaultHost = "http://localhost";
strRemoteHost = null;
externalHosts = null;
iIterations = 10;
if (this.factory == null)
{
GDataLoggingRequestFactory factory = new GDataLoggingRequestFactory(ServiceName, ApplicationName);
this.factory = factory;
}
ReadConfigFile();
}
/// <summary>the end it all method</summary>
[TearDown]
public virtual void EndTest()
{
Tracing.ExitTracing();
}
/// <summary>default extension for temp files. They do get removed after a successful run</summary>
protected static string defExt = ".log";
/// <summary>holds the default localhost address</summary>
protected string defaultHost;
/// <summary>holds the default external host</summary>
protected string strRemoteHost;
/// <summary>holds the default remote host address</summary>
protected IDictionary externalHosts;
/// <summary>holds the number of iterations for the tests</summary>
protected int iIterations;
/// <summary>holds the logging factory</summary>
protected IGDataRequestFactory factory;
/// <summary>holds the configuration of the test found in the dll.config file</summary>
protected IDictionary unitTestConfiguration;
/// <summary>holds path to resources (xml files, jpgs) that are used during the unittests</summary>
protected string resourcePath = "";
public virtual string ServiceName
{
get { return "cl"; }
}
public virtual string ApplicationName
{
get { return "UnitTests"; }
}
/// <summary>private void ReadConfigFile()</summary>
/// <returns> </returns>
protected virtual void ReadConfigFile()
{
unitTestConfiguration = (IDictionary) ConfigurationManager.GetSection("unitTestSection");
// no need to go further if the configuration file is needed.
if (unitTestConfiguration == null)
throw new FileNotFoundException("The DLL configuration file wasn't found, aborting.");
if (unitTestConfiguration.Contains("defHost"))
{
defaultHost = (string) unitTestConfiguration["defHost"];
Tracing.TraceInfo("Read defaultHost value: " + defaultHost);
}
if (unitTestConfiguration.Contains("defRemoteHost"))
{
strRemoteHost = (string) unitTestConfiguration["defRemoteHost"];
Tracing.TraceInfo("Read default remote host value: " + strRemoteHost);
}
if (unitTestConfiguration.Contains("iteration"))
{
iIterations = int.Parse((string) unitTestConfiguration["iteration"]);
}
if (unitTestConfiguration.Contains("resourcePath"))
{
resourcePath = (string) unitTestConfiguration["resourcePath"];
}
if (unitTestConfiguration.Contains("requestlogging"))
{
bool flag = bool.Parse((string) unitTestConfiguration["requestlogging"]);
if (!flag)
{
// we are creating the logging factory by default. If
// tester set's it off, create the standard factory.
factory = new GDataGAuthRequestFactory(ServiceName, ApplicationName);
}
}
externalHosts = (IDictionary) ConfigurationManager.GetSection("unitTestExternalHosts");
}
/// <summary>private string CreateDumpFileName(string baseName)</summary>
/// <param name="baseName">the basename</param>
/// <returns>the complete filename for file creation</returns>
protected string CreateDumpFileName(string baseName)
{
return Path.GetTempPath() + Path.DirectorySeparatorChar + baseName + defExt;
}
/// <summary>private string CreateUriFileName(string baseName)</summary>
/// <param name="baseName">the basename</param>
/// <returns>the complete Uri name for file access</returns>
protected string CreateUriLogFileName(string baseName)
{
return CreateUriFileName(baseName + defExt);
}
/// <summary>private string CreateUriFileName(string baseName)</summary>
/// <param name="baseName">the basename</param>
/// <returns>the complete Uri name for file access</returns>
protected string CreateUriFileName(string fileName)
{
string fileAndPath = Path.GetTempPath() + "/" + fileName;
return CreateUri(fileAndPath);
}
/// <summary>private string CreateUriFileName(string baseName)</summary>
/// <param name="baseName">the basename</param>
/// <returns>the complete Uri name for file access</returns>
protected string CreateUri(string fileAndPathName)
{
string strUri = null;
try
{
UriBuilder temp = new UriBuilder("file", "localhost", 0, fileAndPathName);
strUri = temp.Uri.AbsoluteUri;
}
catch (UriFormatException)
{
UriBuilder temp = new UriBuilder("file", "", 0, fileAndPathName);
strUri = temp.Uri.AbsoluteUri;
}
return (strUri);
}
/// <summary>
/// eventhandling. called when a new entry is parsed
/// </summary>
/// <param name="sender"> the object which send the event</param>
/// <param name="e">FeedParserEventArguments, holds the feedentry</param>
/// <returns> </returns>
protected void OnParsedNewEntry(object sender, FeedParserEventArgs e)
{
if (e == null)
{
throw new ArgumentNullException("e");
}
if (e.CreatingEntry)
{
Tracing.TraceMsg("\t top level event dispatcher - new Entry");
e.Entry = new MyEntry();
}
}
/// <summary>eventhandler - called for new extension element</summary>
/// <param name="sender"> the object which send the event</param>
/// <param name="e">FeedParserEventArguments, holds the feedentry</param>
/// <returns> </returns>
protected void OnNewExtensionElement(object sender, ExtensionElementEventArgs e)
{
// by default, if our event chain is not hooked, the underlying parser will add it
Tracing.TraceCall("received new extension element notification");
Tracing.Assert(e != null, "e should not be null");
if (e == null)
{
throw new ArgumentNullException("e");
}
Tracing.TraceMsg("\t top level event = new extension");
if (string.Compare(e.ExtensionElement.NamespaceURI, "http://purl.org/dc/elements/1.1/", true) == 0)
{
// found DC namespace
Tracing.TraceMsg("\t top level event = new DC extension");
if (e.ExtensionElement.LocalName == "date")
{
MyEntry entry = e.Base as MyEntry;
if (entry != null)
{
entry.DCDate = DateTime.Parse(e.ExtensionElement.InnerText);
e.DiscardEntry = true;
}
}
}
}
}
/// <summary>
/// this is just a dummy class to test new tests. Use the Ignore on the fixutre to disable or enable one class
/// </summary>
[TestFixture]
public class InDevTests : IBaseWalkerAction
{
/// <summary>
/// the setup method
/// </summary>
[SetUp]
public virtual void InitTest()
{
}
/// <summary>public bool Go(AtomBase baseObject)</summary>
/// <param name="baseObject">object to do something with </param>
/// <returns>true if we are done walking the tree</returns>
public bool Go(AtomBase baseObject)
{
Tracing.TraceInfo("inside go: " + baseObject + " is dirty set: " + baseObject.IsDirty());
return false;
}
/// <summary>
/// creates a number or rows and delets them again
/// </summary>
[Test]
public void TestIt()
{
Tracing.TraceMsg("Entering TestIt");
}
}
/// <summary>
/// a subclass that is used to represent the tree in the extension testcase
/// </summary>
public class MyEntry : AtomEntry
{
/// <summary>
/// accessor method public DateTime DCDate
/// </summary>
/// <returns> </returns>
public DateTime DCDate { get; set; }
/// <summary>
/// saves the inner state of the element
/// </summary>
/// <param name="writer">
/// the xmlWriter to save into
/// </param>
protected override void SaveInnerXml(XmlWriter writer)
{
base.SaveInnerXml(writer);
writer.WriteElementString("date", "http://purl.org/dc/elements/1.1/", DCDate.ToString());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
namespace MS.Internal.Xml.XPath
{
internal sealed class StringFunctions : ValueQuery
{
private Function.FunctionType _funcType;
private IList<Query> _argList;
public StringFunctions(Function.FunctionType funcType, IList<Query> argList)
{
Debug.Assert(argList != null, "Use 'new Query[]{}' instead.");
_funcType = funcType;
_argList = argList;
}
private StringFunctions(StringFunctions other) : base(other)
{
_funcType = other._funcType;
Query[] tmp = new Query[other._argList.Count];
{
for (int i = 0; i < tmp.Length; i++)
{
tmp[i] = Clone(other._argList[i]);
}
}
_argList = tmp;
}
public override void SetXsltContext(XsltContext context)
{
for (int i = 0; i < _argList.Count; i++)
{
_argList[i].SetXsltContext(context);
}
}
public override object Evaluate(XPathNodeIterator nodeIterator)
{
switch (_funcType)
{
case Function.FunctionType.FuncString: return toString(nodeIterator);
case Function.FunctionType.FuncConcat: return Concat(nodeIterator);
case Function.FunctionType.FuncStartsWith: return StartsWith(nodeIterator);
case Function.FunctionType.FuncContains: return Contains(nodeIterator);
case Function.FunctionType.FuncSubstringBefore: return SubstringBefore(nodeIterator);
case Function.FunctionType.FuncSubstringAfter: return SubstringAfter(nodeIterator);
case Function.FunctionType.FuncSubstring: return Substring(nodeIterator);
case Function.FunctionType.FuncStringLength: return StringLength(nodeIterator);
case Function.FunctionType.FuncNormalize: return Normalize(nodeIterator);
case Function.FunctionType.FuncTranslate: return Translate(nodeIterator);
}
return string.Empty;
}
internal static string toString(double num)
{
return num.ToString("R", NumberFormatInfo.InvariantInfo);
}
internal static string toString(bool b)
{
return b ? "true" : "false";
}
private string toString(XPathNodeIterator nodeIterator)
{
if (_argList.Count > 0)
{
object argVal = _argList[0].Evaluate(nodeIterator);
switch (GetXPathType(argVal))
{
case XPathResultType.NodeSet:
XPathNavigator value = _argList[0].Advance();
return value != null ? value.Value : string.Empty;
case XPathResultType.String:
return (string)argVal;
case XPathResultType.Boolean:
return ((bool)argVal) ? "true" : "false";
case XPathResultType_Navigator:
return ((XPathNavigator)argVal).Value;
default:
Debug.Assert(GetXPathType(argVal) == XPathResultType.Number);
return toString((double)argVal);
}
}
return nodeIterator.Current.Value;
}
public override XPathResultType StaticType
{
get
{
if (_funcType == Function.FunctionType.FuncStringLength)
{
return XPathResultType.Number;
}
if (
_funcType == Function.FunctionType.FuncStartsWith ||
_funcType == Function.FunctionType.FuncContains
)
{
return XPathResultType.Boolean;
}
return XPathResultType.String;
}
}
private string Concat(XPathNodeIterator nodeIterator)
{
int count = 0;
StringBuilder s = new StringBuilder();
while (count < _argList.Count)
{
s.Append(_argList[count++].Evaluate(nodeIterator).ToString());
}
return s.ToString();
}
private bool StartsWith(XPathNodeIterator nodeIterator)
{
string s1 = _argList[0].Evaluate(nodeIterator).ToString();
string s2 = _argList[1].Evaluate(nodeIterator).ToString();
return s1.Length >= s2.Length && string.CompareOrdinal(s1, 0, s2, 0, s2.Length) == 0;
}
private static readonly CompareInfo s_compareInfo = CultureInfo.InvariantCulture.CompareInfo;
private bool Contains(XPathNodeIterator nodeIterator)
{
string s1 = _argList[0].Evaluate(nodeIterator).ToString();
string s2 = _argList[1].Evaluate(nodeIterator).ToString();
return s_compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal) >= 0;
}
private string SubstringBefore(XPathNodeIterator nodeIterator)
{
string s1 = _argList[0].Evaluate(nodeIterator).ToString();
string s2 = _argList[1].Evaluate(nodeIterator).ToString();
if (s2.Length == 0) { return s2; }
int idx = s_compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal);
return (idx < 1) ? string.Empty : s1.Substring(0, idx);
}
private string SubstringAfter(XPathNodeIterator nodeIterator)
{
string s1 = _argList[0].Evaluate(nodeIterator).ToString();
string s2 = _argList[1].Evaluate(nodeIterator).ToString();
if (s2.Length == 0) { return s1; }
int idx = s_compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal);
return (idx < 0) ? string.Empty : s1.Substring(idx + s2.Length);
}
private string Substring(XPathNodeIterator nodeIterator)
{
string str1 = _argList[0].Evaluate(nodeIterator).ToString();
double num = XmlConvert.XPathRound(XmlConvert.ToXPathDouble(_argList[1].Evaluate(nodeIterator))) - 1;
if (double.IsNaN(num) || str1.Length <= num)
{
return string.Empty;
}
if (_argList.Count == 3)
{
double num1 = XmlConvert.XPathRound(XmlConvert.ToXPathDouble(_argList[2].Evaluate(nodeIterator)));
if (double.IsNaN(num1))
{
return string.Empty;
}
if (num < 0 || num1 < 0)
{
num1 = num + num1;
// NOTE: condition is true for NaN
if (!(num1 > 0))
{
return string.Empty;
}
num = 0;
}
double maxlength = str1.Length - num;
if (num1 > maxlength)
{
num1 = maxlength;
}
return str1.Substring((int)num, (int)num1);
}
if (num < 0)
{
num = 0;
}
return str1.Substring((int)num);
}
private double StringLength(XPathNodeIterator nodeIterator)
{
if (_argList.Count > 0)
{
return _argList[0].Evaluate(nodeIterator).ToString().Length;
}
return nodeIterator.Current.Value.Length;
}
private string Normalize(XPathNodeIterator nodeIterator)
{
string value;
if (_argList.Count > 0)
{
value = _argList[0].Evaluate(nodeIterator).ToString();
}
else
{
value = nodeIterator.Current.Value;
}
int modifyPos = -1;
char[] chars = value.ToCharArray();
bool firstSpace = false; // Start false to trim the beginning
XmlCharType xmlCharType = XmlCharType.Instance;
for (int comparePos = 0; comparePos < chars.Length; comparePos++)
{
if (!xmlCharType.IsWhiteSpace(chars[comparePos]))
{
firstSpace = true;
modifyPos++;
chars[modifyPos] = chars[comparePos];
}
else if (firstSpace)
{
firstSpace = false;
modifyPos++;
chars[modifyPos] = ' ';
}
}
// Trim end
if (modifyPos > -1 && chars[modifyPos] == ' ')
modifyPos--;
return new string(chars, 0, modifyPos + 1);
}
private string Translate(XPathNodeIterator nodeIterator)
{
string value = _argList[0].Evaluate(nodeIterator).ToString();
string mapFrom = _argList[1].Evaluate(nodeIterator).ToString();
string mapTo = _argList[2].Evaluate(nodeIterator).ToString();
int modifyPos = -1;
char[] chars = value.ToCharArray();
for (int comparePos = 0; comparePos < chars.Length; comparePos++)
{
int index = mapFrom.IndexOf(chars[comparePos]);
if (index != -1)
{
if (index < mapTo.Length)
{
modifyPos++;
chars[modifyPos] = mapTo[index];
}
}
else
{
modifyPos++;
chars[modifyPos] = chars[comparePos];
}
}
return new string(chars, 0, modifyPos + 1);
}
public override XPathNodeIterator Clone() { return new StringFunctions(this); }
}
}
| |
// 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.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.WebSockets
{
internal sealed class WebSocketHandle
{
/// <summary>GUID appended by the server as part of the security key response. Defined in the RFC.</summary>
private const string WSServerGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
/// <summary>Shared, lazily-initialized handler for when using default options.</summary>
private static SocketsHttpHandler s_defaultHandler;
private readonly CancellationTokenSource _abortSource = new CancellationTokenSource();
private WebSocketState _state = WebSocketState.Connecting;
private WebSocket _webSocket;
public static WebSocketHandle Create() => new WebSocketHandle();
public static bool IsValid(WebSocketHandle handle) => handle != null;
public WebSocketCloseStatus? CloseStatus => _webSocket?.CloseStatus;
public string CloseStatusDescription => _webSocket?.CloseStatusDescription;
public WebSocketState State => _webSocket?.State ?? _state;
public string SubProtocol => _webSocket?.SubProtocol;
public static void CheckPlatformSupport() { /* nop */ }
public void Dispose()
{
_state = WebSocketState.Closed;
_webSocket?.Dispose();
}
public void Abort()
{
_abortSource.Cancel();
_webSocket?.Abort();
}
public Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) =>
_webSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken);
public ValueTask SendAsync(ReadOnlyMemory<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) =>
_webSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken);
public Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken cancellationToken) =>
_webSocket.ReceiveAsync(buffer, cancellationToken);
public ValueTask<ValueWebSocketReceiveResult> ReceiveAsync(Memory<byte> buffer, CancellationToken cancellationToken) =>
_webSocket.ReceiveAsync(buffer, cancellationToken);
public Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) =>
_webSocket.CloseAsync(closeStatus, statusDescription, cancellationToken);
public Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) =>
_webSocket.CloseOutputAsync(closeStatus, statusDescription, cancellationToken);
public async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options)
{
HttpResponseMessage response = null;
SocketsHttpHandler handler = null;
bool disposeHandler = true;
try
{
var request = new HttpRequestMessage(HttpMethod.Get, uri);
if (options._requestHeaders?.Count > 0) // use field to avoid lazily initializing the collection
{
foreach (string key in options.RequestHeaders)
{
request.Headers.Add(key, options.RequestHeaders[key]);
}
}
// Create the security key and expected response, then build all of the request headers
KeyValuePair<string, string> secKeyAndSecWebSocketAccept = CreateSecKeyAndSecWebSocketAccept();
AddWebSocketHeaders(request, secKeyAndSecWebSocketAccept.Key, options);
// Create the handler for this request and populate it with all of the options.
// Try to use a shared handler rather than creating a new one just for this request, if
// the options are compatible.
if (options.Credentials == null &&
!options.UseDefaultCredentials &&
options.Proxy == null &&
options.Cookies == null &&
options.RemoteCertificateValidationCallback == null &&
options._clientCertificates?.Count == 0)
{
disposeHandler = false;
handler = s_defaultHandler;
if (handler == null)
{
handler = new SocketsHttpHandler()
{
PooledConnectionLifetime = TimeSpan.Zero,
UseProxy = false,
UseCookies = false,
};
if (Interlocked.CompareExchange(ref s_defaultHandler, handler, null) != null)
{
handler.Dispose();
handler = s_defaultHandler;
}
}
}
else
{
handler = new SocketsHttpHandler();
handler.PooledConnectionLifetime = TimeSpan.Zero;
handler.CookieContainer = options.Cookies;
handler.UseCookies = options.Cookies != null;
handler.SslOptions.RemoteCertificateValidationCallback = options.RemoteCertificateValidationCallback;
if (options.UseDefaultCredentials)
{
handler.Credentials = CredentialCache.DefaultCredentials;
}
else
{
handler.Credentials = options.Credentials;
}
if (options.Proxy == null)
{
handler.UseProxy = false;
}
else if (options.Proxy != ClientWebSocket.DefaultWebProxy.Instance)
{
handler.Proxy = options.Proxy;
}
if (options._clientCertificates?.Count > 0) // use field to avoid lazily initializing the collection
{
Debug.Assert(handler.SslOptions.ClientCertificates == null);
handler.SslOptions.ClientCertificates = new X509Certificate2Collection();
handler.SslOptions.ClientCertificates.AddRange(options.ClientCertificates);
}
}
// Issue the request. The response must be status code 101.
CancellationTokenSource linkedCancellation, externalAndAbortCancellation;
if (cancellationToken.CanBeCanceled) // avoid allocating linked source if external token is not cancelable
{
linkedCancellation =
externalAndAbortCancellation =
CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _abortSource.Token);
}
else
{
linkedCancellation = null;
externalAndAbortCancellation = _abortSource;
}
using (linkedCancellation)
{
response = await new HttpMessageInvoker(handler).SendAsync(request, externalAndAbortCancellation.Token).ConfigureAwait(false);
externalAndAbortCancellation.Token.ThrowIfCancellationRequested(); // poll in case sends/receives in request/response didn't observe cancellation
}
if (response.StatusCode != HttpStatusCode.SwitchingProtocols)
{
throw new WebSocketException(SR.Format(SR.net_WebSockets_Connect101Expected, (int) response.StatusCode));
}
// The Connection, Upgrade, and SecWebSocketAccept headers are required and with specific values.
ValidateHeader(response.Headers, HttpKnownHeaderNames.Connection, "Upgrade");
ValidateHeader(response.Headers, HttpKnownHeaderNames.Upgrade, "websocket");
ValidateHeader(response.Headers, HttpKnownHeaderNames.SecWebSocketAccept, secKeyAndSecWebSocketAccept.Value);
// The SecWebSocketProtocol header is optional. We should only get it with a non-empty value if we requested subprotocols,
// and then it must only be one of the ones we requested. If we got a subprotocol other than one we requested (or if we
// already got one in a previous header), fail. Otherwise, track which one we got.
string subprotocol = null;
IEnumerable<string> subprotocolEnumerableValues;
if (response.Headers.TryGetValues(HttpKnownHeaderNames.SecWebSocketProtocol, out subprotocolEnumerableValues))
{
Debug.Assert(subprotocolEnumerableValues is string[]);
string[] subprotocolArray = (string[])subprotocolEnumerableValues;
if (subprotocolArray.Length > 0 && !string.IsNullOrEmpty(subprotocolArray[0]))
{
subprotocol = options.RequestedSubProtocols.Find(requested => string.Equals(requested, subprotocolArray[0], StringComparison.OrdinalIgnoreCase));
if (subprotocol == null)
{
throw new WebSocketException(
WebSocketError.UnsupportedProtocol,
SR.Format(SR.net_WebSockets_AcceptUnsupportedProtocol, string.Join(", ", options.RequestedSubProtocols), string.Join(", ", subprotocolArray)));
}
}
}
// Get the response stream and wrap it in a web socket.
Stream connectedStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
Debug.Assert(connectedStream.CanWrite);
Debug.Assert(connectedStream.CanRead);
_webSocket = WebSocket.CreateFromStream(
connectedStream,
isServer: false,
subprotocol,
options.KeepAliveInterval);
}
catch (Exception exc)
{
if (_state < WebSocketState.Closed)
{
_state = WebSocketState.Closed;
}
Abort();
response?.Dispose();
if (exc is WebSocketException)
{
throw;
}
throw new WebSocketException(SR.net_webstatus_ConnectFailure, exc);
}
finally
{
// Disposing the handler will not affect any active stream wrapped in the WebSocket.
if (disposeHandler)
{
handler?.Dispose();
}
}
}
/// <param name="secKey">The generated security key to send in the Sec-WebSocket-Key header.</param>
private static void AddWebSocketHeaders(HttpRequestMessage request, string secKey, ClientWebSocketOptions options)
{
request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.Connection, HttpKnownHeaderNames.Upgrade);
request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.Upgrade, "websocket");
request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.SecWebSocketVersion, "13");
request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.SecWebSocketKey, secKey);
if (options._requestedSubProtocols?.Count > 0)
{
request.Headers.Add(HttpKnownHeaderNames.SecWebSocketProtocol, string.Join(", ", options.RequestedSubProtocols));
}
}
/// <summary>
/// Creates a pair of a security key for sending in the Sec-WebSocket-Key header and
/// the associated response we expect to receive as the Sec-WebSocket-Accept header value.
/// </summary>
/// <returns>A key-value pair of the request header security key and expected response header value.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "Required by RFC6455")]
private static KeyValuePair<string, string> CreateSecKeyAndSecWebSocketAccept()
{
string secKey = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
using (SHA1 sha = SHA1.Create())
{
return new KeyValuePair<string, string>(
secKey,
Convert.ToBase64String(sha.ComputeHash(Encoding.ASCII.GetBytes(secKey + WSServerGuid))));
}
}
private static void ValidateHeader(HttpHeaders headers, string name, string expectedValue)
{
if (!headers.TryGetValues(name, out IEnumerable<string> values))
{
ThrowConnectFailure();
}
Debug.Assert(values is string[]);
string[] array = (string[])values;
if (array.Length != 1 || !string.Equals(array[0], expectedValue, StringComparison.OrdinalIgnoreCase))
{
throw new WebSocketException(SR.Format(SR.net_WebSockets_InvalidResponseHeader, name, string.Join(", ", array)));
}
}
private static void ThrowConnectFailure() => throw new WebSocketException(SR.net_webstatus_ConnectFailure);
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.Models;
namespace Microsoft.WindowsAzure.Management.Models
{
/// <summary>
/// The List Subscription Operations operation response.
/// </summary>
public partial class SubscriptionListOperationsResponse : OperationResponse
{
private string _continuationToken;
/// <summary>
/// Optional. The string that can be used to return the rest of the
/// list. Subsequent requests must include this parameter to continue
/// listing operations from where the last response left off. This
/// element exists only if the complete list of subscription
/// operations was not returned.
/// </summary>
public string ContinuationToken
{
get { return this._continuationToken; }
set { this._continuationToken = value; }
}
private IList<SubscriptionListOperationsResponse.SubscriptionOperation> _subscriptionOperations;
/// <summary>
/// Optional. The list of operations that have been performed on the
/// subscription during the specified timeframe.
/// </summary>
public IList<SubscriptionListOperationsResponse.SubscriptionOperation> SubscriptionOperations
{
get { return this._subscriptionOperations; }
set { this._subscriptionOperations = value; }
}
/// <summary>
/// Initializes a new instance of the
/// SubscriptionListOperationsResponse class.
/// </summary>
public SubscriptionListOperationsResponse()
{
this.SubscriptionOperations = new LazyList<SubscriptionListOperationsResponse.SubscriptionOperation>();
}
/// <summary>
/// A collection of attributes that identify the source of the
/// operation.
/// </summary>
public partial class OperationCallerDetails
{
private string _clientIPAddress;
/// <summary>
/// Optional. The IP address of the client computer that initiated
/// the operation. This element is returned only if
/// UsedServiceManagementApi is true.
/// </summary>
public string ClientIPAddress
{
get { return this._clientIPAddress; }
set { this._clientIPAddress = value; }
}
private string _subscriptionCertificateThumbprint;
/// <summary>
/// Optional. The thumbprint of the subscription certificate used
/// to initiate the operation.
/// </summary>
public string SubscriptionCertificateThumbprint
{
get { return this._subscriptionCertificateThumbprint; }
set { this._subscriptionCertificateThumbprint = value; }
}
private bool _usedServiceManagementApi;
/// <summary>
/// Optional. Indicates whether the operation was initiated by
/// using the Service Management API. This will be false if it was
/// initiated by another source, such as the Management Portal.
/// </summary>
public bool UsedServiceManagementApi
{
get { return this._usedServiceManagementApi; }
set { this._usedServiceManagementApi = value; }
}
private string _userEmailAddress;
/// <summary>
/// Optional. The email associated with the Windows Live ID of the
/// user who initiated the operation from the Management Portal.
/// This element is returned only if UsedServiceManagementApi is
/// false.
/// </summary>
public string UserEmailAddress
{
get { return this._userEmailAddress; }
set { this._userEmailAddress = value; }
}
/// <summary>
/// Initializes a new instance of the OperationCallerDetails class.
/// </summary>
public OperationCallerDetails()
{
}
}
/// <summary>
/// An operation that has been performed on the subscription during the
/// specified timeframe.
/// </summary>
public partial class SubscriptionOperation
{
private SubscriptionListOperationsResponse.OperationCallerDetails _operationCaller;
/// <summary>
/// Optional. A collection of attributes that identify the source
/// of the operation.
/// </summary>
public SubscriptionListOperationsResponse.OperationCallerDetails OperationCaller
{
get { return this._operationCaller; }
set { this._operationCaller = value; }
}
private DateTime _operationCompletedTime;
/// <summary>
/// Optional. The time that the operation finished executing.
/// </summary>
public DateTime OperationCompletedTime
{
get { return this._operationCompletedTime; }
set { this._operationCompletedTime = value; }
}
private string _operationId;
/// <summary>
/// Optional. The globally unique identifier (GUID) of the
/// operation.
/// </summary>
public string OperationId
{
get { return this._operationId; }
set { this._operationId = value; }
}
private string _operationName;
/// <summary>
/// Optional. The name of the performed operation.
/// </summary>
public string OperationName
{
get { return this._operationName; }
set { this._operationName = value; }
}
private string _operationObjectId;
/// <summary>
/// Optional. The target object for the operation. This value is
/// equal to the URL for performing an HTTP GET on the object, and
/// corresponds to the same values for the ObjectIdFilter in the
/// request.
/// </summary>
public string OperationObjectId
{
get { return this._operationObjectId; }
set { this._operationObjectId = value; }
}
private IDictionary<string, string> _operationParameters;
/// <summary>
/// Optional. The collection of parameters for the performed
/// operation.
/// </summary>
public IDictionary<string, string> OperationParameters
{
get { return this._operationParameters; }
set { this._operationParameters = value; }
}
private DateTime _operationStartedTime;
/// <summary>
/// Optional. The time that the operation started to execute.
/// </summary>
public DateTime OperationStartedTime
{
get { return this._operationStartedTime; }
set { this._operationStartedTime = value; }
}
private string _operationStatus;
/// <summary>
/// Optional. An object that contains information on the current
/// status of the operation. The object returned has the following
/// XML format: <OperationStatus>
/// <ID>339c6c13-1f81-412f-9bc6-00e9c5876695</ID>
/// <Status>Succeeded</Status>
/// <HttpStatusCode>200</HttpStatusCode> </OperationStatus>.
/// Possible values of the Status element, whichholds the
/// operation status, are: Succeeded, Failed, or InProgress.
/// </summary>
public string OperationStatus
{
get { return this._operationStatus; }
set { this._operationStatus = value; }
}
/// <summary>
/// Initializes a new instance of the SubscriptionOperation class.
/// </summary>
public SubscriptionOperation()
{
this.OperationParameters = new LazyDictionary<string, string>();
}
}
}
}
| |
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Numerics;
using Nethereum.Hex.HexTypes;
using Nethereum.ABI.FunctionEncoding.Attributes;
using Nethereum.Web3;
using Nethereum.RPC.Eth.DTOs;
using Nethereum.Contracts.CQS;
using Nethereum.Contracts;
using System.Threading;
namespace Nethereum.GnosisSafe.ContractDefinition
{
public partial class GnosisSafeDeployment : GnosisSafeDeploymentBase
{
public GnosisSafeDeployment() : base(BYTECODE) { }
public GnosisSafeDeployment(string byteCode) : base(byteCode) { }
}
public class GnosisSafeDeploymentBase : ContractDeploymentMessage
{
public static string BYTECODE = "0x";
public GnosisSafeDeploymentBase() : base(BYTECODE) { }
public GnosisSafeDeploymentBase(string byteCode) : base(byteCode) { }
}
public partial class VERSIONFunction : VERSIONFunctionBase { }
[Function("VERSION", "string")]
public class VERSIONFunctionBase : FunctionMessage
{
}
public partial class AddOwnerWithThresholdFunction : AddOwnerWithThresholdFunctionBase { }
[Function("addOwnerWithThreshold")]
public class AddOwnerWithThresholdFunctionBase : FunctionMessage
{
[Parameter("address", "owner", 1)]
public virtual string Owner { get; set; }
[Parameter("uint256", "_threshold", 2)]
public virtual BigInteger Threshold { get; set; }
}
public partial class ApproveHashFunction : ApproveHashFunctionBase { }
[Function("approveHash")]
public class ApproveHashFunctionBase : FunctionMessage
{
[Parameter("bytes32", "hashToApprove", 1)]
public virtual byte[] HashToApprove { get; set; }
}
public partial class ApprovedHashesFunction : ApprovedHashesFunctionBase { }
[Function("approvedHashes", "uint256")]
public class ApprovedHashesFunctionBase : FunctionMessage
{
[Parameter("address", "", 1)]
public virtual string ReturnValue1 { get; set; }
[Parameter("bytes32", "", 2)]
public virtual byte[] ReturnValue2 { get; set; }
}
public partial class ChangeThresholdFunction : ChangeThresholdFunctionBase { }
[Function("changeThreshold")]
public class ChangeThresholdFunctionBase : FunctionMessage
{
[Parameter("uint256", "_threshold", 1)]
public virtual BigInteger Threshold { get; set; }
}
public partial class DisableModuleFunction : DisableModuleFunctionBase { }
[Function("disableModule")]
public class DisableModuleFunctionBase : FunctionMessage
{
[Parameter("address", "prevModule", 1)]
public virtual string PrevModule { get; set; }
[Parameter("address", "module", 2)]
public virtual string Module { get; set; }
}
public partial class DomainSeparatorFunction : DomainSeparatorFunctionBase { }
[Function("domainSeparator", "bytes32")]
public class DomainSeparatorFunctionBase : FunctionMessage
{
}
public partial class EnableModuleFunction : EnableModuleFunctionBase { }
[Function("enableModule")]
public class EnableModuleFunctionBase : FunctionMessage
{
[Parameter("address", "module", 1)]
public virtual string Module { get; set; }
}
public partial class ExecTransactionFunction : ExecTransactionFunctionBase { }
[Function("execTransaction", "bool")]
public class ExecTransactionFunctionBase : FunctionMessage
{
[Parameter("address", "to", 1)]
public virtual string To { get; set; }
[Parameter("uint256", "value", 2)]
public virtual BigInteger Value { get; set; }
[Parameter("bytes", "data", 3)]
public virtual byte[] Data { get; set; }
[Parameter("uint8", "operation", 4)]
public virtual byte Operation { get; set; }
[Parameter("uint256", "safeTxGas", 5)]
public virtual BigInteger SafeTxGas { get; set; }
[Parameter("uint256", "baseGas", 6)]
public virtual BigInteger BaseGas { get; set; }
[Parameter("uint256", "gasPrice", 7)]
public virtual BigInteger SafeGasPrice { get; set; }
[Parameter("address", "gasToken", 8)]
public virtual string GasToken { get; set; }
[Parameter("address", "refundReceiver", 9)]
public virtual string RefundReceiver { get; set; }
[Parameter("bytes", "signatures", 10)]
public virtual byte[] Signatures { get; set; }
}
public partial class ExecTransactionFromModuleFunction : ExecTransactionFromModuleFunctionBase { }
[Function("execTransactionFromModule", "bool")]
public class ExecTransactionFromModuleFunctionBase : FunctionMessage
{
[Parameter("address", "to", 1)]
public virtual string To { get; set; }
[Parameter("uint256", "value", 2)]
public virtual BigInteger Value { get; set; }
[Parameter("bytes", "data", 3)]
public virtual byte[] Data { get; set; }
[Parameter("uint8", "operation", 4)]
public virtual byte Operation { get; set; }
}
public partial class ExecTransactionFromModuleReturnDataFunction : ExecTransactionFromModuleReturnDataFunctionBase { }
[Function("execTransactionFromModuleReturnData", typeof(ExecTransactionFromModuleReturnDataOutputDTO))]
public class ExecTransactionFromModuleReturnDataFunctionBase : FunctionMessage
{
[Parameter("address", "to", 1)]
public virtual string To { get; set; }
[Parameter("uint256", "value", 2)]
public virtual BigInteger Value { get; set; }
[Parameter("bytes", "data", 3)]
public virtual byte[] Data { get; set; }
[Parameter("uint8", "operation", 4)]
public virtual byte Operation { get; set; }
}
public partial class GetChainIdFunction : GetChainIdFunctionBase { }
[Function("getChainId", "uint256")]
public class GetChainIdFunctionBase : FunctionMessage
{
}
public partial class GetModulesPaginatedFunction : GetModulesPaginatedFunctionBase { }
[Function("getModulesPaginated", typeof(GetModulesPaginatedOutputDTO))]
public class GetModulesPaginatedFunctionBase : FunctionMessage
{
[Parameter("address", "start", 1)]
public virtual string Start { get; set; }
[Parameter("uint256", "pageSize", 2)]
public virtual BigInteger PageSize { get; set; }
}
public partial class GetOwnersFunction : GetOwnersFunctionBase { }
[Function("getOwners", "address[]")]
public class GetOwnersFunctionBase : FunctionMessage
{
}
public partial class GetStorageAtFunction : GetStorageAtFunctionBase { }
[Function("getStorageAt", "bytes")]
public class GetStorageAtFunctionBase : FunctionMessage
{
[Parameter("uint256", "offset", 1)]
public virtual BigInteger Offset { get; set; }
[Parameter("uint256", "length", 2)]
public virtual BigInteger Length { get; set; }
}
public partial class GetThresholdFunction : GetThresholdFunctionBase { }
[Function("getThreshold", "uint256")]
public class GetThresholdFunctionBase : FunctionMessage
{
}
public partial class GetTransactionHashFunction : GetTransactionHashFunctionBase { }
[Function("getTransactionHash", "bytes32")]
public class GetTransactionHashFunctionBase : FunctionMessage
{
[Parameter("address", "to", 1)]
public virtual string To { get; set; }
[Parameter("uint256", "value", 2)]
public virtual BigInteger Value { get; set; }
[Parameter("bytes", "data", 3)]
public virtual byte[] Data { get; set; }
[Parameter("uint8", "operation", 4)]
public virtual byte Operation { get; set; }
[Parameter("uint256", "safeTxGas", 5)]
public virtual BigInteger SafeTxGas { get; set; }
[Parameter("uint256", "baseGas", 6)]
public virtual BigInteger BaseGas { get; set; }
[Parameter("uint256", "gasPrice", 7)]
public virtual BigInteger SafeGasPrice { get; set; }
[Parameter("address", "gasToken", 8)]
public virtual string GasToken { get; set; }
[Parameter("address", "refundReceiver", 9)]
public virtual string RefundReceiver { get; set; }
[Parameter("uint256", "_nonce", 10)]
public virtual BigInteger SafeNonce { get; set; }
}
public partial class IsModuleEnabledFunction : IsModuleEnabledFunctionBase { }
[Function("isModuleEnabled", "bool")]
public class IsModuleEnabledFunctionBase : FunctionMessage
{
[Parameter("address", "module", 1)]
public virtual string Module { get; set; }
}
public partial class IsOwnerFunction : IsOwnerFunctionBase { }
[Function("isOwner", "bool")]
public class IsOwnerFunctionBase : FunctionMessage
{
[Parameter("address", "owner", 1)]
public virtual string Owner { get; set; }
}
public partial class NonceFunction : NonceFunctionBase { }
[Function("nonce", "uint256")]
public class NonceFunctionBase : FunctionMessage
{
}
public partial class RemoveOwnerFunction : RemoveOwnerFunctionBase { }
[Function("removeOwner")]
public class RemoveOwnerFunctionBase : FunctionMessage
{
[Parameter("address", "prevOwner", 1)]
public virtual string PrevOwner { get; set; }
[Parameter("address", "owner", 2)]
public virtual string Owner { get; set; }
[Parameter("uint256", "_threshold", 3)]
public virtual BigInteger Threshold { get; set; }
}
public partial class RequiredTxGasFunction : RequiredTxGasFunctionBase { }
[Function("requiredTxGas", "uint256")]
public class RequiredTxGasFunctionBase : FunctionMessage
{
[Parameter("address", "to", 1)]
public virtual string To { get; set; }
[Parameter("uint256", "value", 2)]
public virtual BigInteger Value { get; set; }
[Parameter("bytes", "data", 3)]
public virtual byte[] Data { get; set; }
[Parameter("uint8", "operation", 4)]
public virtual byte Operation { get; set; }
}
public partial class SetFallbackHandlerFunction : SetFallbackHandlerFunctionBase { }
[Function("setFallbackHandler")]
public class SetFallbackHandlerFunctionBase : FunctionMessage
{
[Parameter("address", "handler", 1)]
public virtual string Handler { get; set; }
}
public partial class SetGuardFunction : SetGuardFunctionBase { }
[Function("setGuard")]
public class SetGuardFunctionBase : FunctionMessage
{
[Parameter("address", "guard", 1)]
public virtual string Guard { get; set; }
}
public partial class SetupFunction : SetupFunctionBase { }
[Function("setup")]
public class SetupFunctionBase : FunctionMessage
{
[Parameter("address[]", "_owners", 1)]
public virtual List<string> Owners { get; set; }
[Parameter("uint256", "_threshold", 2)]
public virtual BigInteger Threshold { get; set; }
[Parameter("address", "to", 3)]
public virtual string To { get; set; }
[Parameter("bytes", "data", 4)]
public virtual byte[] Data { get; set; }
[Parameter("address", "fallbackHandler", 5)]
public virtual string FallbackHandler { get; set; }
[Parameter("address", "paymentToken", 6)]
public virtual string PaymentToken { get; set; }
[Parameter("uint256", "payment", 7)]
public virtual BigInteger Payment { get; set; }
[Parameter("address", "paymentReceiver", 8)]
public virtual string PaymentReceiver { get; set; }
}
public partial class SignedMessagesFunction : SignedMessagesFunctionBase { }
[Function("signedMessages", "uint256")]
public class SignedMessagesFunctionBase : FunctionMessage
{
[Parameter("bytes32", "", 1)]
public virtual byte[] ReturnValue1 { get; set; }
}
public partial class SimulateAndRevertFunction : SimulateAndRevertFunctionBase { }
[Function("simulateAndRevert")]
public class SimulateAndRevertFunctionBase : FunctionMessage
{
[Parameter("address", "targetContract", 1)]
public virtual string TargetContract { get; set; }
[Parameter("bytes", "calldataPayload", 2)]
public virtual byte[] CalldataPayload { get; set; }
}
public partial class SwapOwnerFunction : SwapOwnerFunctionBase { }
[Function("swapOwner")]
public class SwapOwnerFunctionBase : FunctionMessage
{
[Parameter("address", "prevOwner", 1)]
public virtual string PrevOwner { get; set; }
[Parameter("address", "oldOwner", 2)]
public virtual string OldOwner { get; set; }
[Parameter("address", "newOwner", 3)]
public virtual string NewOwner { get; set; }
}
public partial class AddedOwnerEventDTO : AddedOwnerEventDTOBase { }
[Event("AddedOwner")]
public class AddedOwnerEventDTOBase : IEventDTO
{
[Parameter("address", "owner", 1, false )]
public virtual string Owner { get; set; }
}
public partial class ApproveHashEventDTO : ApproveHashEventDTOBase { }
[Event("ApproveHash")]
public class ApproveHashEventDTOBase : IEventDTO
{
[Parameter("bytes32", "approvedHash", 1, true )]
public virtual byte[] ApprovedHash { get; set; }
[Parameter("address", "owner", 2, true )]
public virtual string Owner { get; set; }
}
public partial class ChangedFallbackHandlerEventDTO : ChangedFallbackHandlerEventDTOBase { }
[Event("ChangedFallbackHandler")]
public class ChangedFallbackHandlerEventDTOBase : IEventDTO
{
[Parameter("address", "handler", 1, false )]
public virtual string Handler { get; set; }
}
public partial class ChangedGuardEventDTO : ChangedGuardEventDTOBase { }
[Event("ChangedGuard")]
public class ChangedGuardEventDTOBase : IEventDTO
{
[Parameter("address", "guard", 1, false )]
public virtual string Guard { get; set; }
}
public partial class ChangedThresholdEventDTO : ChangedThresholdEventDTOBase { }
[Event("ChangedThreshold")]
public class ChangedThresholdEventDTOBase : IEventDTO
{
[Parameter("uint256", "threshold", 1, false )]
public virtual BigInteger Threshold { get; set; }
}
public partial class DisabledModuleEventDTO : DisabledModuleEventDTOBase { }
[Event("DisabledModule")]
public class DisabledModuleEventDTOBase : IEventDTO
{
[Parameter("address", "module", 1, false )]
public virtual string Module { get; set; }
}
public partial class EnabledModuleEventDTO : EnabledModuleEventDTOBase { }
[Event("EnabledModule")]
public class EnabledModuleEventDTOBase : IEventDTO
{
[Parameter("address", "module", 1, false )]
public virtual string Module { get; set; }
}
public partial class ExecutionFailureEventDTO : ExecutionFailureEventDTOBase { }
[Event("ExecutionFailure")]
public class ExecutionFailureEventDTOBase : IEventDTO
{
[Parameter("bytes32", "txHash", 1, false )]
public virtual byte[] TxHash { get; set; }
[Parameter("uint256", "payment", 2, false )]
public virtual BigInteger Payment { get; set; }
}
public partial class ExecutionFromModuleFailureEventDTO : ExecutionFromModuleFailureEventDTOBase { }
[Event("ExecutionFromModuleFailure")]
public class ExecutionFromModuleFailureEventDTOBase : IEventDTO
{
[Parameter("address", "module", 1, true )]
public virtual string Module { get; set; }
}
public partial class ExecutionFromModuleSuccessEventDTO : ExecutionFromModuleSuccessEventDTOBase { }
[Event("ExecutionFromModuleSuccess")]
public class ExecutionFromModuleSuccessEventDTOBase : IEventDTO
{
[Parameter("address", "module", 1, true )]
public virtual string Module { get; set; }
}
public partial class ExecutionSuccessEventDTO : ExecutionSuccessEventDTOBase { }
[Event("ExecutionSuccess")]
public class ExecutionSuccessEventDTOBase : IEventDTO
{
[Parameter("bytes32", "txHash", 1, false )]
public virtual byte[] TxHash { get; set; }
[Parameter("uint256", "payment", 2, false )]
public virtual BigInteger Payment { get; set; }
}
public partial class RemovedOwnerEventDTO : RemovedOwnerEventDTOBase { }
[Event("RemovedOwner")]
public class RemovedOwnerEventDTOBase : IEventDTO
{
[Parameter("address", "owner", 1, false )]
public virtual string Owner { get; set; }
}
public partial class SafeReceivedEventDTO : SafeReceivedEventDTOBase { }
[Event("SafeReceived")]
public class SafeReceivedEventDTOBase : IEventDTO
{
[Parameter("address", "sender", 1, true )]
public virtual string Sender { get; set; }
[Parameter("uint256", "value", 2, false )]
public virtual BigInteger Value { get; set; }
}
public partial class SafeSetupEventDTO : SafeSetupEventDTOBase { }
[Event("SafeSetup")]
public class SafeSetupEventDTOBase : IEventDTO
{
[Parameter("address", "initiator", 1, true )]
public virtual string Initiator { get; set; }
[Parameter("address[]", "owners", 2, false )]
public virtual List<string> Owners { get; set; }
[Parameter("uint256", "threshold", 3, false )]
public virtual BigInteger Threshold { get; set; }
[Parameter("address", "initializer", 4, false )]
public virtual string Initializer { get; set; }
[Parameter("address", "fallbackHandler", 5, false )]
public virtual string FallbackHandler { get; set; }
}
public partial class SignMsgEventDTO : SignMsgEventDTOBase { }
[Event("SignMsg")]
public class SignMsgEventDTOBase : IEventDTO
{
[Parameter("bytes32", "msgHash", 1, true )]
public virtual byte[] MsgHash { get; set; }
}
public partial class VERSIONOutputDTO : VERSIONOutputDTOBase { }
[FunctionOutput]
public class VERSIONOutputDTOBase : IFunctionOutputDTO
{
[Parameter("string", "", 1)]
public virtual string ReturnValue1 { get; set; }
}
public partial class ApprovedHashesOutputDTO : ApprovedHashesOutputDTOBase { }
[FunctionOutput]
public class ApprovedHashesOutputDTOBase : IFunctionOutputDTO
{
[Parameter("uint256", "", 1)]
public virtual BigInteger ReturnValue1 { get; set; }
}
public partial class DomainSeparatorOutputDTO : DomainSeparatorOutputDTOBase { }
[FunctionOutput]
public class DomainSeparatorOutputDTOBase : IFunctionOutputDTO
{
[Parameter("bytes32", "", 1)]
public virtual byte[] ReturnValue1 { get; set; }
}
public partial class EncodeTransactionDataOutputDTO : EncodeTransactionDataOutputDTOBase { }
[FunctionOutput]
public class EncodeTransactionDataOutputDTOBase : IFunctionOutputDTO
{
[Parameter("bytes", "", 1)]
public virtual byte[] ReturnValue1 { get; set; }
}
public partial class ExecTransactionFromModuleReturnDataOutputDTO : ExecTransactionFromModuleReturnDataOutputDTOBase { }
[FunctionOutput]
public class ExecTransactionFromModuleReturnDataOutputDTOBase : IFunctionOutputDTO
{
[Parameter("bool", "success", 1)]
public virtual bool Success { get; set; }
[Parameter("bytes", "returnData", 2)]
public virtual byte[] ReturnData { get; set; }
}
public partial class GetChainIdOutputDTO : GetChainIdOutputDTOBase { }
[FunctionOutput]
public class GetChainIdOutputDTOBase : IFunctionOutputDTO
{
[Parameter("uint256", "", 1)]
public virtual BigInteger ReturnValue1 { get; set; }
}
public partial class GetModulesPaginatedOutputDTO : GetModulesPaginatedOutputDTOBase { }
[FunctionOutput]
public class GetModulesPaginatedOutputDTOBase : IFunctionOutputDTO
{
[Parameter("address[]", "array", 1)]
public virtual List<string> Array { get; set; }
[Parameter("address", "next", 2)]
public virtual string Next { get; set; }
}
public partial class GetOwnersOutputDTO : GetOwnersOutputDTOBase { }
[FunctionOutput]
public class GetOwnersOutputDTOBase : IFunctionOutputDTO
{
[Parameter("address[]", "", 1)]
public virtual List<string> ReturnValue1 { get; set; }
}
public partial class GetStorageAtOutputDTO : GetStorageAtOutputDTOBase { }
[FunctionOutput]
public class GetStorageAtOutputDTOBase : IFunctionOutputDTO
{
[Parameter("bytes", "", 1)]
public virtual byte[] ReturnValue1 { get; set; }
}
public partial class GetThresholdOutputDTO : GetThresholdOutputDTOBase { }
[FunctionOutput]
public class GetThresholdOutputDTOBase : IFunctionOutputDTO
{
[Parameter("uint256", "", 1)]
public virtual BigInteger ReturnValue1 { get; set; }
}
public partial class GetTransactionHashOutputDTO : GetTransactionHashOutputDTOBase { }
[FunctionOutput]
public class GetTransactionHashOutputDTOBase : IFunctionOutputDTO
{
[Parameter("bytes32", "", 1)]
public virtual byte[] ReturnValue1 { get; set; }
}
public partial class IsModuleEnabledOutputDTO : IsModuleEnabledOutputDTOBase { }
[FunctionOutput]
public class IsModuleEnabledOutputDTOBase : IFunctionOutputDTO
{
[Parameter("bool", "", 1)]
public virtual bool ReturnValue1 { get; set; }
}
public partial class IsOwnerOutputDTO : IsOwnerOutputDTOBase { }
[FunctionOutput]
public class IsOwnerOutputDTOBase : IFunctionOutputDTO
{
[Parameter("bool", "", 1)]
public virtual bool ReturnValue1 { get; set; }
}
public partial class NonceOutputDTO : NonceOutputDTOBase { }
[FunctionOutput]
public class NonceOutputDTOBase : IFunctionOutputDTO
{
[Parameter("uint256", "", 1)]
public virtual BigInteger ReturnValue1 { get; set; }
}
public partial class SignedMessagesOutputDTO : SignedMessagesOutputDTOBase { }
[FunctionOutput]
public class SignedMessagesOutputDTOBase : IFunctionOutputDTO
{
[Parameter("uint256", "", 1)]
public virtual BigInteger ReturnValue1 { get; set; }
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Text;
using System.Timers;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using Mono.Addins;
namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AvatarFactoryModule")]
public class AvatarFactoryModule : IAvatarFactoryModule, INonSharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public const string BAKED_TEXTURES_REPORT_FORMAT = "{0,-9} {1}";
private Scene m_scene = null;
private int m_savetime = 5; // seconds to wait before saving changed appearance
private int m_sendtime = 2; // seconds to wait before sending changed appearance
private int m_checkTime = 500; // milliseconds to wait between checks for appearance updates
private System.Timers.Timer m_updateTimer = new System.Timers.Timer();
private Dictionary<UUID,long> m_savequeue = new Dictionary<UUID,long>();
private Dictionary<UUID,long> m_sendqueue = new Dictionary<UUID,long>();
private object m_setAppearanceLock = new object();
#region Region Module interface
public void Initialise(IConfigSource config)
{
IConfig appearanceConfig = config.Configs["Appearance"];
if (appearanceConfig != null)
{
m_savetime = Convert.ToInt32(appearanceConfig.GetString("DelayBeforeAppearanceSave",Convert.ToString(m_savetime)));
m_sendtime = Convert.ToInt32(appearanceConfig.GetString("DelayBeforeAppearanceSend",Convert.ToString(m_sendtime)));
// m_log.InfoFormat("[AVFACTORY] configured for {0} save and {1} send",m_savetime,m_sendtime);
}
}
public void AddRegion(Scene scene)
{
if (m_scene == null)
m_scene = scene;
scene.RegisterModuleInterface<IAvatarFactoryModule>(this);
scene.EventManager.OnNewClient += SubscribeToClientEvents;
}
public void RemoveRegion(Scene scene)
{
if (scene == m_scene)
{
scene.UnregisterModuleInterface<IAvatarFactoryModule>(this);
scene.EventManager.OnNewClient -= SubscribeToClientEvents;
}
m_scene = null;
}
public void RegionLoaded(Scene scene)
{
m_updateTimer.Enabled = false;
m_updateTimer.AutoReset = true;
m_updateTimer.Interval = m_checkTime; // 500 milliseconds wait to start async ops
m_updateTimer.Elapsed += new ElapsedEventHandler(HandleAppearanceUpdateTimer);
}
public void Close()
{
}
public string Name
{
get { return "Default Avatar Factory"; }
}
public bool IsSharedModule
{
get { return false; }
}
public Type ReplaceableInterface
{
get { return null; }
}
private void SubscribeToClientEvents(IClientAPI client)
{
client.OnRequestWearables += Client_OnRequestWearables;
client.OnSetAppearance += Client_OnSetAppearance;
client.OnAvatarNowWearing += Client_OnAvatarNowWearing;
}
#endregion
#region IAvatarFactoryModule
/// </summary>
/// <param name="sp"></param>
/// <param name="texture"></param>
/// <param name="visualParam"></param>
public void SetAppearance(IScenePresence sp, AvatarAppearance appearance)
{
SetAppearance(sp, appearance.Texture, appearance.VisualParams);
}
/// <summary>
/// Set appearance data (texture asset IDs and slider settings)
/// </summary>
/// <param name="sp"></param>
/// <param name="texture"></param>
/// <param name="visualParam"></param>
public void SetAppearance(IScenePresence sp, Primitive.TextureEntry textureEntry, byte[] visualParams)
{
// m_log.DebugFormat(
// "[AVFACTORY]: start SetAppearance for {0}, te {1}, visualParams {2}",
// sp.Name, textureEntry, visualParams);
// TODO: This is probably not necessary any longer, just assume the
// textureEntry set implies that the appearance transaction is complete
bool changed = false;
// Process the texture entry transactionally, this doesn't guarantee that Appearance is
// going to be handled correctly but it does serialize the updates to the appearance
lock (m_setAppearanceLock)
{
// Process the visual params, this may change height as well
if (visualParams != null)
{
// string[] visualParamsStrings = new string[visualParams.Length];
// for (int i = 0; i < visualParams.Length; i++)
// visualParamsStrings[i] = visualParams[i].ToString();
// m_log.DebugFormat(
// "[AVFACTORY]: Setting visual params for {0} to {1}",
// client.Name, string.Join(", ", visualParamsStrings));
float oldHeight = sp.Appearance.AvatarHeight;
changed = sp.Appearance.SetVisualParams(visualParams);
if (sp.Appearance.AvatarHeight != oldHeight && sp.Appearance.AvatarHeight > 0)
((ScenePresence)sp).SetHeight(sp.Appearance.AvatarHeight);
}
// Process the baked texture array
if (textureEntry != null)
{
// m_log.DebugFormat("[AVFACTORY]: Received texture update for {0} {1}", sp.Name, sp.UUID);
// WriteBakedTexturesReport(sp, m_log.DebugFormat);
changed = sp.Appearance.SetTextureEntries(textureEntry) || changed;
// WriteBakedTexturesReport(sp, m_log.DebugFormat);
// If bake textures are missing and this is not an NPC, request a rebake from client
if (!ValidateBakedTextureCache(sp) && (((ScenePresence)sp).PresenceType != PresenceType.Npc))
RequestRebake(sp, true);
// This appears to be set only in the final stage of the appearance
// update transaction. In theory, we should be able to do an immediate
// appearance send and save here.
}
// NPC should send to clients immediately and skip saving appearance
if (((ScenePresence)sp).PresenceType == PresenceType.Npc)
{
SendAppearance((ScenePresence)sp);
return;
}
// save only if there were changes, send no matter what (doesn't hurt to send twice)
if (changed)
QueueAppearanceSave(sp.ControllingClient.AgentId);
QueueAppearanceSend(sp.ControllingClient.AgentId);
}
// m_log.WarnFormat("[AVFACTORY]: complete SetAppearance for {0}:\n{1}",client.AgentId,sp.Appearance.ToString());
}
private void SendAppearance(ScenePresence sp)
{
// Send the appearance to everyone in the scene
sp.SendAppearanceToAllOtherAgents();
// Send animations back to the avatar as well
sp.Animator.SendAnimPack();
}
public bool SendAppearance(UUID agentId)
{
// m_log.DebugFormat("[AVFACTORY]: Sending appearance for {0}", agentId);
ScenePresence sp = m_scene.GetScenePresence(agentId);
if (sp == null)
{
// This is expected if the user has gone away.
// m_log.DebugFormat("[AVFACTORY]: Agent {0} no longer in the scene", agentId);
return false;
}
SendAppearance(sp);
return true;
}
public Dictionary<BakeType, Primitive.TextureEntryFace> GetBakedTextureFaces(UUID agentId)
{
ScenePresence sp = m_scene.GetScenePresence(agentId);
if (sp == null)
return new Dictionary<BakeType, Primitive.TextureEntryFace>();
return GetBakedTextureFaces(sp);
}
public bool SaveBakedTextures(UUID agentId)
{
ScenePresence sp = m_scene.GetScenePresence(agentId);
if (sp == null)
return false;
m_log.DebugFormat(
"[AV FACTORY]: Permanently saving baked textures for {0} in {1}",
sp.Name, m_scene.RegionInfo.RegionName);
Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures = GetBakedTextureFaces(sp);
if (bakedTextures.Count == 0)
return false;
foreach (BakeType bakeType in bakedTextures.Keys)
{
Primitive.TextureEntryFace bakedTextureFace = bakedTextures[bakeType];
if (bakedTextureFace == null)
{
// This can happen legitimately, since some baked textures might not exist
//m_log.WarnFormat(
// "[AV FACTORY]: No texture ID set for {0} for {1} in {2} not found when trying to save permanently",
// bakeType, sp.Name, m_scene.RegionInfo.RegionName);
continue;
}
AssetBase asset = m_scene.AssetService.Get(bakedTextureFace.TextureID.ToString());
if (asset != null)
{
// Replace an HG ID with the simple asset ID so that we can persist textures for foreign HG avatars
asset.ID = asset.FullID.ToString();
asset.Temporary = false;
asset.Local = false;
m_scene.AssetService.Store(asset);
}
else
{
m_log.WarnFormat(
"[AV FACTORY]: Baked texture id {0} not found for bake {1} for avatar {2} in {3} when trying to save permanently",
bakedTextureFace.TextureID, bakeType, sp.Name, m_scene.RegionInfo.RegionName);
}
}
return true;
}
/// <summary>
/// Queue up a request to send appearance.
/// </summary>
/// <remarks>
/// Makes it possible to accumulate changes without sending out each one separately.
/// </remarks>
/// <param name="agentId"></param>
public void QueueAppearanceSend(UUID agentid)
{
// m_log.DebugFormat("[AVFACTORY]: Queue appearance send for {0}", agentid);
// 10000 ticks per millisecond, 1000 milliseconds per second
long timestamp = DateTime.Now.Ticks + Convert.ToInt64(m_sendtime * 1000 * 10000);
lock (m_sendqueue)
{
m_sendqueue[agentid] = timestamp;
m_updateTimer.Start();
}
}
public void QueueAppearanceSave(UUID agentid)
{
// m_log.WarnFormat("[AVFACTORY]: Queue appearance save for {0}", agentid);
// 10000 ticks per millisecond, 1000 milliseconds per second
long timestamp = DateTime.Now.Ticks + Convert.ToInt64(m_savetime * 1000 * 10000);
lock (m_savequeue)
{
m_savequeue[agentid] = timestamp;
m_updateTimer.Start();
}
}
public bool ValidateBakedTextureCache(IScenePresence sp)
{
bool defonly = true; // are we only using default textures
// Process the texture entry
for (int i = 0; i < AvatarAppearance.BAKE_INDICES.Length; i++)
{
int idx = AvatarAppearance.BAKE_INDICES[i];
Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx];
// if there is no texture entry, skip it
if (face == null)
continue;
// m_log.DebugFormat(
// "[AVFACTORY]: Looking for texture {0}, id {1} for {2} {3}",
// face.TextureID, idx, client.Name, client.AgentId);
// if the texture is one of the "defaults" then skip it
// this should probably be more intelligent (skirt texture doesnt matter
// if the avatar isnt wearing a skirt) but if any of the main baked
// textures is default then the rest should be as well
if (face.TextureID == UUID.Zero || face.TextureID == AppearanceManager.DEFAULT_AVATAR_TEXTURE)
continue;
defonly = false; // found a non-default texture reference
if (m_scene.AssetService.Get(face.TextureID.ToString()) == null)
return false;
}
// m_log.DebugFormat("[AVFACTORY]: Completed texture check for {0} {1}", sp.Name, sp.UUID);
// If we only found default textures, then the appearance is not cached
return (defonly ? false : true);
}
public int RequestRebake(IScenePresence sp, bool missingTexturesOnly)
{
int texturesRebaked = 0;
for (int i = 0; i < AvatarAppearance.BAKE_INDICES.Length; i++)
{
int idx = AvatarAppearance.BAKE_INDICES[i];
Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx];
// if there is no texture entry, skip it
if (face == null)
continue;
// m_log.DebugFormat(
// "[AVFACTORY]: Looking for texture {0}, id {1} for {2} {3}",
// face.TextureID, idx, client.Name, client.AgentId);
// if the texture is one of the "defaults" then skip it
// this should probably be more intelligent (skirt texture doesnt matter
// if the avatar isnt wearing a skirt) but if any of the main baked
// textures is default then the rest should be as well
if (face.TextureID == UUID.Zero || face.TextureID == AppearanceManager.DEFAULT_AVATAR_TEXTURE)
continue;
if (missingTexturesOnly)
{
if (m_scene.AssetService.Get(face.TextureID.ToString()) != null)
{
continue;
}
else
{
// On inter-simulator teleports, this occurs if baked textures are not being stored by the
// grid asset service (which means that they are not available to the new region and so have
// to be re-requested from the client).
//
// The only available core OpenSimulator behaviour right now
// is not to store these textures, temporarily or otherwise.
m_log.DebugFormat(
"[AVFACTORY]: Missing baked texture {0} ({1}) for {2}, requesting rebake.",
face.TextureID, idx, sp.Name);
}
}
else
{
m_log.DebugFormat(
"[AVFACTORY]: Requesting rebake of {0} ({1}) for {2}.",
face.TextureID, idx, sp.Name);
}
texturesRebaked++;
sp.ControllingClient.SendRebakeAvatarTextures(face.TextureID);
}
return texturesRebaked;
}
#endregion
#region AvatarFactoryModule private methods
private Dictionary<BakeType, Primitive.TextureEntryFace> GetBakedTextureFaces(ScenePresence sp)
{
if (sp.IsChildAgent)
return new Dictionary<BakeType, Primitive.TextureEntryFace>();
Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures
= new Dictionary<BakeType, Primitive.TextureEntryFace>();
AvatarAppearance appearance = sp.Appearance;
Primitive.TextureEntryFace[] faceTextures = appearance.Texture.FaceTextures;
foreach (int i in Enum.GetValues(typeof(BakeType)))
{
BakeType bakeType = (BakeType)i;
if (bakeType == BakeType.Unknown)
continue;
// m_log.DebugFormat(
// "[AVFACTORY]: NPC avatar {0} has texture id {1} : {2}",
// acd.AgentID, i, acd.Appearance.Texture.FaceTextures[i]);
int ftIndex = (int)AppearanceManager.BakeTypeToAgentTextureIndex(bakeType);
Primitive.TextureEntryFace texture = faceTextures[ftIndex]; // this will be null if there's no such baked texture
bakedTextures[bakeType] = texture;
}
return bakedTextures;
}
private void HandleAppearanceUpdateTimer(object sender, EventArgs ea)
{
long now = DateTime.Now.Ticks;
lock (m_sendqueue)
{
Dictionary<UUID, long> sends = new Dictionary<UUID, long>(m_sendqueue);
foreach (KeyValuePair<UUID, long> kvp in sends)
{
// We have to load the key and value into local parameters to avoid a race condition if we loop
// around and load kvp with a different value before FireAndForget has launched its thread.
UUID avatarID = kvp.Key;
long sendTime = kvp.Value;
// m_log.DebugFormat("[AVFACTORY]: Handling queued appearance updates for {0}, update delta to now is {1}", avatarID, sendTime - now);
if (sendTime < now)
{
Util.FireAndForget(o => SendAppearance(avatarID));
m_sendqueue.Remove(avatarID);
}
}
}
lock (m_savequeue)
{
Dictionary<UUID, long> saves = new Dictionary<UUID, long>(m_savequeue);
foreach (KeyValuePair<UUID, long> kvp in saves)
{
// We have to load the key and value into local parameters to avoid a race condition if we loop
// around and load kvp with a different value before FireAndForget has launched its thread.
UUID avatarID = kvp.Key;
long sendTime = kvp.Value;
if (sendTime < now)
{
Util.FireAndForget(o => SaveAppearance(avatarID));
m_savequeue.Remove(avatarID);
}
}
// We must lock both queues here so that QueueAppearanceSave() or *Send() don't m_updateTimer.Start() on
// another thread inbetween the first count calls and m_updateTimer.Stop() on this thread.
lock (m_sendqueue)
if (m_savequeue.Count == 0 && m_sendqueue.Count == 0)
m_updateTimer.Stop();
}
}
private void SaveAppearance(UUID agentid)
{
// We must set appearance parameters in the en_US culture in order to avoid issues where values are saved
// in a culture where decimal points are commas and then reloaded in a culture which just treats them as
// number seperators.
Culture.SetCurrentCulture();
ScenePresence sp = m_scene.GetScenePresence(agentid);
if (sp == null)
{
// This is expected if the user has gone away.
// m_log.DebugFormat("[AVFACTORY]: Agent {0} no longer in the scene", agentid);
return;
}
// m_log.WarnFormat("[AVFACTORY] avatar {0} save appearance",agentid);
// This could take awhile since it needs to pull inventory
// We need to do it at the point of save so that there is a sufficient delay for any upload of new body part/shape
// assets and item asset id changes to complete.
// I don't think we need to worry about doing this within m_setAppearanceLock since the queueing avoids
// multiple save requests.
SetAppearanceAssets(sp.UUID, sp.Appearance);
m_scene.AvatarService.SetAppearance(agentid, sp.Appearance);
// Trigger this here because it's the final step in the set/queue/save process for appearance setting.
// Everything has been updated and stored. Ensures bakes have been persisted (if option is set to persist bakes).
m_scene.EventManager.TriggerAvatarAppearanceChanged(sp);
}
private void SetAppearanceAssets(UUID userID, AvatarAppearance appearance)
{
IInventoryService invService = m_scene.InventoryService;
if (invService.GetRootFolder(userID) != null)
{
for (int i = 0; i < AvatarWearable.MAX_WEARABLES; i++)
{
for (int j = 0; j < appearance.Wearables[i].Count; j++)
{
if (appearance.Wearables[i][j].ItemID == UUID.Zero)
continue;
// Ignore ruth's assets
if (appearance.Wearables[i][j].ItemID == AvatarWearable.DefaultWearables[i][0].ItemID)
continue;
InventoryItemBase baseItem = new InventoryItemBase(appearance.Wearables[i][j].ItemID, userID);
baseItem = invService.GetItem(baseItem);
if (baseItem != null)
{
appearance.Wearables[i].Add(appearance.Wearables[i][j].ItemID, baseItem.AssetID);
}
else
{
m_log.ErrorFormat(
"[AVFACTORY]: Can't find inventory item {0} for {1}, setting to default",
appearance.Wearables[i][j].ItemID, (WearableType)i);
appearance.Wearables[i].RemoveItem(appearance.Wearables[i][j].ItemID);
}
}
}
}
else
{
m_log.WarnFormat("[AVFACTORY]: user {0} has no inventory, appearance isn't going to work", userID);
}
}
#endregion
#region Client Event Handlers
/// <summary>
/// Tell the client for this scene presence what items it should be wearing now
/// </summary>
/// <param name="client"></param>
private void Client_OnRequestWearables(IClientAPI client)
{
// m_log.DebugFormat("[AVFACTORY]: Client_OnRequestWearables called for {0} ({1})", client.Name, client.AgentId);
ScenePresence sp = m_scene.GetScenePresence(client.AgentId);
if (sp != null)
client.SendWearables(sp.Appearance.Wearables, sp.Appearance.Serial++);
else
m_log.WarnFormat("[AVFACTORY]: Client_OnRequestWearables unable to find presence for {0}", client.AgentId);
}
/// <summary>
/// Set appearance data (texture asset IDs and slider settings) received from a client
/// </summary>
/// <param name="client"></param>
/// <param name="texture"></param>
/// <param name="visualParam"></param>
private void Client_OnSetAppearance(IClientAPI client, Primitive.TextureEntry textureEntry, byte[] visualParams)
{
// m_log.WarnFormat("[AVFACTORY]: Client_OnSetAppearance called for {0} ({1})", client.Name, client.AgentId);
ScenePresence sp = m_scene.GetScenePresence(client.AgentId);
if (sp != null)
SetAppearance(sp, textureEntry, visualParams);
else
m_log.WarnFormat("[AVFACTORY]: Client_OnSetAppearance unable to find presence for {0}", client.AgentId);
}
/// <summary>
/// Update what the avatar is wearing using an item from their inventory.
/// </summary>
/// <param name="client"></param>
/// <param name="e"></param>
private void Client_OnAvatarNowWearing(IClientAPI client, AvatarWearingArgs e)
{
// m_log.WarnFormat("[AVFACTORY]: Client_OnAvatarNowWearing called for {0} ({1})", client.Name, client.AgentId);
ScenePresence sp = m_scene.GetScenePresence(client.AgentId);
if (sp == null)
{
m_log.WarnFormat("[AVFACTORY]: Client_OnAvatarNowWearing unable to find presence for {0}", client.AgentId);
return;
}
// we need to clean out the existing textures
sp.Appearance.ResetAppearance();
// operate on a copy of the appearance so we don't have to lock anything yet
AvatarAppearance avatAppearance = new AvatarAppearance(sp.Appearance, false);
foreach (AvatarWearingArgs.Wearable wear in e.NowWearing)
{
if (wear.Type < AvatarWearable.MAX_WEARABLES)
avatAppearance.Wearables[wear.Type].Add(wear.ItemID, UUID.Zero);
}
avatAppearance.GetAssetsFrom(sp.Appearance);
lock (m_setAppearanceLock)
{
// Update only those fields that we have changed. This is important because the viewer
// often sends AvatarIsWearing and SetAppearance packets at once, and AvatarIsWearing
// shouldn't overwrite the changes made in SetAppearance.
sp.Appearance.Wearables = avatAppearance.Wearables;
sp.Appearance.Texture = avatAppearance.Texture;
// We don't need to send the appearance here since the "iswearing" will trigger a new set
// of visual param and baked texture changes. When those complete, the new appearance will be sent
QueueAppearanceSave(client.AgentId);
}
}
#endregion
public void WriteBakedTexturesReport(IScenePresence sp, ReportOutputAction outputAction)
{
outputAction("For {0} in {1}", sp.Name, m_scene.RegionInfo.RegionName);
outputAction(BAKED_TEXTURES_REPORT_FORMAT, "Bake Type", "UUID");
Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures = GetBakedTextureFaces(sp.UUID);
foreach (BakeType bt in bakedTextures.Keys)
{
string rawTextureID;
if (bakedTextures[bt] == null)
{
rawTextureID = "not set";
}
else
{
rawTextureID = bakedTextures[bt].TextureID.ToString();
if (m_scene.AssetService.Get(rawTextureID) == null)
rawTextureID += " (not found)";
else
rawTextureID += " (uploaded)";
}
outputAction(BAKED_TEXTURES_REPORT_FORMAT, bt, rawTextureID);
}
bool bakedTextureValid = m_scene.AvatarFactory.ValidateBakedTextureCache(sp);
outputAction("{0} baked appearance texture is {1}", sp.Name, bakedTextureValid ? "OK" : "incomplete");
}
}
}
| |
#region License
/*
* Copyright (C) 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Threading;
using BitCoinSharp.Threading.Execution;
namespace BitCoinSharp.Threading.Future
{
/// <summary>
/// Enumeration representing a task execution status.
/// </summary>
[Flags]
internal enum TaskState : short // NET_ONLY
{
/// <summary>State value representing that task is ready to run </summary>
Ready = 0,
/// <summary>State value representing that task is running </summary>
Running = 1,
/// <summary>State value representing that task ran </summary>
Complete = 2,
/// <summary>State value representing that task was cancelled </summary>
Cancelled = 4,
/// <summary>State value representing that the task should be stopped.</summary>
Stop = 8
}
/// <summary>
/// A cancellable asynchronous computation.
/// </summary>
/// <remarks>
/// <para>
/// This class provides a base implementation of
/// <see cref="IFuture{T}"/> , with methods to start and cancel
/// a computation, query to see if the computation is complete, and
/// retrieve the result of the computation. The result can only be
/// retrieved when the computation has completed; the <see cref="GetResult()"/>
/// method will block if the computation has not yet completed. Once
/// the computation has completed, the computation cannot be restarted
/// or cancelled.
/// </para>
/// <para>
/// A <see cref="FutureTask{T}"/> can be used to wrap a <see cref="Action"/>
/// delegate, <see cref="Func{T}"/> delegate, <see cref="IRunnable"/> object
/// or <see cref="ICallable{T}"/> object. Because <see cref="FutureTask{T}"/>
/// implements <see cref="IRunnable"/>, a <see cref="FutureTask{T}"/> can be
/// submitted to an <see cref="IExecutor"/> for execution.
/// </para>
/// <para>
/// In addition to serving as a standalone class, this class provides
/// protected functionality that may be useful when creating
/// customized task classes.
/// </para>
/// </remarks>
/// <typeparam name="T">
/// The result type returned by <see cref="GetResult()"/> method.
/// </typeparam>
/// <author>Doug Lea</author>
/// <author>Griffin Caprio (.NET)</author>
/// <author>Kenneth Xu</author>
internal class FutureTask<T> : IRunnableFuture<T>, IContextCopyingTask //BACKPORT_3_1
{
private readonly ICallable<T> _callable;
private T _result;
private Exception _exception;
private TaskState _taskState;
/// <summary>
/// The thread running task. When nulled after set/cancel, this
/// indicates that the results are accessible. Must be
/// volatile, to ensure visibility upon completion.
/// </summary>
private volatile Thread _runningThread;
private IContextCarrier _contextCarrier;
/// <summary>
/// Creates a <see cref="FutureTask{T}"/> that will, upon running, execute the
/// given <see cref="ICallable{T}"/>.
/// </summary>
/// <param name="callable">The callable task.</param>
/// <exception cref="System.ArgumentNullException">
/// If the <paramref name="callable"/> is <c>null</c>.
/// </exception>
public FutureTask(ICallable<T> callable)
{
if (callable == null) throw new ArgumentNullException("callable");
_callable = callable;
}
/// <summary>
/// Creates a <see cref="FutureTask{T}"/> that will, upon running, execute the
/// given <see cref="Func{T}"/> delegate.
/// </summary>
/// <param name="call">The <see cref="Func{T}"/> delegate.</param>
/// <exception cref="System.ArgumentNullException">
/// If the <paramref name="call"/> is <c>null</c>.
/// </exception>
public FutureTask(Func<T> call)
: this(Executors.CreateCallable(call))
{
}
/// <summary>
/// Creates a <see cref="FutureTask{T}"/> that will, upon running, execute the
/// given <see cref="IRunnable"/>, and arrange that <see cref="GetResult()"/>
/// will return the given <paramref name="result"/> upon successful completion.
/// </summary>
/// <param name="task">The runnable task.</param>
/// <param name="result">
/// The result to return on successful completion. If
/// you don't need a particular result, consider using
/// constructions of the form:
/// <code language="c#">
/// Future f = new FutureTask(runnable, default(T))
/// </code>
/// </param>
/// <exception cref="System.ArgumentNullException">
/// If the <paramref name="task"/> is <c>null</c>.
/// </exception>
public FutureTask(IRunnable task, T result)
: this(Executors.CreateCallable(task, result))
{
}
/// <summary>
/// Creates a <see cref="FutureTask{T}"/> that will, upon running, execute the
/// given <see cref="Action"/>, and arrange that <see cref="GetResult()"/>
/// will return the given <paramref name="result"/> upon successful completion.
/// </summary>
/// <param name="action">The <see cref="Action"/> delegate.</param>
/// <param name="result">
/// The result to return on successful completion. If
/// you don't need a particular result, consider using
/// constructions of the form:
/// <code language="c#">
/// Future f = new FutureTask(action, default(T))
/// </code>
/// </param>
/// <exception cref="ArgumentNullException">
/// If the <paramref name="action"/> is <c>null</c>.
/// </exception>
public FutureTask(Action action, T result)
: this(Executors.CreateCallable(action, result))
{
}
#region IFuture<T> Members
/// <summary>
/// Determines if this task was cancelled.
/// </summary>
/// <remarks>
/// Returns <c>true</c> if this task was cancelled before it completed
/// normally.
/// </remarks>
/// <returns> <c>true</c>if task was cancelled before it completed
/// </returns>
public virtual bool IsCancelled
{
get
{
lock (this)
{
return _taskState == TaskState.Cancelled;
}
}
}
/// <summary>
/// Returns <c>true</c> if this task completed.
/// </summary>
/// <remarks>
/// Completion may be due to normal termination, an exception, or
/// cancellation -- in all of these cases, this method will return
/// <c>true</c> if this task completed.
/// </remarks>
/// <returns> <c>true</c>if this task completed.</returns>
public virtual bool IsDone
{
get
{
lock (this)
{
return RanOrCancelled() && _runningThread == null;
}
}
}
/// <summary>
/// Waits for computation to complete, then returns its result.
/// </summary>
/// <remarks>
/// Waits if necessary for the computation to complete, and then
/// retrieves its result.
/// </remarks>
/// <returns>The computed result</returns>
/// <exception cref="CancellationException">if the computation was cancelled.</exception>
/// <exception cref="ExecutionException">if the computation threw an exception.</exception>
/// <exception cref="System.Threading.ThreadInterruptedException">if the current thread was interrupted while waiting.</exception>
public virtual T GetResult()
{
lock (this)
{
WaitFor();
return Result;
}
}
/// <summary>
/// Waits for the given time span, then returns its result.
/// </summary>
/// <remarks>
/// Waits, if necessary, for at most the <paramref name="durationToWait"/> for the computation
/// to complete, and then retrieves its result, if available.
/// </remarks>
/// <param name="durationToWait">the <see cref="System.TimeSpan"/> to wait.</param>
/// <returns>the computed result</returns>
/// <exception cref="CancellationException">if the computation was cancelled.</exception>
/// <exception cref="ExecutionException">if the computation threw an exception.</exception>
/// <exception cref="System.Threading.ThreadInterruptedException">if the current thread was interrupted while waiting.</exception>
/// <exception cref="TimeoutException">if the computation threw an exception.</exception>
public virtual T GetResult(TimeSpan durationToWait)
{
lock (this)
{
WaitFor(durationToWait);
return Result;
}
}
/// <summary>
/// Attempts to cancel execution of this task.
/// </summary>
/// <remarks>
/// This attempt will fail if the task has already completed, already been cancelled,
/// or could not be cancelled for some other reason. If successful,
/// and this task has not started when <see cref="ICancellable.Cancel()"/> is called,
/// this task should never run. If the task has already started, the in-progress tasks are allowed
/// to complete
/// </remarks>
/// <returns> <c>false</c> if the task could not be cancelled,
/// typically because it has already completed normally;
/// <c>true</c> otherwise
/// </returns>
public virtual bool Cancel()
{
return Cancel(false);
}
/// <summary>
/// Attempts to cancel execution of this task.
/// </summary>
/// <remarks>
/// This attempt will fail if the task has already completed, already been cancelled,
/// or could not be cancelled for some other reason. If successful,
/// and this task has not started when <see cref="ICancellable.Cancel()"/> is called,
/// this task should never run. If the task has already started,
/// then the <paramref name="mayInterruptIfRunning"/> parameter determines
/// whether the thread executing this task should be interrupted in
/// an attempt to stop the task.
/// </remarks>
/// <param name="mayInterruptIfRunning"><c>true</c> if the thread executing this
/// task should be interrupted; otherwise, in-progress tasks are allowed
/// to complete
/// </param>
/// <returns> <c>false</c> if the task could not be cancelled,
/// typically because it has already completed normally;
/// <c>true</c> otherwise
/// </returns>
public virtual bool Cancel(bool mayInterruptIfRunning)
{
lock (this)
{
if (RanOrCancelled()) return false;
_taskState = TaskState.Cancelled;
if (mayInterruptIfRunning)
{
var r = _runningThread;
if (r != null) r.Interrupt();
}
_runningThread = null;
Monitor.PulseAll(this);
}
Done();
return true;
}
/// <summary>
/// The entry point
/// </summary>
public virtual void Run()
{
if (_contextCarrier != null)
{
_contextCarrier.Restore();
}
lock (this)
{
if (_taskState != TaskState.Ready) return;
_taskState = TaskState.Running;
_runningThread = Thread.CurrentThread;
}
try
{
SetCompleted(_callable.Call());
}
catch (Exception ex)
{
SetFailed(ex);
}
}
#endregion
#region Protected Methods
/// <summary>
/// Sets the result of this <see cref="IFuture{T}"/> to the given
/// <paramref name="result"/> value unless
/// this future has already been set or has been cancelled.
/// </summary>
/// <remarks>
/// This method is invoked upon successful completion of the
/// computation.
/// </remarks>
/// <param name="result">
/// The value to be retured by <see cref="GetResult()"/>.
/// </param>
protected virtual void SetResult(T result)
{
SetCompleted(result);
}
/// <summary>
/// Protected method invoked when this task transitions to state
/// <see cref="ICancellable.IsDone"/> (whether normally or via cancellation).
/// </summary>
/// <remarks>
/// The default implementation does nothing. Subclasses may override
/// this method to invoke completion callbacks or perform
/// bookkeeping. Note that you can query status inside the
/// implementation of this method to determine whether this task
/// has been cancelled.
/// </remarks>
protected internal virtual void Done()
{
}
/// <summary>
/// Causes this future to report an <see cref="BitCoinSharp.Threading.Execution.ExecutionException"/>
/// with the given <see cref="System.Exception"/> as its cause, unless this <see cref="IFuture{T}"/> has
/// already been set or has been cancelled.
/// </summary>
/// <remarks>
/// This method is invoked internally by the <see cref="BitCoinSharp.Threading.IRunnable"/> method
/// upon failure of the computation.
/// </remarks>
/// <param name="t">the cause of failure</param>
protected virtual void SetException(Exception t)
{
SetFailed(t);
}
/// <summary>
/// Executes the computation without setting its result, and then
/// resets this Future to initial state, failing to do so if the
/// computation encounters an exception or is cancelled.
/// </summary>
/// <remarks>
/// This is designed for use with tasks that intrinsically execute more
/// than once.
/// </remarks>
/// <returns> <c>true</c> if successfully run and reset</returns>
protected virtual bool RunAndReset()
{
lock (this)
{
if (_taskState != TaskState.Ready) return false;
_taskState = TaskState.Running;
_runningThread = Thread.CurrentThread;
}
try
{
_callable.Call();
lock (this)
{
_runningThread = null;
if (_taskState == TaskState.Running)
{
_taskState = TaskState.Ready;
return true;
}
else
{
return false;
}
}
}
catch (Exception ex)
{
SetFailed(ex);
return false;
}
}
#endregion
/// <summary>
/// Sets the result of the task, and marks the task as completed
/// </summary>
private void SetCompleted(T value)
{
lock (this)
{
if (RanOrCancelled()) return;
_taskState = TaskState.Complete;
_result = value;
_runningThread = null;
Monitor.PulseAll(this);
}
// invoking callbacks *after* setting future as completed and
// outside the synchronization block makes it safe to call
// interrupt() from within callback code (in which case it will be
// ignored rather than cause deadlock / illegal state exception)
Done();
}
/// <summary>
/// Sets the exception result of the task, and marks the tasks as completed.
/// </summary>
private void SetFailed(Exception value)
{
lock (this)
{
if (RanOrCancelled()) return;
_taskState = TaskState.Complete;
_exception = value;
_runningThread = null;
Monitor.PulseAll(this);
}
// invoking callbacks *after* setting future as completed and
// outside the synchronization block makes it safe to call
// interrupt() from within callback code (in which case it will be
// ignored rather than cause deadlock / illegal state exception)
Done();
}
/// <summary>
/// Gets the result of the task.
/// </summary>
private T Result
{
get
{
if (_taskState == TaskState.Cancelled)
{
throw new CancellationException();
}
if (_exception != null)
{
throw new ExecutionException(_exception);
}
return _result;
}
}
/// <summary> Waits for the task to complete.</summary>
private void WaitFor()
{
while (!IsDone)
{
Monitor.Wait(this);
}
}
/// <summary>
/// Waits for the task to complete for <paramref name="durationToWait"/> or throws a
/// <see cref="TimeoutException"/>
/// if still not completed after that
/// </summary>
private void WaitFor(TimeSpan durationToWait)
{
if (durationToWait.Ticks <= 0)
throw new ArgumentOutOfRangeException(
"durationToWait", durationToWait, "Duration must be positive value.");
if (IsDone) return;
var deadline = DateTime.UtcNow.Add(durationToWait);
while (durationToWait.Ticks > 0)
{
Monitor.Wait(this, durationToWait);
if (IsDone) return;
durationToWait = deadline.Subtract(DateTime.UtcNow);
}
throw new TimeoutException();
}
private const TaskState CompleteOrCancelled = TaskState.Complete | TaskState.Cancelled;
private bool RanOrCancelled()
{
return (_taskState & CompleteOrCancelled) != 0;
}
#region IContextCopyingTask Members
IContextCarrier IContextCopyingTask.ContextCarrier
{
get { return _contextCarrier; }
set { _contextCarrier = value; }
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
public class FluidSim : MonoBehaviour
{
int m_width = 512, m_height = 512;
public Material m_guiMat, m_advectMat, m_buoyancyMat, m_divergenceMat, m_jacobiMat, m_impluseMat, m_gradientMat, m_obstaclesMat;
RenderTexture m_guiTex, m_divergenceTex, m_obstaclesTex;
RenderTexture[] m_velocityTex, m_densityTex, m_pressureTex, m_temperatureTex;
float m_timeStep = 0.125f;
float m_impulseTemperature = 10.0f;
float m_impulseDensity = 1.0f;
float m_temperatureDissipation = 0.99f;
float m_velocityDissipation = 0.99f;
float m_densityDissipation = 0.9999f;
float m_ambientTemperature = 0.0f;
float m_smokeBuoyancy = 1.0f;
float m_smokeWeight = 0.05f;
float m_cellSize = 1.0f;
float m_gradientScale = 1.0f;
Vector2 m_inverseSize;
int m_numJacobiIterations = 50;
Vector2 m_implusePos = new Vector2(0.5f, 0.0f);
float m_impluseRadius = 0.1f;
Vector2 m_obstaclePos = new Vector2(0.5f, 0.5f);
float m_obstacleRadius = 0.1f;
void Start ()
{
m_inverseSize = new Vector2(1.0f/(float)m_width, 1.0f/(float)m_height);
m_velocityTex = new RenderTexture[2];
m_densityTex = new RenderTexture[2];
m_temperatureTex = new RenderTexture[2];
m_pressureTex = new RenderTexture[2];
CreateSurface(m_velocityTex, RenderTextureFormat.RGFloat, FilterMode.Bilinear);
CreateSurface(m_densityTex, RenderTextureFormat.RFloat, FilterMode.Bilinear);
CreateSurface(m_temperatureTex, RenderTextureFormat.RFloat, FilterMode.Bilinear);
CreateSurface(m_pressureTex, RenderTextureFormat.RFloat, FilterMode.Point);
m_guiTex = new RenderTexture(m_width, m_height, 0, RenderTextureFormat.ARGB32);
m_guiTex.filterMode = FilterMode.Bilinear;
m_guiTex.wrapMode = TextureWrapMode.Clamp;
m_guiTex.Create();
m_divergenceTex = new RenderTexture(m_width, m_height, 0, RenderTextureFormat.RFloat);
m_divergenceTex.filterMode = FilterMode.Point;
m_divergenceTex.wrapMode = TextureWrapMode.Clamp;
m_divergenceTex.Create();
m_obstaclesTex = new RenderTexture(m_width, m_height, 0, RenderTextureFormat.RFloat);
m_obstaclesTex.filterMode = FilterMode.Point;
m_obstaclesTex.wrapMode = TextureWrapMode.Clamp;
m_obstaclesTex.Create();
guiTexture.texture = m_guiTex;
m_guiMat.SetTexture("_Obstacles", m_obstaclesTex);
}
void CreateSurface(RenderTexture[] surface, RenderTextureFormat format, FilterMode filter)
{
surface[0] = new RenderTexture(m_width, m_height, 0, format);
surface[0].filterMode = filter;
surface[0].wrapMode = TextureWrapMode.Clamp;
surface[0].Create();
surface[1] = new RenderTexture(m_width, m_height, 0, format);
surface[1].filterMode = filter;
surface[1].wrapMode = TextureWrapMode.Clamp;
surface[1].Create();
}
void Advect(RenderTexture velocity, RenderTexture source, RenderTexture dest, float dissipation)
{
m_advectMat.SetVector("_InverseSize", m_inverseSize);
m_advectMat.SetFloat("_TimeStep", m_timeStep);
m_advectMat.SetFloat("_Dissipation", dissipation);
m_advectMat.SetTexture("_Velocity", velocity);
m_advectMat.SetTexture("_Source", source);
m_advectMat.SetTexture("_Obstacles", m_obstaclesTex);
Graphics.Blit(null, dest, m_advectMat);
}
void ApplyBuoyancy(RenderTexture velocity, RenderTexture temperature, RenderTexture density, RenderTexture dest)
{
m_buoyancyMat.SetTexture("_Velocity", velocity);
m_buoyancyMat.SetTexture("_Temperature", temperature);
m_buoyancyMat.SetTexture("_Density", density);
m_buoyancyMat.SetFloat("_AmbientTemperature", m_ambientTemperature);
m_buoyancyMat.SetFloat("_TimeStep", m_timeStep);
m_buoyancyMat.SetFloat("_Sigma", m_smokeBuoyancy);
m_buoyancyMat.SetFloat("_Kappa", m_smokeWeight);
Graphics.Blit(null, dest, m_buoyancyMat);
}
void ApplyImpulse(RenderTexture dest, float val)
{
m_impluseMat.SetVector("_Point", m_implusePos);
m_impluseMat.SetFloat("_Radius", m_impluseRadius);
m_impluseMat.SetVector("_FillColor", new Vector3(val,val,val));
Graphics.Blit(null, dest, m_impluseMat);
}
void ComputeDivergence(RenderTexture velocity, RenderTexture dest)
{
m_divergenceMat.SetFloat("_HalfInverseCellSize", 0.5f / m_cellSize);
m_divergenceMat.SetTexture("_Velocity", velocity);
m_divergenceMat.SetVector("_InverseSize", m_inverseSize);
m_divergenceMat.SetTexture("_Obstacles", m_obstaclesTex);
Graphics.Blit(null, dest, m_divergenceMat);
}
void Jacobi(RenderTexture pressure, RenderTexture divergence, RenderTexture dest)
{
m_jacobiMat.SetTexture("_Pressure", pressure);
m_jacobiMat.SetTexture("_Divergence", divergence);
m_jacobiMat.SetVector("_InverseSize", m_inverseSize);
m_jacobiMat.SetFloat("_Alpha", -m_cellSize*m_cellSize);
m_jacobiMat.SetFloat("_InverseBeta", 0.25f);
m_jacobiMat.SetTexture("_Obstacles", m_obstaclesTex);
Graphics.Blit(null, dest, m_jacobiMat);
}
void SubtractGradient(RenderTexture velocity, RenderTexture pressure, RenderTexture dest)
{
m_gradientMat.SetTexture("_Velocity", velocity);
m_gradientMat.SetTexture("_Pressure", pressure);
m_gradientMat.SetFloat("_GradientScale", m_gradientScale);
m_gradientMat.SetVector("_InverseSize", m_inverseSize);
m_gradientMat.SetTexture("_Obstacles", m_obstaclesTex);
Graphics.Blit(null, dest, m_gradientMat);
}
void AddObstacles()
{
m_obstaclesMat.SetVector("_InverseSize", m_inverseSize);
m_obstaclesMat.SetVector("_Point", m_obstaclePos);
m_obstaclesMat.SetFloat("_Radius", m_obstacleRadius);
Graphics.Blit(null, m_obstaclesTex, m_obstaclesMat);
}
void ClearSurface(RenderTexture surface)
{
Graphics.SetRenderTarget(surface);
GL.Clear(false, true, new Color(0,0,0,0));
Graphics.SetRenderTarget(null);
}
void Swap(RenderTexture[] texs)
{
RenderTexture temp = texs[0];
texs[0] = texs[1];
texs[1] = temp;
}
void Update ()
{
//Obstacles only need to be added once but the web player doesnt show them unless there are rendered every frame or at least the first few? bug?
AddObstacles();
int READ = 0;
int WRITE = 1;
//Advect velocity against its self
Advect(m_velocityTex[READ], m_velocityTex[READ], m_velocityTex[WRITE], m_velocityDissipation);
//Advect temperature against velocity
Advect(m_velocityTex[READ], m_temperatureTex[READ], m_temperatureTex[WRITE], m_temperatureDissipation);
//Advect density against velocity
Advect(m_velocityTex[READ], m_densityTex[READ], m_densityTex[WRITE], m_densityDissipation);
Swap(m_velocityTex);
Swap(m_temperatureTex);
Swap(m_densityTex);
//Determine how the flow of the fluid changes the velocity
ApplyBuoyancy(m_velocityTex[READ], m_temperatureTex[READ], m_densityTex[READ], m_velocityTex[WRITE]);
Swap(m_velocityTex);
//Refresh the impluse of density and temperature
ApplyImpulse(m_temperatureTex[READ], m_impulseTemperature);
ApplyImpulse(m_densityTex[READ], m_impulseDensity);
//Calculates how divergent the velocity is
ComputeDivergence(m_velocityTex[READ], m_divergenceTex);
ClearSurface(m_pressureTex[READ]);
int i = 0;
for(i = 0; i < m_numJacobiIterations; ++i)
{
Jacobi(m_pressureTex[READ], m_divergenceTex, m_pressureTex[WRITE]);
Swap(m_pressureTex);
}
//Use the pressure tex that was last rendered into. This computes divergence free velocity
SubtractGradient(m_velocityTex[READ], m_pressureTex[READ], m_velocityTex[WRITE]);
Swap(m_velocityTex);
//Render the rex you want to see into gui tex. Will only use the red channel
Graphics.Blit(m_densityTex[READ], m_guiTex, m_guiMat);
}
}
| |
// 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 Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
using System.Security.Claims;
namespace System.Security.Principal
{
public enum WindowsBuiltInRole
{
Administrator = 0x220,
User = 0x221,
Guest = 0x222,
PowerUser = 0x223,
AccountOperator = 0x224,
SystemOperator = 0x225,
PrintOperator = 0x226,
BackupOperator = 0x227,
Replicator = 0x228
}
[Serializable]
public class WindowsPrincipal : ClaimsPrincipal
{
private WindowsIdentity _identity = null;
//
// Constructors.
//
private WindowsPrincipal() { }
public WindowsPrincipal(WindowsIdentity ntIdentity)
: base(ntIdentity)
{
if (ntIdentity == null)
throw new ArgumentNullException(nameof(ntIdentity));
Contract.EndContractBlock();
_identity = ntIdentity;
}
[OnDeserialized]
private void OnDeserializedMethod(StreamingContext context)
{
ClaimsIdentity firstNonNullIdentity = null;
foreach (ClaimsIdentity identity in base.Identities)
{
if (identity != null)
{
firstNonNullIdentity = identity;
break;
}
}
if (firstNonNullIdentity == null)
{
base.AddIdentity(_identity);
}
}
//
// Properties.
//
public override IIdentity Identity
{
get
{
return _identity;
}
}
//
// Public methods.
//
public override bool IsInRole(string role)
{
if (role == null || role.Length == 0)
return false;
NTAccount ntAccount = new NTAccount(role);
IdentityReferenceCollection source = new IdentityReferenceCollection(1);
source.Add(ntAccount);
IdentityReferenceCollection target = NTAccount.Translate(source, typeof(SecurityIdentifier), false);
SecurityIdentifier sid = target[0] as SecurityIdentifier;
if (sid != null)
{
if (IsInRole(sid))
{
return true;
}
}
// possible that identity has other role claims that match
return base.IsInRole(role);
}
// <summary
// Returns all of the claims from all of the identities that are windows user claims
// found in the NT token.
// </summary>
public virtual IEnumerable<Claim> UserClaims
{
get
{
foreach (ClaimsIdentity identity in Identities)
{
WindowsIdentity wi = identity as WindowsIdentity;
if (wi != null)
{
foreach (Claim claim in wi.UserClaims)
{
yield return claim;
}
}
}
}
}
// <summary
// Returns all of the claims from all of the identities that are windows device claims
// found in the NT token.
// </summary>
public virtual IEnumerable<Claim> DeviceClaims
{
get
{
foreach (ClaimsIdentity identity in Identities)
{
WindowsIdentity wi = identity as WindowsIdentity;
if (wi != null)
{
foreach (Claim claim in wi.DeviceClaims)
{
yield return claim;
}
}
}
}
}
public virtual bool IsInRole(WindowsBuiltInRole role)
{
if (role < WindowsBuiltInRole.Administrator || role > WindowsBuiltInRole.Replicator)
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)role), nameof(role));
Contract.EndContractBlock();
return IsInRole((int)role);
}
public virtual bool IsInRole(int rid)
{
SecurityIdentifier sid = new SecurityIdentifier(IdentifierAuthority.NTAuthority,
new int[] { Interop.SecurityIdentifier.SECURITY_BUILTIN_DOMAIN_RID, rid });
return IsInRole(sid);
}
// This method (with a SID parameter) is more general than the 2 overloads that accept a WindowsBuiltInRole or
// a rid (as an int). It is also better from a performance standpoint than the overload that accepts a string.
// The aformentioned overloads remain in this class since we do not want to introduce a
// breaking change. However, this method should be used in all new applications.
public virtual bool IsInRole(SecurityIdentifier sid)
{
if (sid == null)
throw new ArgumentNullException(nameof(sid));
Contract.EndContractBlock();
// special case the anonymous identity.
if (_identity.AccessToken.IsInvalid)
return false;
// CheckTokenMembership expects an impersonation token
SafeAccessTokenHandle token = SafeAccessTokenHandle.InvalidHandle;
if (_identity.ImpersonationLevel == TokenImpersonationLevel.None)
{
if (!Interop.Advapi32.DuplicateTokenEx(_identity.AccessToken,
(uint)TokenAccessLevels.Query,
IntPtr.Zero,
(uint)TokenImpersonationLevel.Identification,
(uint)TokenType.TokenImpersonation,
ref token))
throw new SecurityException(new Win32Exception().Message);
}
bool isMember = false;
// CheckTokenMembership will check if the SID is both present and enabled in the access token.
if (!Interop.Advapi32.CheckTokenMembership((_identity.ImpersonationLevel != TokenImpersonationLevel.None ? _identity.AccessToken : token),
sid.BinaryForm,
ref isMember))
throw new SecurityException(new Win32Exception().Message);
token.Dispose();
return isMember;
}
}
}
| |
#region License
// Copyright 2004-2010 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.
//
#endregion
namespace Framework.Transaction
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using Castle.Core.Configuration;
using Castle.MicroKernel.Facilities;
using Castle.Services.Transaction;
using Framework.Utils;
/// <summary>
/// Pendent
/// </summary>
public class TransactionMetaInfoStore : MarshalByRefObject
{
private static readonly String TransactionModeAtt = "transactionMode";
private static readonly String IsolationModeAtt = "isolationLevel";
private readonly IDictionary type2MetaInfo = new HybridDictionary();
private ITransactionMatcher txMatcher;
public TransactionMetaInfoStore(ITransactionMatcher txMatcher)
{
this.txMatcher = txMatcher;
}
#region MarshalByRefObject overrides
/// <summary>
/// Overrides the MBRO Lifetime initialization
/// </summary>
/// <returns>Null</returns>
public override object InitializeLifetimeService()
{
return null;
}
#endregion
///<summary>
/// Creates meta-information from a type.
///</summary>
public TransactionMetaInfo CreateMetaFromType(Type implementation)
{
bool definedTxAttribute = implementation.IsDefined(typeof(TransactionalAttribute), true);
bool matchedInConfig = txMatcher.Match(implementation);
if (definedTxAttribute == false && matchedInConfig == false)
{
return null;
}
TransactionMetaInfo metaInfo = new TransactionMetaInfo();
PopulateMetaInfoFromType(metaInfo, implementation, definedTxAttribute, matchedInConfig);
Register(implementation, metaInfo);
return metaInfo;
}
private void PopulateMetaInfoFromType(TransactionMetaInfo metaInfo, Type implementation, bool definedTxAttribute, bool matchedInConfig)
{
if (implementation == null || implementation == typeof(object) || implementation == typeof(MarshalByRefObject))
{
return;
}
MethodInfo[] methods = implementation.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
foreach (MethodInfo method in methods)
{
TransactionAttribute txAttr = null;
if (matchedInConfig)
{
txAttr = txMatcher.Match(method);
}
if (txAttr == null)//config is high priority.
{
if (definedTxAttribute)
{
object[] atts = method.GetCustomAttributes(typeof(TransactionAttribute), true);
if (atts.Length != 0)
{
txAttr = atts[0] as TransactionAttribute;
}
}
}
if (txAttr != null)
{
// only add the method as transaction injection if we also have specified a transaction attribute.
InjectTransactionAttribute injectAttr = ReflectionHelper.GetAttribute<InjectTransactionAttribute>(method);
if (injectAttr != null)
{
metaInfo.AddInjection(method);
}
metaInfo.Add(method, txAttr);
}
}
PopulateMetaInfoFromType(metaInfo, implementation.BaseType, definedTxAttribute, matchedInConfig);
}
///<summary>
/// Create meta-information from the configuration about
/// what methods should be overridden.
///</summary>
public TransactionMetaInfo CreateMetaFromConfig(Type implementation, IList<MethodInfo> methods, IConfiguration config)
{
TransactionMetaInfo metaInfo = GetMetaFor(implementation);
if (metaInfo == null)
{
metaInfo = new TransactionMetaInfo();
}
foreach (MethodInfo method in methods)
{
String transactionMode = config.Attributes[TransactionModeAtt];
String isolationLevel = config.Attributes[IsolationModeAtt];
TransactionMode mode = ObtainTransactionMode(implementation, method, transactionMode);
IsolationMode level = ObtainIsolation(implementation, method, isolationLevel);
metaInfo.Add(method, new TransactionAttribute(mode, level));
}
Register(implementation, metaInfo);
return metaInfo;
}
///<summary>
/// Gets the meta-data for the implementation.
///</summary>
///<param name="implementation"></param>
///<returns></returns>
public TransactionMetaInfo GetMetaFor(Type implementation)
{
return (TransactionMetaInfo)type2MetaInfo[implementation];
}
private static TransactionMode ObtainTransactionMode(Type implementation, MethodInfo method, string mode)
{
if (mode == null)
{
return TransactionMode.Unspecified;
}
try
{
return (TransactionMode)Enum.Parse(typeof(TransactionMode), mode, true);
}
catch (Exception)
{
String[] values = (String[])Enum.GetValues(typeof(TransactionMode));
String message = String.Format("The configuration for the class {0}, " +
"method {1}, has specified {2} on {3} attribute which is not supported. " +
"The possible values are {4}",
implementation.FullName, method.Name, mode, TransactionModeAtt, String.Join(", ", values));
throw new FacilityException(message);
}
}
private IsolationMode ObtainIsolation(Type implementation, MethodInfo method, string level)
{
if (level == null)
{
return IsolationMode.Unspecified;
}
try
{
return (IsolationMode)Enum.Parse(typeof(IsolationMode), level, true);
}
catch (Exception)
{
String[] values = (String[])Enum.GetValues(typeof(TransactionMode));
String message = String.Format("The configuration for the class {0}, " +
"method {1}, has specified {2} on {3} attribute which is not supported. " +
"The possible values are {4}",
implementation.FullName, method.Name, level, IsolationModeAtt, String.Join(", ", values));
throw new FacilityException(message);
}
}
private void Register(Type implementation, TransactionMetaInfo metaInfo)
{
type2MetaInfo[implementation] = metaInfo;
}
}
}
| |
// Copyright 2020 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
//
// 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 DebuggerApi;
using DebuggerCommonApi;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
using System;
using System.Diagnostics;
namespace YetiVSI.DebugEngine
{
public interface IBoundBreakpoint : IDebugBoundBreakpoint2
{
int GetId();
/// <summary>
/// Update the state of the pending breakpoint upon a hit.
/// </summary>
void OnHit();
}
// This represents a breakpoint that has been bound in the debugger.
public class DebugBoundBreakpoint : IBoundBreakpoint
{
public class Factory
{
readonly DebugDocumentContext.Factory _documentContextFactory;
readonly DebugCodeContext.Factory _codeContextFactory;
readonly DebugBreakpointResolution.Factory _breakpointResolutionFactory;
[Obsolete("This constructor only exists to support mocking libraries.", error: true)]
protected Factory()
{
}
public Factory(DebugDocumentContext.Factory documentContextFactory,
DebugCodeContext.Factory codeContextFactory,
DebugBreakpointResolution.Factory breakpointResolutionFactory)
{
_documentContextFactory = documentContextFactory;
_codeContextFactory = codeContextFactory;
_breakpointResolutionFactory = breakpointResolutionFactory;
}
public virtual IBoundBreakpoint Create(
IDebugPendingBreakpoint2 pendingBreakpoint, SbBreakpointLocation breakpointLocation,
IGgpDebugProgram program,
Guid languageGuid) => new DebugBoundBreakpoint(_documentContextFactory,
_codeContextFactory,
_breakpointResolutionFactory,
pendingBreakpoint,
breakpointLocation, program,
languageGuid);
}
readonly IDebugPendingBreakpoint2 _pendingBreakpoint;
readonly SbBreakpointLocation _breakpointLocation;
readonly IDebugBreakpointResolution2 _breakpointResolution;
bool _enabled;
bool _deleted;
// LLDB doesn't support the equal style pass count natively. We implement it by disabling
// the lldb breakpoint location once its hit count reaches its pass count. While that
// happens, we don't modify |enabled| so the status appears unchanged on the UI.
// DebugBoundBreakpoint.Enable does not reenable the underlying breakpoint or breakpoint
// locations if it is disabled by reaching its pass count.
bool _disabledByPassCount;
BP_PASSCOUNT _passCount;
// Hit count at the last hit count reset. Since lldb does not support resetting hit count,
// we just remember the lldb hit count value at the last reset (to subtract it from
// the lldb hit count on GetHitCount queries).
int _baseHitCount = 0;
// Constructor with factories for tests.
DebugBoundBreakpoint(DebugDocumentContext.Factory documentContextFactory,
DebugCodeContext.Factory codeContextFactory,
DebugBreakpointResolution.Factory breakpointResolutionFactory,
IDebugPendingBreakpoint2 pendingBreakpoint,
SbBreakpointLocation breakpointLocation, IGgpDebugProgram program,
Guid languageGuid)
{
_pendingBreakpoint = pendingBreakpoint;
_breakpointLocation = breakpointLocation;
_enabled = true;
_deleted = false;
_disabledByPassCount = false;
SbAddress address = breakpointLocation.GetAddress();
if (address != null)
{
LineEntryInfo lineEntry = address.GetLineEntry();
IDebugDocumentContext2 documentContext = null;
// |lineEntry| is null if the breakpoint is set on an external function.
if (lineEntry != null)
{
documentContext = documentContextFactory.Create(lineEntry);
}
IDebugCodeContext2 codeContext = codeContextFactory.Create(
target: program.Target,
address: breakpointLocation.GetLoadAddress(),
functionName: null,
documentContext,
languageGuid);
_breakpointResolution = breakpointResolutionFactory.Create(codeContext, program);
}
else
{
Trace.WriteLine("Warning: Unable to obtain address from breakpoint location." +
" No breakpoint resolution created.");
}
}
#region IBoundBreakpoint functions
public int GetId() => _breakpointLocation.GetId();
public void OnHit()
{
GetHitCount(out uint hitCount);
switch (_passCount.stylePassCount)
{
case enum_BP_PASSCOUNT_STYLE.BP_PASSCOUNT_EQUAL:
if (hitCount != _passCount.dwPassCount)
{
Trace.WriteLine($"Error: breakpoint's hit count {hitCount} != its " +
$"pass count {_passCount.dwPassCount} on hit");
}
// The breakpoint has reached its pass count. Disable |breakpointLocation| and
// make sure it doesn't get re-enabled until the pass count is reset.
_disabledByPassCount = true;
_breakpointLocation.SetEnabled(false);
break;
case enum_BP_PASSCOUNT_STYLE.BP_PASSCOUNT_MOD:
_breakpointLocation.SetIgnoreCount(_passCount.dwPassCount - 1);
break;
}
}
#endregion IBoundBreakpoint functions
#region IDebugBoundBreakpoint2 functions
public int Delete()
{
if (_deleted)
{
return AD7Constants.E_BP_DELETED;
}
// TODO: Figure out if it's possible for VS to delete a single call site,
// as it doesn't look like LLDB supports that. If that's the case we'll need to fake it
// by disabling the breakpoint. Currently this is only coded to handle being called
// from DebugPendingBreakpoint::Delete().
_deleted = true;
return VSConstants.S_OK;
}
public int Enable(int enable)
{
if (_deleted)
{
return AD7Constants.E_BP_DELETED;
}
_enabled = Convert.ToBoolean(enable);
if (!_disabledByPassCount)
{
_breakpointLocation.SetEnabled(_enabled);
}
return VSConstants.S_OK;
}
public int GetBreakpointResolution(out IDebugBreakpointResolution2 breakpointResolution)
{
breakpointResolution = null;
if (_deleted)
{
return AD7Constants.E_BP_DELETED;
}
if (_breakpointResolution == null)
{
return VSConstants.E_FAIL;
}
breakpointResolution = _breakpointResolution;
return VSConstants.S_OK;
}
public int GetHitCount(out uint hitCount)
{
hitCount = 0;
if (_deleted)
{
return AD7Constants.E_BP_DELETED;
}
hitCount = _breakpointLocation.GetHitCount();
if (hitCount < _baseHitCount)
{
Trace.WriteLine(
$"Error: Inconsistent hitcount - base hit count ({_baseHitCount}) is " +
$"smaller than actual hitcount {hitCount}.");
hitCount = 0;
}
else
{
hitCount = Convert.ToUInt32(Convert.ToInt32(hitCount) - _baseHitCount);
}
return VSConstants.S_OK;
}
public int GetPendingBreakpoint(out IDebugPendingBreakpoint2 pendingBreakpoint)
{
pendingBreakpoint = _pendingBreakpoint;
return VSConstants.S_OK;
}
public int GetState(enum_BP_STATE[] state)
{
state[0] = enum_BP_STATE.BPS_NONE;
if (_deleted)
{
state[0] = enum_BP_STATE.BPS_DELETED;
}
else if (_enabled)
{
state[0] = enum_BP_STATE.BPS_ENABLED;
}
else if (!_enabled)
{
state[0] = enum_BP_STATE.BPS_DISABLED;
}
return VSConstants.S_OK;
}
public int SetCondition(BP_CONDITION breakpointCondition)
{
if (_deleted)
{
return AD7Constants.E_BP_DELETED;
}
switch (breakpointCondition.styleCondition)
{
case enum_BP_COND_STYLE.BP_COND_NONE:
_breakpointLocation.SetCondition("");
break;
case enum_BP_COND_STYLE.BP_COND_WHEN_TRUE:
_breakpointLocation.SetCondition(breakpointCondition.bstrCondition);
break;
default:
return VSConstants.E_NOTIMPL;
}
return VSConstants.S_OK;
}
public int SetHitCount(uint hitCount)
{
if (_deleted)
{
return AD7Constants.E_BP_DELETED;
}
var totalHitCount = _breakpointLocation.GetHitCount();
_baseHitCount = Convert.ToInt32(totalHitCount) - Convert.ToInt32(hitCount);
// Recalculate the criteria that depend on hit count.
SetPassCount(_passCount);
return VSConstants.S_OK;
}
public int SetPassCount(BP_PASSCOUNT breakpointPassCount)
{
if (_deleted)
{
return AD7Constants.E_BP_DELETED;
}
_passCount = breakpointPassCount;
_breakpointLocation.SetEnabled(_enabled);
_disabledByPassCount = false;
GetHitCount(out uint hitCount);
switch (breakpointPassCount.stylePassCount)
{
case enum_BP_PASSCOUNT_STYLE.BP_PASSCOUNT_NONE:
_breakpointLocation.SetIgnoreCount(0);
break;
case enum_BP_PASSCOUNT_STYLE.BP_PASSCOUNT_EQUAL_OR_GREATER:
_breakpointLocation.SetIgnoreCount(
(uint)Math.Max(0, (int)breakpointPassCount.dwPassCount - (int)hitCount - 1));
break;
case enum_BP_PASSCOUNT_STYLE.BP_PASSCOUNT_EQUAL:
if (breakpointPassCount.dwPassCount > hitCount)
{
_breakpointLocation.SetIgnoreCount(breakpointPassCount.dwPassCount - hitCount -
1);
}
else
{
// Current hit count is already beyond the specified pass count.
// The breakpoint will not break.
_breakpointLocation.SetEnabled(false);
_disabledByPassCount = true;
}
break;
case enum_BP_PASSCOUNT_STYLE.BP_PASSCOUNT_MOD:
_breakpointLocation.SetIgnoreCount(breakpointPassCount.dwPassCount -
hitCount % breakpointPassCount.dwPassCount - 1);
break;
}
return VSConstants.S_OK;
}
#endregion IDebugBoundBreakpoint2 functions
}
}
| |
#region WatiN Copyright (C) 2006-2011 Jeroen van Menen
//Copyright 2006-2011 Jeroen van Menen
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion Copyright
using System;
using System.Text.RegularExpressions;
using Moq;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using WatiN.Core.Exceptions;
using WatiN.Core.Native;
using WatiN.Core.UnitTests.TestUtils;
using TimeoutException=WatiN.Core.Exceptions.TimeoutException;
namespace WatiN.Core.UnitTests
{
[TestFixture]
public class DocumentTests : BaseWithBrowserTests
{
private int _originalWaitUntilExistsTimeOut;
public override Uri TestPageUri
{
get { return MainURI; }
}
[SetUp]
public override void TestSetUp()
{
base.TestSetUp();
_originalWaitUntilExistsTimeOut = Settings.WaitUntilExistsTimeOut;
}
[TearDown]
public void TearDown()
{
Settings.WaitUntilExistsTimeOut = _originalWaitUntilExistsTimeOut;
}
[Test]
public void DocumentIsIElementsContainer()
{
// GIVEN
var documentType = typeof(Document);
// WHEN
var actual = documentType.GetInterface(typeof(IElementContainer).ToString());
// THEN
Assert.That(actual, Is.Not.Null, "document should implement IElementsContainer");
}
[Test]
public void DocumentUrlandUri()
{
ExecuteTest(browser =>
{
var uri = new Uri(browser.Url);
Assert.AreEqual(MainURI, uri);
Assert.AreEqual(browser.Uri, uri);
});
}
[Test]
public void RunScriptShouldCallRunScriptOnNativeDocument()
{
// GIVEN
var domContainer = new Mock<DomContainer>().Object;
var nativeDocumentMock = new Mock<INativeDocument>();
var nativeDocument = nativeDocumentMock.Object;
var document = new TestDocument(domContainer, nativeDocument);
var scriptCode = "alert('hello')";
// WHEN
document.RunScript(scriptCode);
// THEN
nativeDocumentMock.Verify(doc => doc.RunScript(scriptCode, "javascript"));
}
[Test]
public void RunJavaScript()
{
ExecuteTest(browser =>
{
var documentVariableName = browser.NativeDocument.JavaScriptVariableName;
browser.RunScript(documentVariableName + ".getElementById('last').innerHTML = 'java script has run';");
Assert.That(browser.Div("last").Text, Is.EqualTo("java script has run"));
try
{
browser.RunScript("a+1");
Assert.Fail("Expected RunScriptException");
}
catch (RunScriptException)
{
// OK;
}
});
}
[Test]
public void Text()
{
// GIVEN
var nativeDocumentMock = new Mock<INativeDocument>();
var nativeElementMock = new Mock<INativeElement>();
nativeElementMock.Expect(x => x.IsElementReferenceStillValid()).Returns(true);
nativeElementMock.Expect(element => element.GetAttributeValue("innertext")).Returns("Something");
nativeDocumentMock.Expect(native => native.Body).Returns(nativeElementMock.Object);
var domContainer = new Mock<DomContainer>().Object;
var document = new TestDocument(domContainer, nativeDocumentMock.Object);
// WHEN
var text = document.Text;
// THEN
Assert.That(text, Is.EqualTo("Something"));
}
[Test]
public void TestEval()
{
ExecuteTest(browser =>
{
var result = browser.Eval("2+5");
Assert.That(result, Is.EqualTo("7"));
result = browser.Eval("'te' + 'st'");
Assert.That(result, Is.EqualTo("test"));
try
{
browser.Eval("a+1");
Assert.Fail("Expected JavaScriptException");
}
catch (JavaScriptException){}
// Make sure a valid eval after a failed eval executes OK.
var documentVariableName = browser.NativeDocument.JavaScriptVariableName;
result = browser.Eval(documentVariableName + ".getElementById('last').innerHTML = 'java script has run';4+4;");
Assert.AreEqual("8", result);
Assert.That(browser.Div("last").Text, Is.EqualTo("java script has run"));
browser.GoTo(TestPageUri);
}
);
}
[Test]
public void RunScriptAndEval()
{
ExecuteTest(browser =>
{
browser.RunScript("var myVar = 5;");
var result = browser.Eval("myVar;");
Assert.AreEqual("5", result);
});
}
[Test]
public void ContainsText()
{
ExecuteTest(browser =>
{
Assert.IsTrue(browser.ContainsText("Contains text in DIV"), "Text not found");
Assert.IsFalse(browser.ContainsText("abcde"), "Text incorrectly found");
Assert.IsTrue(browser.ContainsText(new Regex("Contains text in DIV")), "Regex: Text not found");
Assert.IsFalse(browser.ContainsText(new Regex("abcde")), "Regex: Text incorrectly found");
});
}
[Test]
public void FindText()
{
ExecuteTest(browser =>
{
Assert.AreEqual("Contains text in DIV", browser.FindText(new Regex("Contains .* in DIV")), "Text not found");
Assert.IsNull(browser.FindText(new Regex("abcde")), "Text incorrectly found");
});
}
[Test] //, ExpectedException(typeof(Exceptions.TimeoutException))]
public void WaitUntilContainsTextShouldThrowTimeOutException()
{
ExecuteTest(browser =>
{
// GIVEN
Settings.WaitUntilExistsTimeOut = 1;
HtmlInjector.Start(browser, "some text 1", 2);
try
{
browser.WaitUntilContainsText("some text 1");
// THEN
Assert.Fail("Expected " + typeof(TimeoutException));
}
catch (Exception e)
{
Assert.That(e, Is.InstanceOfType(typeof(TimeoutException)));
}
finally
{
browser.GoTo(TestPageUri);
}
});
}
[Test]
public void WaitUntilContainsTextShouldReturn()
{
ExecuteTest(browser =>
{
Settings.WaitUntilExistsTimeOut = 2;
HtmlInjector.Start(browser, "some text 2", 1);
browser.WaitUntilContainsText("some text 2");
browser.GoTo(TestPageUri);
});
}
[Test] //, ExpectedException(typeof(Exceptions.TimeoutException))]
public void WaitUntilContainsTextRegexShouldThrowTimeOutException()
{
ExecuteTest(browser =>
{
// GIVEN
Settings.WaitUntilExistsTimeOut = 1;
HtmlInjector.Start(browser, "some text 3", 2);
// WHEN
try
{
browser.WaitUntilContainsText(new Regex("me text 3"));
// THEN
Assert.Fail("Expected " + typeof(TimeoutException));
}
catch (Exception e)
{
Assert.That(e, Is.InstanceOfType(typeof(TimeoutException)));
}
finally
{
browser.GoTo(TestPageUri);
}
});
}
[Test]
public void WaitUntilContainsTextRegexShouldReturn()
{
Settings.WaitUntilExistsTimeOut = 2;
ExecuteTest(browser =>
{
HtmlInjector.Start(browser, "some text 4", 1);
browser.WaitUntilContainsText(new Regex("me text 4"));
browser.GoTo(TestPageUri);
});
}
[Test, Ignore("TODO")]
public void TestAreaPredicateOverload()
{
ExecuteTest(browser =>
{
var Area = browser.Area(t => t.Id == "readonlytext");
Assert.That(Area.Id, Is.EqualTo("readonlytext"));
});
}
[Test]
public void TestButtonPredicateOverload()
{
ExecuteTest(browser =>
{
var Button = browser.Button(t => t.Id == "popupid");
Assert.That(Button.Id, Is.EqualTo("popupid"));
});
}
[Test]
public void TestCheckBoxPredicateOverload()
{
ExecuteTest(browser =>
{
var CheckBox = browser.CheckBox(t => t.Id == "Checkbox2");
Assert.That(CheckBox.Id, Is.EqualTo("Checkbox2"));
});
}
[Test]
public void TestElementPredicateOverload()
{
ExecuteTest(browser =>
{
var Element = browser.Element(t => t.Id == "Radio1");
Assert.That(Element.Id, Is.EqualTo("Radio1"));
});
}
[Test]
public void TestFileUploadPredicateOverload()
{
ExecuteTest(browser =>
{
var FileUpload = browser.FileUpload(t => t.Id == "upload");
Assert.That(FileUpload.Id, Is.EqualTo("upload"));
});
}
[Test]
public void TestFormPredicateOverload()
{
ExecuteTest(browser =>
{
var Form = browser.Form(t => t.Id == "Form");
Assert.That(Form.Id, Is.EqualTo("Form"));
});
}
[Test]
public void TestLabelPredicateOverload()
{
ExecuteTest(browser =>
{
var Label = browser.Label(t => t.For == "Checkbox21");
Assert.That(Label.For, Is.EqualTo("Checkbox21"));
});
}
[Test]
public void TestLinkPredicateOverload()
{
ExecuteTest(browser =>
{
var Link = browser.Link(t => t.Id == "testlinkid");
Assert.That(Link.Id, Is.EqualTo("testlinkid"));
});
}
[Test]
public void TestParaPredicateOverload()
{
ExecuteTest(browser =>
{
var Para = browser.Para(t => t.Id == "links");
Assert.That(Para.Id, Is.EqualTo("links"));
});
}
[Test]
public void TestRadioButtonPredicateOverload()
{
ExecuteTest(browser =>
{
var RadioButton = browser.RadioButton(t => t.Id == "Radio1");
Assert.That(RadioButton.Id, Is.EqualTo("Radio1"));
});
}
[Test]
public void TestSelectListPredicateOverload()
{
ExecuteTest(browser =>
{
var SelectList = browser.SelectList(t => t.Id == "Select1");
Assert.That(SelectList.Id, Is.EqualTo("Select1"));
});
}
[Test]
public void TestTablePredicateOverload()
{
ExecuteTest(browser =>
{
var Table = browser.Table(t => t.Id == "table1");
Assert.That(Table.Id, Is.EqualTo("table1"));
});
}
[Test]
public void TestTableCellPredicateOverload()
{
ExecuteTest(browser =>
{
var TableCell = browser.TableCell(t => t.Id == "td2");
Assert.That(TableCell.Id, Is.EqualTo("td2"));
});
}
[Test]
public void TestTableRowPredicateOverload()
{
ExecuteTest(browser =>
{
var TableRow = browser.TableRow(t => t.Id == "row0");
Assert.That(TableRow.Id, Is.EqualTo("row0"));
});
}
[Test, Ignore("TODO")]
public void TestTableBodyPredicateOverload()
{
ExecuteTest(browser =>
{
var TableBody = browser.TableBody(t => t.Id == "readonlytext");
Assert.That(TableBody.Id, Is.EqualTo("readonlytext"));
});
}
[Test]
public void TestTextFieldPredicateOverload()
{
ExecuteTest(browser =>
{
var textField = browser.TextField(t => t.Id == "readonlytext");
Assert.That(textField.Id, Is.EqualTo("readonlytext"));
});
}
[Test]
public void TestSpanPredicateOverload()
{
ExecuteTest(browser =>
{
var Span = browser.Span(t => t.Id == "Span1");
Assert.That(Span.Id, Is.EqualTo("Span1"));
});
}
[Test]
public void TestDivPredicateOverload()
{
ExecuteTest(browser =>
{
var Div = browser.Div(t => t.Id == "NextAndPreviousTests");
Assert.That(Div.Id, Is.EqualTo("NextAndPreviousTests"));
});
}
[Test, Ignore("TODO")]
public void TestImagePredicateOverload()
{
ExecuteTest(browser =>
{
var Image = browser.Image(t => t.Id == "readonlytext");
Assert.That(Image.Id, Is.EqualTo("readonlytext"));
});
}
[Test, Ignore("but it doesn't")]
public void FFelementInnerHtmlToInnerTextShouldBeWorkingForThisAsWell()
{
// GIVEN
var ieText = Ie.Text;
// WHEN
var ffText = Firefox.Text;
// THEN
Assert.That(ffText, Is.EqualTo(ieText));
}
[Test]
public void TextShouldStartWith()
{
ExecuteTest(browser =>
{
// GIVEN
var newlineSpaces = new Regex("[\n\r ]*");
// WHEN
var text = browser.Text;
// remove all newlines and spaces.... browser differences
text = newlineSpaces.Replace(text, "");
// THEN
Assert.That(text, NUnit.Framework.SyntaxHelpers.Text.StartsWith("col1col2a1a2b1b2"));
});
}
[Test]
public void HtmlShouldStartWithBodyTag()
{
ExecuteTest(browser =>
{
// GIVEN
// WHEN
var outerHtml = browser.Html.ToLowerInvariant();
outerHtml = outerHtml.Replace("\r\n", "");
// THEN
Assert.That(outerHtml, NUnit.Framework.SyntaxHelpers.Text.StartsWith("<body style="));
});
}
}
public class TestDocument : Document
{
private readonly INativeDocument document;
public TestDocument(DomContainer container, INativeDocument document)
: base(container)
{
this.document = document;
}
public override INativeDocument NativeDocument
{
get { return document; }
}
protected override string GetAttributeValueImpl(string attributeName)
{
throw new NotImplementedException();
}
}
}
| |
// 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.Collections.Generic;
using System.Runtime.Versioning;
namespace System.Xml
{
internal sealed partial class XmlValidatingReaderImpl : XmlReader, IXmlLineInfo, IXmlNamespaceResolver
{
//
// Private helper types
//
// ParsingFunction = what should the reader do when the next Read() is called
private enum ParsingFunction
{
Read = 0,
Init,
ParseDtdFromContext,
ResolveEntityInternally,
InReadBinaryContent,
ReaderClosed,
Error,
None,
}
internal class ValidationEventHandling : IValidationEventHandling
{
// Fields
private XmlValidatingReaderImpl _reader;
private ValidationEventHandler _eventHandler;
// Constructor
internal ValidationEventHandling(XmlValidatingReaderImpl reader)
{
_reader = reader;
}
// IValidationEventHandling interface
#region IValidationEventHandling interface
object IValidationEventHandling.EventHandler
{
get { return _eventHandler; }
}
void IValidationEventHandling.SendEvent(Exception /*XmlSchemaException*/ exception, XmlSeverityType severity)
{
if (_eventHandler != null)
{
_eventHandler(_reader, new ValidationEventArgs((XmlSchemaException)exception, severity));
}
else if (_reader._validationType != ValidationType.None && severity == XmlSeverityType.Error)
{
throw exception;
}
}
#endregion
// XmlValidatingReaderImpl helper methods
internal void AddHandler(ValidationEventHandler handler)
{
_eventHandler += handler;
}
internal void RemoveHandler(ValidationEventHandler handler)
{
_eventHandler -= handler;
}
}
//
// Fields
//
// core text reader
private XmlReader _coreReader;
private XmlTextReaderImpl _coreReaderImpl;
private IXmlNamespaceResolver _coreReaderNSResolver;
// validation
private ValidationType _validationType;
private BaseValidator _validator;
#pragma warning disable 618
private XmlSchemaCollection _schemaCollection;
#pragma warning restore 618
private bool _processIdentityConstraints;
// parsing function (state)
private ParsingFunction _parsingFunction = ParsingFunction.Init;
// event handling
private ValidationEventHandling _eventHandling;
// misc
private XmlParserContext _parserContext;
// helper for Read[Element]ContentAs{Base64,BinHex} methods
private ReadContentAsBinaryHelper _readBinaryHelper;
// Outer XmlReader exposed to the user - either XmlValidatingReader or XmlValidatingReaderImpl (when created via XmlReader.Create).
// Virtual methods called from within XmlValidatingReaderImpl must be called on the outer reader so in case the user overrides
// some of the XmlValidatingReader methods we will call the overriden version.
private XmlReader _outerReader;
//
// Constructors
//
// Initializes a new instance of XmlValidatingReaderImpl class with the specified XmlReader.
// This constructor is used when creating XmlValidatingReaderImpl for V1 XmlValidatingReader
internal XmlValidatingReaderImpl(XmlReader reader)
{
XmlAsyncCheckReader asyncCheckReader = reader as XmlAsyncCheckReader;
if (asyncCheckReader != null)
{
reader = asyncCheckReader.CoreReader;
}
_outerReader = this;
_coreReader = reader;
_coreReaderNSResolver = reader as IXmlNamespaceResolver;
_coreReaderImpl = reader as XmlTextReaderImpl;
if (_coreReaderImpl == null)
{
XmlTextReader tr = reader as XmlTextReader;
if (tr != null)
{
_coreReaderImpl = tr.Impl;
}
}
if (_coreReaderImpl == null)
{
throw new ArgumentException(SR.Arg_ExpectingXmlTextReader, nameof(reader));
}
_coreReaderImpl.EntityHandling = EntityHandling.ExpandEntities;
_coreReaderImpl.XmlValidatingReaderCompatibilityMode = true;
_processIdentityConstraints = true;
#pragma warning disable 618
_schemaCollection = new XmlSchemaCollection(_coreReader.NameTable);
_schemaCollection.XmlResolver = GetResolver();
_eventHandling = new ValidationEventHandling(this);
_coreReaderImpl.ValidationEventHandling = _eventHandling;
_coreReaderImpl.OnDefaultAttributeUse = new XmlTextReaderImpl.OnDefaultAttributeUseDelegate(ValidateDefaultAttributeOnUse);
_validationType = ValidationType.Auto;
SetupValidation(ValidationType.Auto);
#pragma warning restore 618
}
// Initializes a new instance of XmlValidatingReaderImpl class for parsing fragments with the specified string, fragment type and parser context
// This constructor is used when creating XmlValidatingReaderImpl for V1 XmlValidatingReader
// SxS: This method resolves an Uri but does not expose it to the caller. It's OK to suppress the SxS warning.
internal XmlValidatingReaderImpl(string xmlFragment, XmlNodeType fragType, XmlParserContext context)
: this(new XmlTextReader(xmlFragment, fragType, context))
{
if (_coreReader.BaseURI.Length > 0)
{
_validator.BaseUri = GetResolver().ResolveUri(null, _coreReader.BaseURI);
}
if (context != null)
{
_parsingFunction = ParsingFunction.ParseDtdFromContext;
_parserContext = context;
}
}
// Initializes a new instance of XmlValidatingReaderImpl class for parsing fragments with the specified stream, fragment type and parser context
// This constructor is used when creating XmlValidatingReaderImpl for V1 XmlValidatingReader
// SxS: This method resolves an Uri but does not expose it to the caller. It's OK to suppress the SxS warning.
internal XmlValidatingReaderImpl(Stream xmlFragment, XmlNodeType fragType, XmlParserContext context)
: this(new XmlTextReader(xmlFragment, fragType, context))
{
if (_coreReader.BaseURI.Length > 0)
{
_validator.BaseUri = GetResolver().ResolveUri(null, _coreReader.BaseURI);
}
if (context != null)
{
_parsingFunction = ParsingFunction.ParseDtdFromContext;
_parserContext = context;
}
}
// Initializes a new instance of XmlValidatingReaderImpl class with the specified arguments.
// This constructor is used when creating XmlValidatingReaderImpl reader via "XmlReader.Create(..)"
internal XmlValidatingReaderImpl(XmlReader reader, ValidationEventHandler settingsEventHandler, bool processIdentityConstraints)
{
XmlAsyncCheckReader asyncCheckReader = reader as XmlAsyncCheckReader;
if (asyncCheckReader != null)
{
reader = asyncCheckReader.CoreReader;
}
_outerReader = this;
_coreReader = reader;
_coreReaderImpl = reader as XmlTextReaderImpl;
if (_coreReaderImpl == null)
{
XmlTextReader tr = reader as XmlTextReader;
if (tr != null)
{
_coreReaderImpl = tr.Impl;
}
}
if (_coreReaderImpl == null)
{
throw new ArgumentException(SR.Arg_ExpectingXmlTextReader, nameof(reader));
}
_coreReaderImpl.XmlValidatingReaderCompatibilityMode = true;
_coreReaderNSResolver = reader as IXmlNamespaceResolver;
_processIdentityConstraints = processIdentityConstraints;
#pragma warning disable 618
_schemaCollection = new XmlSchemaCollection(_coreReader.NameTable);
#pragma warning restore 618
_schemaCollection.XmlResolver = GetResolver();
_eventHandling = new ValidationEventHandling(this);
if (settingsEventHandler != null)
{
_eventHandling.AddHandler(settingsEventHandler);
}
_coreReaderImpl.ValidationEventHandling = _eventHandling;
_coreReaderImpl.OnDefaultAttributeUse = new XmlTextReaderImpl.OnDefaultAttributeUseDelegate(ValidateDefaultAttributeOnUse);
_validationType = ValidationType.DTD;
SetupValidation(ValidationType.DTD);
}
//
// XmlReader members
//
// Returns the current settings of the reader
public override XmlReaderSettings Settings
{
get
{
XmlReaderSettings settings;
if (_coreReaderImpl.V1Compat)
{
settings = null;
}
else
{
settings = _coreReader.Settings;
}
if (settings != null)
{
settings = settings.Clone();
}
else
{
settings = new XmlReaderSettings();
}
settings.ValidationType = ValidationType.DTD;
if (!_processIdentityConstraints)
{
settings.ValidationFlags &= ~XmlSchemaValidationFlags.ProcessIdentityConstraints;
}
settings.ReadOnly = true;
return settings;
}
}
// Returns the type of the current node.
public override XmlNodeType NodeType
{
get
{
return _coreReader.NodeType;
}
}
// Returns the name of the current node, including prefix.
public override string Name
{
get
{
return _coreReader.Name;
}
}
// Returns local name of the current node (without prefix)
public override string LocalName
{
get
{
return _coreReader.LocalName;
}
}
// Returns namespace name of the current node.
public override string NamespaceURI
{
get
{
return _coreReader.NamespaceURI;
}
}
// Returns prefix associated with the current node.
public override string Prefix
{
get
{
return _coreReader.Prefix;
}
}
// Returns true if the current node can have Value property != string.Empty.
public override bool HasValue
{
get
{
return _coreReader.HasValue;
}
}
// Returns the text value of the current node.
public override string Value
{
get
{
return _coreReader.Value;
}
}
// Returns the depth of the current node in the XML element stack
public override int Depth
{
get
{
return _coreReader.Depth;
}
}
// Returns the base URI of the current node.
public override string BaseURI
{
get
{
return _coreReader.BaseURI;
}
}
// Returns true if the current node is an empty element (for example, <MyElement/>).
public override bool IsEmptyElement
{
get
{
return _coreReader.IsEmptyElement;
}
}
// Returns true of the current node is a default attribute declared in DTD.
public override bool IsDefault
{
get
{
return _coreReader.IsDefault;
}
}
// Returns the quote character used in the current attribute declaration
public override char QuoteChar
{
get
{
return _coreReader.QuoteChar;
}
}
// Returns the current xml:space scope.
public override XmlSpace XmlSpace
{
get
{
return _coreReader.XmlSpace;
}
}
// Returns the current xml:lang scope.</para>
public override string XmlLang
{
get
{
return _coreReader.XmlLang;
}
}
// Returns the current read state of the reader
public override ReadState ReadState
{
get
{
return (_parsingFunction == ParsingFunction.Init) ? ReadState.Initial : _coreReader.ReadState;
}
}
// Returns true if the reader reached end of the input data
public override bool EOF
{
get
{
return _coreReader.EOF;
}
}
// Returns the XmlNameTable associated with this XmlReader
public override XmlNameTable NameTable
{
get
{
return _coreReader.NameTable;
}
}
// Returns encoding of the XML document
internal Encoding Encoding
{
get
{
return _coreReaderImpl.Encoding;
}
}
// Returns the number of attributes on the current node.
public override int AttributeCount
{
get
{
return _coreReader.AttributeCount;
}
}
// Returns value of an attribute with the specified Name
public override string GetAttribute(string name)
{
return _coreReader.GetAttribute(name);
}
// Returns value of an attribute with the specified LocalName and NamespaceURI
public override string GetAttribute(string localName, string namespaceURI)
{
return _coreReader.GetAttribute(localName, namespaceURI);
}
// Returns value of an attribute at the specified index (position)
public override string GetAttribute(int i)
{
return _coreReader.GetAttribute(i);
}
// Moves to an attribute with the specified Name
public override bool MoveToAttribute(string name)
{
if (!_coreReader.MoveToAttribute(name))
{
return false;
}
_parsingFunction = ParsingFunction.Read;
return true;
}
// Moves to an attribute with the specified LocalName and NamespceURI
public override bool MoveToAttribute(string localName, string namespaceURI)
{
if (!_coreReader.MoveToAttribute(localName, namespaceURI))
{
return false;
}
_parsingFunction = ParsingFunction.Read;
return true;
}
// Moves to an attribute at the specified index (position)
public override void MoveToAttribute(int i)
{
_coreReader.MoveToAttribute(i);
_parsingFunction = ParsingFunction.Read;
}
// Moves to the first attribute of the current node
public override bool MoveToFirstAttribute()
{
if (!_coreReader.MoveToFirstAttribute())
{
return false;
}
_parsingFunction = ParsingFunction.Read;
return true;
}
// Moves to the next attribute of the current node
public override bool MoveToNextAttribute()
{
if (!_coreReader.MoveToNextAttribute())
{
return false;
}
_parsingFunction = ParsingFunction.Read;
return true;
}
// If on attribute, moves to the element that contains the attribute node
public override bool MoveToElement()
{
if (!_coreReader.MoveToElement())
{
return false;
}
_parsingFunction = ParsingFunction.Read;
return true;
}
// Reads and validated next node from the input data
public override bool Read()
{
switch (_parsingFunction)
{
case ParsingFunction.Read:
if (_coreReader.Read())
{
ProcessCoreReaderEvent();
return true;
}
else
{
_validator.CompleteValidation();
return false;
}
case ParsingFunction.ParseDtdFromContext:
_parsingFunction = ParsingFunction.Read;
ParseDtdFromParserContext();
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;
ResolveEntityInternally();
goto case ParsingFunction.Read;
case ParsingFunction.InReadBinaryContent:
_parsingFunction = ParsingFunction.Read;
_readBinaryHelper.Finish();
goto case ParsingFunction.Read;
default:
Debug.Fail($"Unexpected parsing function {_parsingFunction}");
return false;
}
}
// Closes the input stream ot TextReader, changes the ReadState to Closed and sets all properties to zero/string.Empty
public override void Close()
{
_coreReader.Close();
_parsingFunction = ParsingFunction.ReaderClosed;
}
// Returns NamespaceURI associated with the specified prefix in the current namespace scope.
public override string LookupNamespace(string prefix)
{
return _coreReaderImpl.LookupNamespace(prefix);
}
// Iterates through the current attribute value's text and entity references chunks.
public override bool ReadAttributeValue()
{
if (_parsingFunction == ParsingFunction.InReadBinaryContent)
{
_parsingFunction = ParsingFunction.Read;
_readBinaryHelper.Finish();
}
if (!_coreReader.ReadAttributeValue())
{
return false;
}
_parsingFunction = ParsingFunction.Read;
return true;
}
public override bool CanReadBinaryContent
{
get
{
return true;
}
}
public override int ReadContentAsBase64(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 = _readBinaryHelper.ReadContentAsBase64(buffer, index, count);
// setup parsingFunction
_parsingFunction = ParsingFunction.InReadBinaryContent;
return readCount;
}
public override int ReadContentAsBinHex(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 = _readBinaryHelper.ReadContentAsBinHex(buffer, index, count);
// setup parsingFunction
_parsingFunction = ParsingFunction.InReadBinaryContent;
return readCount;
}
public override int ReadElementContentAsBase64(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 = _readBinaryHelper.ReadElementContentAsBase64(buffer, index, count);
// setup parsingFunction
_parsingFunction = ParsingFunction.InReadBinaryContent;
return readCount;
}
public override int ReadElementContentAsBinHex(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 = _readBinaryHelper.ReadElementContentAsBinHex(buffer, index, count);
// setup parsingFunction
_parsingFunction = ParsingFunction.InReadBinaryContent;
return readCount;
}
// Returns true if the XmlReader knows how to resolve general entities
public override bool CanResolveEntity
{
get
{
return true;
}
}
// Resolves the current entity reference node
public override void ResolveEntity()
{
if (_parsingFunction == ParsingFunction.ResolveEntityInternally)
{
_parsingFunction = ParsingFunction.Read;
}
_coreReader.ResolveEntity();
}
internal XmlReader OuterReader
{
get
{
return _outerReader;
}
set
{
#pragma warning disable 618
Debug.Assert(value is XmlValidatingReader);
#pragma warning restore 618
_outerReader = value;
}
}
internal void MoveOffEntityReference()
{
if (_outerReader.NodeType == XmlNodeType.EntityReference && _parsingFunction != ParsingFunction.ResolveEntityInternally)
{
if (!_outerReader.Read())
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
}
}
public override string ReadString()
{
MoveOffEntityReference();
return base.ReadString();
}
//
// IXmlLineInfo members
//
public bool HasLineInfo()
{
return true;
}
// Returns the line number of the current node
public int LineNumber
{
get
{
return ((IXmlLineInfo)_coreReader).LineNumber;
}
}
// Returns the line number of the current node
public int LinePosition
{
get
{
return ((IXmlLineInfo)_coreReader).LinePosition;
}
}
//
// IXmlNamespaceResolver members
//
IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope)
{
return this.GetNamespacesInScope(scope);
}
string IXmlNamespaceResolver.LookupNamespace(string prefix)
{
return this.LookupNamespace(prefix);
}
string IXmlNamespaceResolver.LookupPrefix(string namespaceName)
{
return this.LookupPrefix(namespaceName);
}
// Internal IXmlNamespaceResolver methods
internal IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope)
{
return _coreReaderNSResolver.GetNamespacesInScope(scope);
}
internal string LookupPrefix(string namespaceName)
{
return _coreReaderNSResolver.LookupPrefix(namespaceName);
}
//
// XmlValidatingReader members
//
// Specufies the validation event handler that wil get warnings and errors related to validation
internal event ValidationEventHandler ValidationEventHandler
{
add
{
_eventHandling.AddHandler(value);
}
remove
{
_eventHandling.RemoveHandler(value); ;
}
}
// returns the schema type of the current node
internal object SchemaType
{
get
{
if (_validationType != ValidationType.None)
{
XmlSchemaType schemaTypeObj = _coreReaderImpl.InternalSchemaType as XmlSchemaType;
if (schemaTypeObj != null && schemaTypeObj.QualifiedName.Namespace == XmlReservedNs.NsXs)
{
return schemaTypeObj.Datatype;
}
return _coreReaderImpl.InternalSchemaType;
}
else
return null;
}
}
// returns the underlying XmlTextReader or XmlTextReaderImpl
internal XmlReader Reader
{
get
{
return (XmlReader)_coreReader;
}
}
// returns the underlying XmlTextReaderImpl
internal XmlTextReaderImpl ReaderImpl
{
get
{
return _coreReaderImpl;
}
}
// specifies the validation type (None, DDT, XSD, XDR, Auto)
internal ValidationType ValidationType
{
get
{
return _validationType;
}
set
{
if (ReadState != ReadState.Initial)
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
_validationType = value;
SetupValidation(value);
}
}
// current schema collection used for validationg
#pragma warning disable 618
internal XmlSchemaCollection Schemas
{
get
{
return _schemaCollection;
}
}
#pragma warning restore 618
// Spefifies whether general entities should be automatically expanded or not
internal EntityHandling EntityHandling
{
get
{
return _coreReaderImpl.EntityHandling;
}
set
{
_coreReaderImpl.EntityHandling = value;
}
}
// Specifies XmlResolver used for opening the XML document and other external references
internal XmlResolver XmlResolver
{
set
{
_coreReaderImpl.XmlResolver = value;
_validator.XmlResolver = value;
_schemaCollection.XmlResolver = value;
}
}
// Disables or enables support of W3C XML 1.0 Namespaces
internal bool Namespaces
{
get
{
return _coreReaderImpl.Namespaces;
}
set
{
_coreReaderImpl.Namespaces = value;
}
}
// Returns typed value of the current node (based on the type specified by schema)
public object ReadTypedValue()
{
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 (!_outerReader.Read())
{
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 Value;
}
}
}
//
// Private implementation methods
//
private void ParseDtdFromParserContext()
{
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 = dtdParser.ParseFreeFloatingDtd(_parserContext.BaseURI, _parserContext.DocTypeName, _parserContext.PublicId,
_parserContext.SystemId, _parserContext.InternalSubset, proxy);
_coreReaderImpl.SetDtdInfo(dtdInfo);
ValidateDtd();
}
private void ValidateDtd()
{
IDtdInfo dtdInfo = _coreReaderImpl.DtdInfo;
if (dtdInfo != null)
{
switch (_validationType)
{
#pragma warning disable 618
case ValidationType.Auto:
SetupValidation(ValidationType.DTD);
goto case ValidationType.DTD;
#pragma warning restore 618
case ValidationType.DTD:
case ValidationType.None:
_validator.DtdInfo = dtdInfo;
break;
}
}
}
private void ResolveEntityInternally()
{
Debug.Assert(_coreReader.NodeType == XmlNodeType.EntityReference);
int initialDepth = _coreReader.Depth;
_outerReader.ResolveEntity();
while (_outerReader.Read() && _coreReader.Depth > initialDepth) ;
}
// SxS: This method resolves an Uri but does not expose it to caller. It's OK to suppress the SxS warning.
private void SetupValidation(ValidationType valType)
{
_validator = BaseValidator.CreateInstance(valType, this, _schemaCollection, _eventHandling, _processIdentityConstraints);
XmlResolver resolver = GetResolver();
_validator.XmlResolver = resolver;
if (_outerReader.BaseURI.Length > 0)
{
_validator.BaseUri = (resolver == null) ? new Uri(_outerReader.BaseURI, UriKind.RelativeOrAbsolute) : resolver.ResolveUri(null, _outerReader.BaseURI);
}
_coreReaderImpl.ValidationEventHandling = (_validationType == ValidationType.None) ? null : _eventHandling;
}
private static XmlResolver s_tempResolver;
// This is needed because we can't have the setter for XmlResolver public and with internal getter.
private XmlResolver GetResolver()
{
XmlResolver tempResolver = _coreReaderImpl.GetResolver();
if (tempResolver == null && !_coreReaderImpl.IsResolverSet)
{
// it is safe to return valid resolver as it'll be used in the schema validation
if (s_tempResolver == null)
s_tempResolver = new XmlUrlResolver();
return s_tempResolver;
}
return tempResolver;
}
//
// Internal methods for validators, DOM, XPathDocument etc.
//
private void ProcessCoreReaderEvent()
{
switch (_coreReader.NodeType)
{
case XmlNodeType.Whitespace:
if (_coreReader.Depth > 0 || _coreReaderImpl.FragmentType != XmlNodeType.Document)
{
if (_validator.PreserveWhitespace)
{
_coreReaderImpl.ChangeCurrentNodeType(XmlNodeType.SignificantWhitespace);
}
}
goto default;
case XmlNodeType.DocumentType:
ValidateDtd();
break;
case XmlNodeType.EntityReference:
_parsingFunction = ParsingFunction.ResolveEntityInternally;
goto default;
default:
_coreReaderImpl.InternalSchemaType = null;
_coreReaderImpl.InternalTypedValue = null;
_validator.Validate();
break;
}
}
internal BaseValidator Validator
{
get
{
return _validator;
}
set
{
_validator = value;
}
}
internal override XmlNamespaceManager NamespaceManager
{
get
{
return _coreReaderImpl.NamespaceManager;
}
}
internal bool StandAlone
{
get
{
return _coreReaderImpl.StandAlone;
}
}
internal object SchemaTypeObject
{
set
{
_coreReaderImpl.InternalSchemaType = value;
}
}
internal object TypedValueObject
{
get
{
return _coreReaderImpl.InternalTypedValue;
}
set
{
_coreReaderImpl.InternalTypedValue = value;
}
}
internal bool AddDefaultAttribute(SchemaAttDef attdef)
{
return _coreReaderImpl.AddDefaultAttributeNonDtd(attdef);
}
internal override IDtdInfo DtdInfo
{
get { return _coreReaderImpl.DtdInfo; }
}
internal void ValidateDefaultAttributeOnUse(IDtdDefaultAttributeInfo defaultAttribute, XmlTextReaderImpl coreReader)
{
SchemaAttDef attdef = defaultAttribute as SchemaAttDef;
if (attdef == null)
{
return;
}
if (!attdef.DefaultValueChecked)
{
SchemaInfo schemaInfo = coreReader.DtdInfo as SchemaInfo;
if (schemaInfo == null)
{
return;
}
DtdValidator.CheckDefaultValue(attdef, schemaInfo, _eventHandling, coreReader.BaseURI);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Xunit;
using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier<
Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
using VerifyVB = Test.Utilities.VisualBasicSecurityCodeFixVerifier<
Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.NetFramework.Analyzers.UnitTests
{
public partial class DoNotUseInsecureDtdProcessingAnalyzerTests
{
private static DiagnosticResult GetCA3075DataSetReadXmlCSharpResultAt(int line, int column)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleDoNotUseDtdProcessingOverloads).WithLocation(line, column).WithArguments("ReadXml");
#pragma warning restore RS0030 // Do not used banned APIs
private static DiagnosticResult GetCA3075DataSetReadXmlBasicResultAt(int line, int column)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleDoNotUseDtdProcessingOverloads).WithLocation(line, column).WithArguments("ReadXml");
#pragma warning restore RS0030 // Do not used banned APIs
[Fact]
public async Task UseDataSetReadXmlShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Xml;
using System.Data;
namespace TestNamespace
{
public class UseXmlReaderForDataSetReadXml
{
public void TestMethod1214(string path)
{
DataSet ds = new DataSet();
ds.ReadXml(path);
}
}
}
",
GetCA3075DataSetReadXmlCSharpResultAt(12, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Xml
Imports System.Data
Namespace TestNamespace
Public Class UseXmlReaderForDataSetReadXml
Public Sub TestMethod1214(path As String)
Dim ds As New DataSet()
ds.ReadXml(path)
End Sub
End Class
End Namespace",
GetCA3075DataSetReadXmlBasicResultAt(9, 13)
);
}
[Fact]
public async Task UseDataSetReadXmlInGetShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Data;
class TestClass
{
public DataSet Test
{
get {
var src = """";
DataSet ds = new DataSet();
ds.ReadXml(src);
return ds;
}
}
}",
GetCA3075DataSetReadXmlCSharpResultAt(11, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Data
Class TestClass
Public ReadOnly Property Test() As DataSet
Get
Dim src = """"
Dim ds As New DataSet()
ds.ReadXml(src)
Return ds
End Get
End Property
End Class",
GetCA3075DataSetReadXmlBasicResultAt(9, 13)
);
}
[Fact]
public async Task UseDataSetReadXmlInSetShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Data;
class TestClass
{
DataSet privateDoc;
public DataSet GetDoc
{
set
{
if (value == null)
{
var src = """";
DataSet ds = new DataSet();
ds.ReadXml(src);
privateDoc = ds;
}
else
privateDoc = value;
}
}
}",
GetCA3075DataSetReadXmlCSharpResultAt(15, 21)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Data
Class TestClass
Private privateDoc As DataSet
Public WriteOnly Property GetDoc() As DataSet
Set
If value Is Nothing Then
Dim src = """"
Dim ds As New DataSet()
ds.ReadXml(src)
privateDoc = ds
Else
privateDoc = value
End If
End Set
End Property
End Class",
GetCA3075DataSetReadXmlBasicResultAt(11, 17)
);
}
[Fact]
public async Task UseDataSetReadXmlInTryBlockShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System;
using System.Data;
class TestClass
{
private void TestMethod()
{
try
{
var src = """";
DataSet ds = new DataSet();
ds.ReadXml(src);
}
catch (Exception) { throw; }
finally { }
}
}",
GetCA3075DataSetReadXmlCSharpResultAt(13, 17)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.Data
Class TestClass
Private Sub TestMethod()
Try
Dim src = """"
Dim ds As New DataSet()
ds.ReadXml(src)
Catch generatedExceptionName As Exception
Throw
Finally
End Try
End Sub
End Class",
GetCA3075DataSetReadXmlBasicResultAt(10, 13)
);
}
[Fact]
public async Task UseDataSetReadXmlInCatchBlockShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System;
using System.Data;
class TestClass
{
private void TestMethod()
{
try { }
catch (Exception)
{
var src = """";
DataSet ds = new DataSet();
ds.ReadXml(src);
}
finally { }
}
}",
GetCA3075DataSetReadXmlCSharpResultAt(14, 17)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.Data
Class TestClass
Private Sub TestMethod()
Try
Catch generatedExceptionName As Exception
Dim src = """"
Dim ds As New DataSet()
ds.ReadXml(src)
Finally
End Try
End Sub
End Class",
GetCA3075DataSetReadXmlBasicResultAt(11, 13)
);
}
[Fact]
public async Task UseDataSetReadXmlInFinallyBlockShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System;
using System.Data;
class TestClass
{
private void TestMethod()
{
try { }
catch (Exception) { throw; }
finally
{
var src = """";
DataSet ds = new DataSet();
ds.ReadXml(src);
}
}
}",
GetCA3075DataSetReadXmlCSharpResultAt(15, 17)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.Data
Class TestClass
Private Sub TestMethod()
Try
Catch generatedExceptionName As Exception
Throw
Finally
Dim src = """"
Dim ds As New DataSet()
ds.ReadXml(src)
End Try
End Sub
End Class",
GetCA3075DataSetReadXmlBasicResultAt(13, 13)
);
}
[Fact]
public async Task UseDataSetReadXmlInAsyncAwaitShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Threading.Tasks;
using System.Data;
class TestClass
{
private async Task TestMethod()
{
await Task.Run(() => {
var src = """";
DataSet ds = new DataSet();
ds.ReadXml(src);
});
}
private async void TestMethod2()
{
await TestMethod();
}
}",
GetCA3075DataSetReadXmlCSharpResultAt(12, 17)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Threading.Tasks
Imports System.Data
Class TestClass
Private Async Function TestMethod() As Task
Await Task.Run(Function()
Dim src = """"
Dim ds As New DataSet()
ds.ReadXml(src)
End Function)
End Function
Private Async Sub TestMethod2()
Await TestMethod()
End Sub
End Class",
GetCA3075DataSetReadXmlBasicResultAt(10, 9)
);
}
[Fact]
public async Task UseDataSetReadXmlInDelegateShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Data;
class TestClass
{
delegate void Del();
Del d = delegate () {
var src = """";
DataSet ds = new DataSet();
ds.ReadXml(src);
};
}",
GetCA3075DataSetReadXmlCSharpResultAt(11, 9)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Data
Class TestClass
Private Delegate Sub Del()
Private d As Del = Sub()
Dim src = """"
Dim ds As New DataSet()
ds.ReadXml(src)
End Sub
End Class",
GetCA3075DataSetReadXmlBasicResultAt(10, 5)
);
}
[Fact]
public async Task UseDataSetReadXmlWithXmlReaderShouldNotGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Xml;
using System.Data;
namespace TestNamespace
{
public class UseXmlReaderForDataSetReadXml
{
public void TestMethod1214Ok(XmlReader reader)
{
DataSet ds = new DataSet();
ds.ReadXml(reader);
}
}
}
"
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Xml
Imports System.Data
Namespace TestNamespace
Public Class UseXmlReaderForDataSetReadXml
Public Sub TestMethod1214Ok(reader As XmlReader)
Dim ds As New DataSet()
ds.ReadXml(reader)
End Sub
End Class
End Namespace");
}
}
}
| |
#region Namespaces
using System;
using System.Globalization;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using Application = Autodesk.Revit.ApplicationServices.Application;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Analysis;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.DB.Electrical;
using Autodesk.Revit.DB.Lighting;
using System.Windows.Forms;
#endregion
namespace STFExporter
{
/// <summary>
/// Default decimal writer
/// </summary>
public static class DoubleExtensions
{
public static string ToDecimalString(this double value)
{
return value.ToString(CultureInfo.GetCultureInfo("en-US"));
}
}
/// <summary>
/// Command Class
/// </summary>
[Transaction(TransactionMode.Manual)]
[Regeneration(RegenerationOption.Manual)]
public class Command : IExternalCommand
{
public Application _app;
public Document _doc;
public string writer = "";
public double meterMultiplier = 0.3048;
public List<ElementId> distinctLuminaires = new List<ElementId>();
public string stfVersionNum = "1.0.5";
public bool intlVersion;
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Application app = uiapp.Application;
Document doc = uidoc.Document;
_app = app;
_doc = doc;
// Set project units to Meters then back after
// This is how DIALux reads the data from the STF File.
Units pUnit = doc.GetUnits();
FormatOptions formatOptions = pUnit.GetFormatOptions(UnitType.UT_Length);
//DisplayUnitType curUnitType = pUnit.GetDisplayUnitType();
DisplayUnitType curUnitType = formatOptions.DisplayUnits;
using (Transaction tx = new Transaction(doc))
{
tx.Start("STF EXPORT");
const DisplayUnitType meters = DisplayUnitType.DUT_METERS;
formatOptions.DisplayUnits = meters;
// Comment out, different in 2014
//formatOptions.Units = meters;
//formatOptions.Rounding = 0.0000000001;]
formatOptions.Accuracy = 0.0000000001;
// Fix decimal symbol for int'l versions (set back again after finish)
if (pUnit.DecimalSymbol == DecimalSymbol.Comma)
{
intlVersion = true;
//TESTING
//TaskDialog.Show("INTL", "You have an internationalized version of Revit!");
formatOptions.UseDigitGrouping = false;
pUnit.DecimalSymbol = DecimalSymbol.Dot;
}
// Filter for only active view.
try
{
ElementLevelFilter filter = new ElementLevelFilter(doc.ActiveView.GenLevel.Id);
FilteredElementCollector fec = new FilteredElementCollector(doc, doc.ActiveView.Id)
.OfCategory(BuiltInCategory.OST_MEPSpaces)
.WherePasses(filter);
if (fec.Count() < 1)
{
throw new NullReferenceException();
}
int numOfRooms = fec.Count();
writer += "[VERSION]\n"
+ "STFF=" + stfVersionNum + "\n"
+ "Progname=Revit\n"
+ "Progvers=" + app.VersionNumber + "\n"
+ "[Project]\n"
+ "Name=" + _doc.ProjectInformation.Name + "\n"
+ "Date=" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" +
DateTime.Now.Day.ToString() + "\n"
+ "Operator=" + app.Username + "\n"
+ "NrRooms=" + numOfRooms + "\n";
for (int i = 1; i < numOfRooms + 1; i++)
{
string _dialuxRoomName = "Room" + i.ToString() + "=ROOM.R" + i.ToString();
writer += _dialuxRoomName + "\n";
}
int increment = 1;
// Space writer
try
{
foreach (Element e in fec)
{
Space s = e as Space;
string roomRNum = "ROOM.R" + increment.ToString();
writer += "[" + roomRNum + "]\n";
SpaceInfoWriter(s.Id, roomRNum);
increment++;
}
// Write out Luminaires to bottom
writeLumenairs();
// Reset back to original units
formatOptions.DisplayUnits = curUnitType;
if (intlVersion)
pUnit.DecimalSymbol = DecimalSymbol.Comma;
tx.Commit();
SaveFileDialog dialog = new SaveFileDialog
{
FileName = doc.ProjectInformation.Name,
Filter = "STF File | *.stf",
FilterIndex = 2,
RestoreDirectory = true
};
if (dialog.ShowDialog() == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(dialog.FileName);
string[] ar = writer.Split('\n');
for (int i = 0; i < ar.Length; i++)
{
sw.WriteLine(ar[i]);
}
sw.Close();
}
return Result.Succeeded;
}
catch (IndexOutOfRangeException)
{
return Result.Failed;
}
}
catch (NullReferenceException)
{
TaskDialog.Show("Incorrect View","Cannot find Spaces to export.\nMake sure you are in a Floorplan or Ceiling Plan view and Spaces are visible.");
return Result.Failed;
}
}
}
#region Private Methods
private void writeLumenairs()
{
FilteredElementCollector fecFixtures = new FilteredElementCollector(_doc)
.OfCategory(BuiltInCategory.OST_LightingFixtures)
.OfClass(typeof(FamilySymbol));
foreach (Element e in fecFixtures)
{
FamilySymbol fs = e as FamilySymbol;
string load = "";
string flux = "";
Parameter pload = fs.get_Parameter(BuiltInParameter.RBS_ELEC_APPARENT_LOAD);
Parameter pflux = fs.get_Parameter(BuiltInParameter.FBX_LIGHT_LIMUNOUS_FLUX);
if (pflux != null)
{
load = pload.AsValueString();
flux = pflux.AsValueString();
writer += "[" + fs.Name.Replace(" ", "") + "]\n";
writer += "Manufacturer=" + "\n"
+ "Name=" + "\n"
+ "OrderNr=" + "\n"
+ "Box=1 1 0" + "\n" //need to fix per bounding box size (i guess);
+ "Shape=0" + "\n"
+ "Load=" + load.Remove(load.Length - 3) + "\n"
+ "Flux=" + flux.Remove(flux.Length - 3) + "\n"
+ "NrLamps=" + getNumLamps(fs) + "\n"
+ "MountingType=1\n";
}
}
}
private string getNumLamps(FamilySymbol fs)
{
if (fs.LookupParameter("Number of Lamps") != null)
{
return fs.LookupParameter("Number of Lamps").ToString();
}
else
{
// TODO:
// Parse from IES file
var file = fs.get_Parameter(BuiltInParameter.FBX_LIGHT_PHOTOMETRIC_FILE);
return "1"; //for now
}
}
private void SpaceInfoWriter(ElementId spaceID, string RoomRNum)
{
try
{
//const double MAX_ROUNDING_PRECISION = 0.000000000001;
// Get info from Space
Space roomSpace = _doc.GetElement(spaceID) as Space;
//Space roomSpace = _doc.get_Element(spaceID) as Space;
// VARS
string name = roomSpace.Name;
double height = roomSpace.UnboundedHeight * meterMultiplier;
double workPlane = roomSpace.LightingCalculationWorkplane * meterMultiplier;
// Get room vertices
List<String> verticies = new List<string>();
verticies = getVertexPoints(roomSpace);
int numPoints = getVertexPointNums(roomSpace);
// Write out Top part of room entry
writer += "Name=" + name + "\n"
+ "Height=" + height.ToDecimalString() + "\n"
+ "WorkingPlane=" + workPlane.ToDecimalString() + "\n"
+ "NrPoints=" + numPoints.ToString() + "\n";
// Write vertices for each point in vertex numbers
for (int i = 0; i < numPoints; i++)
{
int i2 = i + 1;
writer += "Point" + i2 + "=" + verticies.ElementAt(i) + "\n";
}
double cReflect = roomSpace.CeilingReflectance;
double fReflect = roomSpace.FloorReflectance;
double wReflect = roomSpace.WallReflectance;
// Write out ceiling reflectance
writer += "R_Ceiling=" + cReflect.ToDecimalString() + "\n";
IList<ElementId> elemIds = roomSpace.GetMonitoredLocalElementIds();
foreach (ElementId e in elemIds)
{
TaskDialog.Show("s", _doc.GetElement(e).Name);
}
// Get fixtures within space
FilteredElementCollector fec = new FilteredElementCollector(_doc)
.OfCategory(BuiltInCategory.OST_LightingFixtures)
.OfClass(typeof(FamilyInstance));
int count = 0;
foreach (Element e in fec)
{
FamilyInstance fi = e as FamilyInstance;
if (fi.Space != null)
{
if (fi.Space.Id == spaceID)
{
FamilySymbol fs = _doc.GetElement(fi.GetTypeId()) as FamilySymbol;
//FamilySymbol fs = _doc.get_Element(fi.GetTypeId()) as FamilySymbol;
int lumNum = count + 1;
string lumName = "Lum" + lumNum.ToString();
LocationPoint locpt = fi.Location as LocationPoint;
XYZ fixtureloc = locpt.Point;
double X = fixtureloc.X * meterMultiplier;
double Y = fixtureloc.Y * meterMultiplier;
double Z = fixtureloc.Z * meterMultiplier;
double rotation = locpt.Rotation;
writer += lumName + "=" + fs.Name.Replace(" ", "") + "\n";
writer += lumName + ".Pos=" + X.ToDecimalString() + " " + Y.ToDecimalString() + " " + Z.ToDecimalString() + "\n";
writer += lumName + ".Rot=0 0 0" + "\n"; //need to figure out this rotation; Update: cannot determine. Almost impossible for Dialux
count++;
}
}
}
// Write out Lums part
writer += "NrLums=" + count.ToString() + "\n";
// Write out Struct part
writer += "NrStruct=0\n";
// Write out Furn part
writer += "NrFurns=" + getFurns(spaceID, RoomRNum);
}
catch (IndexOutOfRangeException)
{
throw new IndexOutOfRangeException();
}
}
private string getFurns(ElementId spaceID, string RoomRNum)
{
string furnsOutput = String.Empty;
// Go through the room and write out the windows/doors
// DOORS //
// Get all doors that have space where id equals current space.
FilteredElementCollector fecDoors = new FilteredElementCollector(_doc)
.OfCategory(BuiltInCategory.OST_Doors)
.OfClass(typeof(FamilyInstance));
// WINDOWS //
FilteredElementCollector fecWindows = new FilteredElementCollector(_doc)
.OfCategory(BuiltInCategory.OST_Windows)
.OfClass(typeof(FamilyInstance));
List<Element> doorsList = new List<Element>();
List<Element> windowList = new List<Element>();
foreach (Element e in fecDoors)
{
FamilyInstance fi = e as FamilyInstance;
if (fi != null && fi.Space != null && fi.Space.Id == spaceID)
doorsList.Add(fi);
}
foreach (Element e in fecWindows)
{
FamilyInstance fi = e as FamilyInstance;
if (fi != null && fi.Space != null && fi.Space.Id == spaceID)
windowList.Add(fi);
}
//Add Number of Furns to string
furnsOutput += (doorsList.Count + windowList.Count).ToString() + "\n";
// Loop through new list of Doors
int furnNumber = 1;
foreach (Element e in doorsList)
{
FamilyInstance fi = e as FamilyInstance;
// Door Width (in meters)
string doorWidth = (fi.Symbol.get_Parameter(BuiltInParameter.DOOR_WIDTH).AsDouble() * 0.3048).ToDecimalString();
// Door height (in meters)
string doorHeight = (fi.Symbol.get_Parameter(BuiltInParameter.DOOR_HEIGHT).AsDouble() * 0.3048).ToDecimalString();
LocationPoint lp = fi.Location as LocationPoint;
XYZ p = new XYZ(lp.Point.X * 0.30, lp.Point.Y * 0.30, 0);
//XYZ p = new XYZ(lp.Point.X, lp.Point.Y, 0);
string lps = p.ToString().Substring(1, p.ToString().Length - 2);
//string lps = lp.Point.ToDecimalString().Substring(1, lp.Point.ToDecimalString().Length - 2);
string sfurnNumber = "Furn" + furnNumber.ToString();
//Furn1=door
//Furn1.Ref=ROOM.R1.F1
//Furn1.Rot=90.00 0.00 0.00
//Furn1.Pos=1.151 3.67 0
//Furn1.Size=1.0 2.0 0.0
furnsOutput += sfurnNumber + "=door\n";
furnsOutput += sfurnNumber + ".Ref=" + RoomRNum + ".F" + furnNumber.ToString() + "\n";
// TODO: fix rotation
furnsOutput += sfurnNumber + ".Rot=90.00 0.00 0.00" + "\n"; //rotation???
// TODO: fix positioning...
furnsOutput += sfurnNumber + ".Pos=" + lps + "\n";
furnsOutput += sfurnNumber + ".Size=" + doorWidth + " " + doorHeight + " 0.00\n";
//Inrement furns
furnNumber++;
}
// WINDOWS //
foreach (Element e in fecWindows)
{
FamilyInstance fi = e as FamilyInstance;
// Window Width
string windowWidth = (fi.Symbol.get_Parameter(BuiltInParameter.WINDOW_WIDTH).AsDouble() * 0.3048).ToDecimalString();
// Window Height
string windowHeight = (fi.Symbol.get_Parameter(BuiltInParameter.WINDOW_HEIGHT).AsDouble() * 0.3048).ToDecimalString();
LocationPoint lp = fi.Location as LocationPoint;
//XYZ p = new XYZ(lp.Point.X * 0.30, lp.Point.Y * 0.30, lp.Point.Z * 0.30);
Transform t1 = fi.GetTransform();
XYZ p = new XYZ(t1.BasisX.X * 0.30,t1.BasisX.Y*0.30,lp.Point.Z * 0.30);
string lps = p.ToString().Substring(1, p.ToString().Length - 2);
string sFurnNumber = "Furn" + furnNumber.ToString();
furnsOutput += sFurnNumber + "=win\n";
furnsOutput += sFurnNumber + ".Ref=" + RoomRNum + ".F" + furnNumber.ToString() + "\n";
// TODO: fix rotation
furnsOutput += sFurnNumber + ".Rot=90.00 0.00 0.00" + "\n"; //rotation???
// TODO: fix positioning...
furnsOutput += sFurnNumber + ".Pos=" + lps + "\n";
furnsOutput += sFurnNumber + ".Size=" + windowWidth + " " + windowHeight + " 0.00\n";
//Inrement furns
furnNumber++;
}
return furnsOutput;
}
private List<string> getVertexPoints(Space roomSpace)
{
List<string> verticies = new List<string>();
SpatialElementBoundaryOptions opts = new SpatialElementBoundaryOptions();
IList<IList<Autodesk.Revit.DB.BoundarySegment>> bsa = roomSpace.GetBoundarySegments(opts);
if (bsa.Count > 0)
{
foreach (Autodesk.Revit.DB.BoundarySegment bs in bsa[0])
{
// For 2014
//var X = bs.Curve.get_EndPoint(0).X * meterMultiplier;
//var Y = bs.Curve.get_EndPoint(0).Y * meterMultiplier;
var X = bs.GetCurve().GetEndPoint(0).X * meterMultiplier;
var Y = bs.GetCurve().GetEndPoint(0).Y * meterMultiplier;
verticies.Add(X.ToDecimalString() + " " + Y.ToDecimalString());
}
}
else
{
verticies.Add("0 0");
}
return verticies;
}
private int getVertexPointNums(Space roomSpace)
{
SpatialElementBoundaryOptions opts = new SpatialElementBoundaryOptions();
try
{
IList<IList<Autodesk.Revit.DB.BoundarySegment>> bsa = roomSpace.GetBoundarySegments(opts);
return bsa[0].Count;
}
catch (Exception)
{
TaskDialog.Show("OOPS!", "Seems you have a Space in your view that is not in a properly enclosed region. \n\nPlease remove these Spaces or re-establish them inside of boundary walls and run the Exporter again.");
throw new IndexOutOfRangeException();
}
}
#endregion
}
}
| |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace UnrealBuildTool
{
class HTML5Platform : UEBuildPlatform
{
// use -win32 for win32 builds. ( build html5 platform as a win32 binary for debugging )
[XmlConfig]
public static string HTML5Architecture = "";
/**
* Whether platform supports switching SDKs during runtime
*
* @return true if supports
*/
protected override bool PlatformSupportsAutoSDKs()
{
return false;
}
public override string GetSDKTargetPlatformName()
{
return "HTML5";
}
/**
* Returns SDK string as required by the platform
*
* @return Valid SDK string
*/
protected override string GetRequiredSDKString()
{
return HTML5SDKInfo.EmscriptenVersion();
}
protected override String GetRequiredScriptVersionString()
{
return "3.0";
}
// The current architecture - affects everything about how UBT operates on HTML5
public override string GetActiveArchitecture()
{
// by default, use an empty architecture (which is really just a modifier to the platform for some paths/names)
return HTML5Architecture;
}
// F5 should always try to run the Win32 version
public override string ModifyNMakeOutput(string ExeName)
{
// nmake Run should always run the win32 version
return Path.ChangeExtension(ExeName+"-win32", ".exe");
}
/**
* Whether the required external SDKs are installed for this platform
*/
protected override SDKStatus HasRequiredManualSDKInternal()
{
if (!HTML5SDKInfo.IsSDKInstalled())
{
return SDKStatus.Invalid;
}
return SDKStatus.Valid;
}
public override bool CanUseXGE()
{
return (GetActiveArchitecture() == "-win32");
}
/**
* Register the platform with the UEBuildPlatform class
*/
protected override void RegisterBuildPlatformInternal()
{
// Make sure the SDK is installed
if ((ProjectFileGenerator.bGenerateProjectFiles == true) || (HasRequiredSDKsInstalled() == SDKStatus.Valid))
{
bool bRegisterBuildPlatform = true;
// make sure we have the HTML5 files; if not, then this user doesn't really have HTML5 access/files, no need to compile HTML5!
string EngineSourcePath = Path.Combine(ProjectFileGenerator.EngineRelativePath, "Source");
string HTML5TargetPlatformFile = Path.Combine(EngineSourcePath, "Developer", "HTML5", "HTML5TargetPlatform", "HTML5TargetPlatform.Build.cs");
if ((File.Exists(HTML5TargetPlatformFile) == false))
{
bRegisterBuildPlatform = false;
Log.TraceWarning("Missing required components (.... HTML5TargetPlatformFile, others here...). Check source control filtering, or try resyncing.");
}
if (bRegisterBuildPlatform == true)
{
// Register this build platform for HTML5
Log.TraceVerbose(" Registering for {0}", UnrealTargetPlatform.HTML5.ToString());
UEBuildPlatform.RegisterBuildPlatform(UnrealTargetPlatform.HTML5, this);
if (GetActiveArchitecture() == "-win32")
{
UEBuildPlatform.RegisterPlatformWithGroup(UnrealTargetPlatform.HTML5, UnrealPlatformGroup.Simulator);
}
else
{
UEBuildPlatform.RegisterPlatformWithGroup(UnrealTargetPlatform.HTML5, UnrealPlatformGroup.Device);
}
}
}
}
/**
* Retrieve the CPPTargetPlatform for the given UnrealTargetPlatform
*
* @param InUnrealTargetPlatform The UnrealTargetPlatform being build
*
* @return CPPTargetPlatform The CPPTargetPlatform to compile for
*/
public override CPPTargetPlatform GetCPPTargetPlatform(UnrealTargetPlatform InUnrealTargetPlatform)
{
switch (InUnrealTargetPlatform)
{
case UnrealTargetPlatform.HTML5:
return CPPTargetPlatform.HTML5;
}
throw new BuildException("HTML5Platform::GetCPPTargetPlatform: Invalid request for {0}", InUnrealTargetPlatform.ToString());
}
/**
* Get the extension to use for the given binary type
*
* @param InBinaryType The binary type being built
*
* @return string The binary extension (ie 'exe' or 'dll')
*/
public override string GetBinaryExtension(UEBuildBinaryType InBinaryType)
{
if (GetActiveArchitecture() == "-win32")
{
switch (InBinaryType)
{
case UEBuildBinaryType.DynamicLinkLibrary:
return ".dll";
case UEBuildBinaryType.Executable:
return ".exe";
case UEBuildBinaryType.StaticLibrary:
return ".lib";
case UEBuildBinaryType.Object:
return ".o";
case UEBuildBinaryType.PrecompiledHeader:
return ".gch";
}
return base.GetBinaryExtension(InBinaryType);
}
else
{
switch (InBinaryType)
{
case UEBuildBinaryType.DynamicLinkLibrary:
return ".js";
case UEBuildBinaryType.Executable:
return ".js";
case UEBuildBinaryType.StaticLibrary:
return ".bc";
case UEBuildBinaryType.Object:
return ".bc";
case UEBuildBinaryType.PrecompiledHeader:
return ".gch";
}
return base.GetBinaryExtension(InBinaryType);
}
}
/**
* Get the extension to use for debug info for the given binary type
*
* @param InBinaryType The binary type being built
*
* @return string The debug info extension (i.e. 'pdb')
*/
public override string GetDebugInfoExtension(UEBuildBinaryType InBinaryType)
{
if (GetActiveArchitecture() == "-win32")
{
switch (InBinaryType)
{
case UEBuildBinaryType.DynamicLinkLibrary:
return ".pdb";
case UEBuildBinaryType.Executable:
return ".pdb";
}
return "";
}
else
{
return "";
}
}
/**
* Gives the platform a chance to 'override' the configuration settings
* that are overridden on calls to RunUBT.
*
* @param InPlatform The UnrealTargetPlatform being built
* @param InConfiguration The UnrealTargetConfiguration being built
*
* @return bool true if debug info should be generated, false if not
*/
public override void ResetBuildConfiguration(UnrealTargetPlatform InPlatform, UnrealTargetConfiguration InConfiguration)
{
ValidateUEBuildConfiguration();
}
/**
* Validate the UEBuildConfiguration for this platform
* This is called BEFORE calling UEBuildConfiguration to allow setting
* various fields used in that function such as CompileLeanAndMean...
*/
public override void ValidateUEBuildConfiguration()
{
UEBuildConfiguration.bCompileLeanAndMeanUE = true;
UEBuildConfiguration.bCompileAPEX = false;
UEBuildConfiguration.bCompilePhysX = true;
UEBuildConfiguration.bRuntimePhysicsCooking = false;
UEBuildConfiguration.bCompileSimplygon = false;
UEBuildConfiguration.bCompileICU = true;
UEBuildConfiguration.bCompileForSize = true;
}
/**
* Whether this platform should build a monolithic binary
*/
public override bool ShouldCompileMonolithicBinary(UnrealTargetPlatform InPlatform)
{
// This platform currently always compiles monolithic
return true;
}
/**
* Whether PDB files should be used
*
* @param InPlatform The CPPTargetPlatform being built
* @param InConfiguration The CPPTargetConfiguration being built
* @param bInCreateDebugInfo true if debug info is getting create, false if not
*
* @return bool true if PDB files should be used, false if not
*/
public override bool ShouldUsePDBFiles(CPPTargetPlatform Platform, CPPTargetConfiguration Configuration, bool bCreateDebugInfo)
{
return bCreateDebugInfo;
}
/**
* Whether PCH files should be used
*
* @param InPlatform The CPPTargetPlatform being built
* @param InConfiguration The CPPTargetConfiguration being built
*
* @return bool true if PCH files should be used, false if not
*/
public override bool ShouldUsePCHFiles(CPPTargetPlatform Platform, CPPTargetConfiguration Configuration)
{
return false;
}
/**
* Whether the editor should be built for this platform or not
*
* @param InPlatform The UnrealTargetPlatform being built
* @param InConfiguration The UnrealTargetConfiguration being built
* @return bool true if the editor should be built, false if not
*/
public override bool ShouldNotBuildEditor(UnrealTargetPlatform InPlatform, UnrealTargetConfiguration InConfiguration)
{
return true;
}
public override bool BuildRequiresCookedData(UnrealTargetPlatform InPlatform, UnrealTargetConfiguration InConfiguration)
{
return true;
}
/**
* Modify the newly created module passed in for this platform.
* This is not required - but allows for hiding details of a
* particular platform.
*
* @param InModule The newly loaded module
* @param Target The target being build
*/
public override void ModifyNewlyLoadedModule(UEBuildModule InModule, TargetInfo Target)
{
if (Target.Platform == UnrealTargetPlatform.HTML5)
{
if (InModule.ToString() == "Core")
{
InModule.AddPublicIncludePath("Runtime/Core/Public/HTML5");
InModule.AddPublicDependencyModule("zlib");
}
else if (InModule.ToString() == "Engine")
{
InModule.AddPrivateDependencyModule("zlib");
InModule.AddPrivateDependencyModule("UElibPNG");
InModule.AddPublicDependencyModule("UEOgg");
InModule.AddPublicDependencyModule("Vorbis");
}
}
else if (Target.Platform == UnrealTargetPlatform.Win32 || Target.Platform == UnrealTargetPlatform.Win64 || Target.Platform == UnrealTargetPlatform.Mac )
{
// allow standalone tools to use targetplatform modules, without needing Engine
if ((!UEBuildConfiguration.bBuildRequiresCookedData
&& InModule.ToString() == "Engine"
&& UEBuildConfiguration.bBuildDeveloperTools)
|| UEBuildConfiguration.bForceBuildTargetPlatforms)
{
InModule.AddPlatformSpecificDynamicallyLoadedModule("HTML5TargetPlatform");
}
}
}
/**
* Setup the target environment for building
*
* @param InBuildTarget The target being built
*/
public override void SetUpEnvironment(UEBuildTarget InBuildTarget)
{
if (GetActiveArchitecture() == "-win32")
InBuildTarget.GlobalLinkEnvironment.Config.ExcludedLibraries.Add("LIBCMT");
InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("PLATFORM_HTML5=1");
if (InBuildTarget.GlobalCompileEnvironment.Config.Target.Architecture == "-win32")
{
InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("PLATFORM_HTML5_WIN32=1");
InBuildTarget.GlobalLinkEnvironment.Config.AdditionalLibraries.Add("delayimp.lib");
}
else
{
InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("PLATFORM_HTML5_BROWSER=1");
}
// @todo needed?
InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("UNICODE");
InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("_UNICODE");
InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("WITH_AUTOMATION_WORKER=0");
InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("REQUIRES_ALIGNED_INT_ACCESS");
InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("WITH_OGGVORBIS=1");
InBuildTarget.GlobalCompileEnvironment.Config.Definitions.Add("USE_SCENE_LOCK=0");
BuildConfiguration.bDeployAfterCompile = true;
}
/**
* Whether this platform should create debug information or not
*
* @param InPlatform The UnrealTargetPlatform being built
* @param InConfiguration The UnrealTargetConfiguration being built
*
* @return bool true if debug info should be generated, false if not
*/
public override bool ShouldCreateDebugInfo(UnrealTargetPlatform Platform, UnrealTargetConfiguration Configuration)
{
switch (Configuration)
{
case UnrealTargetConfiguration.Development:
case UnrealTargetConfiguration.Shipping:
case UnrealTargetConfiguration.Test:
return !BuildConfiguration.bOmitPCDebugInfoInDevelopment;
case UnrealTargetConfiguration.Debug:
default:
// We don't need debug info for Emscripten, and it causes a bunch of issues with linking
return true;
};
}
/**
* Setup the binaries for this specific platform.
*
* @param InBuildTarget The target being built
*/
public override void SetupBinaries(UEBuildTarget InBuildTarget)
{
// InBuildTarget.ExtraModuleNames.Add("ES2RHI");
}
}
}
| |
using Orleans.Persistence.AdoNet.Storage;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Serialization;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Configuration.Overrides;
namespace Orleans.Storage
{
/// <summary>
/// Logging codes used by <see cref="AdoNetGrainStorage"/>.
/// </summary>
/// <remarks> These are taken from <em>Orleans.Providers.ProviderErrorCode</em> and <em>Orleans.Providers.AzureProviderErrorCode</em>.</remarks>
internal enum RelationalStorageProviderCodes
{
//These is from Orleans.Providers.ProviderErrorCode and Orleans.Providers.AzureProviderErrorCode.
ProvidersBase = 200000,
RelationalProviderBase = ProvidersBase + 400,
RelationalProviderDeleteError = RelationalProviderBase + 8,
RelationalProviderInitProvider = RelationalProviderBase + 9,
RelationalProviderNoDeserializer = RelationalProviderBase + 10,
RelationalProviderNoStateFound = RelationalProviderBase + 11,
RelationalProviderClearing = RelationalProviderBase + 12,
RelationalProviderCleared = RelationalProviderBase + 13,
RelationalProviderReading = RelationalProviderBase + 14,
RelationalProviderRead = RelationalProviderBase + 15,
RelationalProviderReadError = RelationalProviderBase + 16,
RelationalProviderWriting = RelationalProviderBase + 17,
RelationalProviderWrote = RelationalProviderBase + 18,
RelationalProviderWriteError = RelationalProviderBase + 19
}
public static class AdoNetGrainStorageFactory
{
public static IGrainStorage Create(IServiceProvider services, string name)
{
var optionsMonitor = services.GetRequiredService<IOptionsMonitor<AdoNetGrainStorageOptions>>();
var clusterOptions = services.GetProviderClusterOptions(name);
return ActivatorUtilities.CreateInstance<AdoNetGrainStorage>(services, Options.Create(optionsMonitor.Get(name)), name, clusterOptions);
}
}
/// <summary>
/// A storage provider for writing grain state data to relational storage.
/// </summary>
/// <remarks>
/// <para>
/// Required configuration params: <c>DataConnectionString</c>
/// </para>
/// <para>
/// Optional configuration params:
/// <c>AdoInvariant</c> -- defaults to <c>System.Data.SqlClient</c>
/// <c>UseJsonFormat</c> -- defaults to <c>false</c>
/// <c>UseXmlFormat</c> -- defaults to <c>false</c>
/// <c>UseBinaryFormat</c> -- defaults to <c>true</c>
/// </para>
/// </remarks>
[DebuggerDisplay("Name = {Name}, ConnectionString = {Storage.ConnectionString}")]
public class AdoNetGrainStorage: IGrainStorage, ILifecycleParticipant<ISiloLifecycle>
{
private SerializationManager serializationManager;
/// <summary>
/// Tag for BinaryFormatSerializer
/// </summary>
public const string BinaryFormatSerializerTag = "BinaryFormatSerializer";
/// <summary>
/// Tag for JsonFormatSerializer
/// </summary>
public const string JsonFormatSerializerTag = "JsonFormatSerializer";
/// <summary>
/// Tag for XmlFormatSerializer
/// </summary>
public const string XmlFormatSerializerTag = "XmlFormatSerializer";
/// <summary>
/// The Service ID for which this relational provider is used.
/// </summary>
private readonly string serviceId;
private readonly ILogger logger;
/// <summary>
/// The storage used for back-end operations.
/// </summary>
private IRelationalStorage Storage { get; set; }
/// <summary>
/// These chars are delimiters when used to extract a class base type from a class
/// that is either <see cref="Type.AssemblyQualifiedName"/> or <see cref="Type.FullName"/>.
/// <see cref="ExtractBaseClass(string)"/>.
/// </summary>
private static char[] BaseClassExtractionSplitDelimeters { get; } = new[] { '[', ']' };
/// <summary>
/// The default query to initialize this structure from the Orleans database.
/// </summary>
public const string DefaultInitializationQuery = "SELECT QueryKey, QueryText FROM OrleansQuery WHERE QueryKey = 'WriteToStorageKey' OR QueryKey = 'ReadFromStorageKey' OR QueryKey = 'ClearStorageKey'";
/// <summary>
/// The queries currently used. When this is updated, the new queries will take effect immediately.
/// </summary>
public RelationalStorageProviderQueries CurrentOperationalQueries { get; set; }
/// <summary>
/// A strategy to pick a serializer or a deserializer for storage operations. This can be used to:
/// 1) Add a custom serializer or deserializer for use in storage provider operations.
/// 2) In combination with serializer or deserializer to update stored object version.
/// 3) Per-grain storage format selection
/// 4) Switch storage format first by reading using the save format and then writing in the new format.
/// </summary>
public IStorageSerializationPicker StorageSerializationPicker { get; set; }
/// <summary>
/// The hash generator used to hash natural keys, grain ID and grain type to a more narrow index.
/// </summary>
public IStorageHasherPicker HashPicker { get; set; } = new StorageHasherPicker(new[] { new OrleansDefaultHasher() });
private readonly AdoNetGrainStorageOptions options;
private readonly IProviderRuntime providerRuntime;
private readonly string name;
public AdoNetGrainStorage(
ILogger<AdoNetGrainStorage> logger,
IProviderRuntime providerRuntime,
IOptions<AdoNetGrainStorageOptions> options,
IOptions<ClusterOptions> clusterOptions,
string name)
{
this.options = options.Value;
this.providerRuntime = providerRuntime;
this.name = name;
this.logger = logger;
this.serviceId = clusterOptions.Value.ServiceId;
}
public void Participate(ISiloLifecycle lifecycle)
{
lifecycle.Subscribe(OptionFormattingUtilities.Name<AdoNetGrainStorage>(this.name), this.options.InitStage, Init, Close);
}
/// <summary>Clear state data function for this storage provider.</summary>
/// <see cref="IGrainStorage.ClearStateAsync(string, GrainReference, IGrainState)"/>.
public async Task ClearStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
//It assumed these parameters are always valid. If not, an exception will be thrown,
//even if not as clear as when using explicitly checked parameters.
var grainId = GrainIdAndExtensionAsString(grainReference);
var baseGrainType = ExtractBaseClass(grainType);
if(logger.IsEnabled(LogLevel.Trace))
{
logger.Trace((int)RelationalStorageProviderCodes.RelationalProviderClearing, LogString("Clearing grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString()));
}
string storageVersion = null;
try
{
var grainIdHash = HashPicker.PickHasher(serviceId, this.name, baseGrainType, grainReference, grainState).Hash(grainId.GetHashBytes());
var grainTypeHash = HashPicker.PickHasher(serviceId, this.name, baseGrainType, grainReference, grainState).Hash(Encoding.UTF8.GetBytes(baseGrainType));
var clearRecord = (await Storage.ReadAsync(CurrentOperationalQueries.ClearState, command =>
{
command.AddParameter("GrainIdHash", grainIdHash);
command.AddParameter("GrainIdN0", grainId.N0Key);
command.AddParameter("GrainIdN1", grainId.N1Key);
command.AddParameter("GrainTypeHash", grainTypeHash);
command.AddParameter("GrainTypeString", baseGrainType);
command.AddParameter("GrainIdExtensionString", grainId.StringKey);
command.AddParameter("ServiceId", serviceId);
command.AddParameter("GrainStateVersion", !string.IsNullOrWhiteSpace(grainState.ETag) ? int.Parse(grainState.ETag, CultureInfo.InvariantCulture) : default(int?));
}, (selector, resultSetCount, token) => Task.FromResult(selector.GetValue(0).ToString()), CancellationToken.None).ConfigureAwait(false));
storageVersion = clearRecord.SingleOrDefault();
}
catch(Exception ex)
{
logger.Error((int)RelationalStorageProviderCodes.RelationalProviderDeleteError, LogString("Error clearing grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString(), ex.Message), ex);
throw;
}
const string OperationString = "ClearState";
var inconsistentStateException = CheckVersionInconsistency(OperationString, serviceId, this.name, storageVersion, grainState.ETag, baseGrainType, grainId.ToString());
if(inconsistentStateException != null)
{
throw inconsistentStateException;
}
//No errors found, the version of the state held by the grain can be updated and also the state.
grainState.ETag = storageVersion;
if(logger.IsEnabled(LogLevel.Trace))
{
logger.Trace((int)RelationalStorageProviderCodes.RelationalProviderCleared, LogString("Cleared grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString()));
}
}
/// <summary> Read state data function for this storage provider.</summary>
/// <see cref="IGrainStorage.ReadStateAsync(string, GrainReference, IGrainState)"/>.
public async Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
//It assumed these parameters are always valid. If not, an exception will be thrown, even if not as clear
//as with explicitly checked parameters.
var grainId = GrainIdAndExtensionAsString(grainReference);
var baseGrainType = ExtractBaseClass(grainType);
if (logger.IsEnabled(LogLevel.Trace))
{
logger.Trace((int)RelationalStorageProviderCodes.RelationalProviderReading, LogString("Reading grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString()));
}
try
{
SerializationChoice choice =StorageSerializationPicker.PickDeserializer(serviceId, this.name, baseGrainType, grainReference, grainState, null);
if(choice.Deserializer == null)
{
var errorString = LogString("No deserializer found", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString());
logger.Error((int)RelationalStorageProviderCodes.RelationalProviderNoDeserializer, errorString);
throw new InvalidOperationException(errorString);
}
var commandBehavior = choice.PreferStreaming ? CommandBehavior.SequentialAccess : CommandBehavior.Default;
var grainIdHash = HashPicker.PickHasher(serviceId, this.name, baseGrainType, grainReference, grainState).Hash(grainId.GetHashBytes());
var grainTypeHash = HashPicker.PickHasher(serviceId, this.name, baseGrainType, grainReference, grainState).Hash(Encoding.UTF8.GetBytes(baseGrainType));
var readRecords = (await Storage.ReadAsync(CurrentOperationalQueries.ReadFromStorage, (command =>
{
command.AddParameter("GrainIdHash", grainIdHash);
command.AddParameter("GrainIdN0", grainId.N0Key);
command.AddParameter("GrainIdN1", grainId.N1Key);
command.AddParameter("GrainTypeHash", grainTypeHash);
command.AddParameter("GrainTypeString", baseGrainType);
command.AddParameter("GrainIdExtensionString", grainId.StringKey);
command.AddParameter("ServiceId", serviceId);
}), async (selector, resultSetCount, token) =>
{
object storageState = null;
int? version;
if(choice.PreferStreaming)
{
//When streaming via ADO.NET, using CommandBehavior.SequentialAccess, the order of
//the columns on how they are read needs to be exactly this.
const int binaryColumnPositionInSelect = 0;
const int xmlColumnPositionInSelect = 1;
const int jsonColumnPositionInSelect = 2;
var streamSelector = (DbDataReader)selector;
if(!(await streamSelector.IsDBNullAsync(binaryColumnPositionInSelect)))
{
using(var downloadStream = streamSelector.GetStream(binaryColumnPositionInSelect, Storage))
{
storageState = choice.Deserializer.Deserialize(downloadStream, grainState.Type);
}
}
if(!(await streamSelector.IsDBNullAsync(xmlColumnPositionInSelect)))
{
using(var downloadStream = streamSelector.GetTextReader(xmlColumnPositionInSelect))
{
storageState = choice.Deserializer.Deserialize(downloadStream, grainState.Type);
}
}
if(!(await streamSelector.IsDBNullAsync(jsonColumnPositionInSelect)))
{
using(var downloadStream = streamSelector.GetTextReader(jsonColumnPositionInSelect))
{
storageState = choice.Deserializer.Deserialize(downloadStream, grainState.Type);
}
}
version = await streamSelector.GetValueAsync<int?>("Version");
}
else
{
//All but one of these should be null. All will be read and an appropriate deserializer picked.
//NOTE: When streaming will be implemented, it is worthwhile to optimize this so that the defined
//serializer will be picked and then streaming tried according to its tag.
object payload;
payload = selector.GetValueOrDefault<byte[]>("PayloadBinary");
if(payload == null)
{
payload = selector.GetValueOrDefault<string>("PayloadXml");
}
if(payload == null)
{
payload = selector.GetValueOrDefault<string>("PayloadJson");
}
if(payload != null)
{
storageState = choice.Deserializer.Deserialize(payload, grainState.Type);
}
version = selector.GetNullableInt32("Version");
}
return Tuple.Create(storageState, version?.ToString(CultureInfo.InvariantCulture));
}, CancellationToken.None, commandBehavior).ConfigureAwait(false)).SingleOrDefault();
object state = readRecords != null ? readRecords.Item1 : null;
string etag = readRecords != null ? readRecords.Item2 : null;
if(state == null)
{
logger.Info((int)RelationalStorageProviderCodes.RelationalProviderNoStateFound, LogString("Null grain state read (default will be instantiated)", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString()));
state = Activator.CreateInstance(grainState.Type);
}
grainState.State = state;
grainState.ETag = etag;
if (logger.IsEnabled(LogLevel.Trace))
{
logger.Trace((int)RelationalStorageProviderCodes.RelationalProviderRead, LogString("Read grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString()));
}
}
catch(Exception ex)
{
logger.Error((int)RelationalStorageProviderCodes.RelationalProviderReadError, LogString("Error reading grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString(), ex.Message), ex);
throw;
}
}
/// <summary> Write state data function for this storage provider.</summary>
/// <see cref="IGrainStorage.WriteStateAsync"/>
public async Task WriteStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
//It assumed these parameters are always valid. If not, an exception will be thrown, even if not as clear
//as with explicitly checked parameters.
var data = grainState.State;
var grainId = GrainIdAndExtensionAsString(grainReference);
var baseGrainType = ExtractBaseClass(grainType);
if (logger.IsEnabled(LogLevel.Trace))
{
logger.Trace((int)RelationalStorageProviderCodes.RelationalProviderWriting, LogString("Writing grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString()));
}
string storageVersion = null;
try
{
var grainIdHash = HashPicker.PickHasher(serviceId, this.name, baseGrainType, grainReference, grainState).Hash(grainId.GetHashBytes());
var grainTypeHash = HashPicker.PickHasher(serviceId, this.name, baseGrainType, grainReference, grainState).Hash(Encoding.UTF8.GetBytes(baseGrainType));
var writeRecord = await Storage.ReadAsync(CurrentOperationalQueries.WriteToStorage, command =>
{
command.AddParameter("GrainIdHash", grainIdHash);
command.AddParameter("GrainIdN0", grainId.N0Key);
command.AddParameter("GrainIdN1", grainId.N1Key);
command.AddParameter("GrainTypeHash", grainTypeHash);
command.AddParameter("GrainTypeString", baseGrainType);
command.AddParameter("GrainIdExtensionString", grainId.StringKey);
command.AddParameter("ServiceId", serviceId);
command.AddParameter("GrainStateVersion", !string.IsNullOrWhiteSpace(grainState.ETag) ? int.Parse(grainState.ETag, CultureInfo.InvariantCulture) : default(int?));
SerializationChoice serializer = StorageSerializationPicker.PickSerializer(serviceId, this.name, baseGrainType, grainReference, grainState);
command.AddParameter("PayloadBinary", (byte[])(serializer.Serializer.Tag == BinaryFormatSerializerTag ? serializer.Serializer.Serialize(data) : null));
command.AddParameter("PayloadJson", (string)(serializer.Serializer.Tag == JsonFormatSerializerTag ? serializer.Serializer.Serialize(data) : null));
command.AddParameter("PayloadXml", (string)(serializer.Serializer.Tag == XmlFormatSerializerTag ? serializer.Serializer.Serialize(data) : null));
}, (selector, resultSetCount, token) =>
{ return Task.FromResult(selector.GetNullableInt32("NewGrainStateVersion").ToString()); }, CancellationToken.None).ConfigureAwait(false);
storageVersion = writeRecord.SingleOrDefault();
}
catch(Exception ex)
{
logger.Error((int)RelationalStorageProviderCodes.RelationalProviderWriteError, LogString("Error writing grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString(), ex.Message), ex);
throw;
}
const string OperationString = "WriteState";
var inconsistentStateException = CheckVersionInconsistency(OperationString, serviceId, this.name, storageVersion, grainState.ETag, baseGrainType, grainId.ToString());
if(inconsistentStateException != null)
{
throw inconsistentStateException;
}
//No errors found, the version of the state held by the grain can be updated.
grainState.ETag = storageVersion;
if (logger.IsEnabled(LogLevel.Trace))
{
logger.Trace((int)RelationalStorageProviderCodes.RelationalProviderWrote, LogString("Wrote grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString()));
}
}
/// <summary> Initialization function for this storage provider. </summary>
private async Task Init(CancellationToken cancellationToken)
{
this.serializationManager = providerRuntime.ServiceProvider.GetRequiredService<SerializationManager>();
//NOTE: StorageSerializationPicker should be defined outside and given as a parameter in constructor or via Init in IProviderConfiguration perhaps.
//Currently this limits one's options to much to the current situation of providing only one serializer for serialization and deserialization
//with no regard to state update or serializer changes. Maybe have this serialized as a JSON in props and read via a key?
StorageSerializationPicker = new DefaultRelationalStoragePicker(this.ConfigureDeserializers(options, providerRuntime), this.ConfigureSerializers(options, providerRuntime));
Storage = RelationalStorage.CreateInstance(options.Invariant, options.ConnectionString);
var queries = await Storage.ReadAsync(DefaultInitializationQuery, command => { }, (selector, resultSetCount, token) =>
{
return Task.FromResult(Tuple.Create(selector.GetValue<string>("QueryKey"), selector.GetValue<string>("QueryText")));
}).ConfigureAwait(false);
CurrentOperationalQueries = new RelationalStorageProviderQueries(
queries.Single(i => i.Item1 == "WriteToStorageKey").Item2,
queries.Single(i => i.Item1 == "ReadFromStorageKey").Item2,
queries.Single(i => i.Item1 == "ClearStorageKey").Item2);
logger.Info((int)RelationalStorageProviderCodes.RelationalProviderInitProvider, $"Initialized storage provider: ServiceId={serviceId} ProviderName={this.name} Invariant={Storage.InvariantName} ConnectionString={Storage.ConnectionString}.");
}
/// <summary>
/// Close this provider
/// </summary>
private Task Close(CancellationToken token)
{
return Task.CompletedTask;
}
/// <summary>
/// Checks for version inconsistency as defined in the database scripts.
/// </summary>
/// <param name="serviceId">Service Id.</param>
/// <param name="providerName">The name of this storage provider.</param>
/// <param name="operation">The operation attempted.</param>
/// <param name="storageVersion">The version from storage.</param>
/// <param name="grainVersion">The grain version.</param>
/// <param name="normalizedGrainType">Grain type without generics information.</param>
/// <param name="grainId">The grain ID.</param>
/// <returns>An exception for throwing or <em>null</em> if no violation was detected.</returns>
/// <remarks>This means that the version was not updated in the database or the version storage version was something else than null
/// when the grain version was null, meaning effectively a double activation and save.</remarks>
private static InconsistentStateException CheckVersionInconsistency(string operation, string serviceId, string providerName, string storageVersion, string grainVersion, string normalizedGrainType, string grainId)
{
//If these are the same, it means no row was inserted or updated in the storage.
//Effectively it means the UPDATE or INSERT conditions failed due to ETag violation.
//Also if grainState.ETag storageVersion is null and storage comes back as null,
//it means two grains were activated an the other one succeeded in writing its state.
//
//NOTE: the storage could return also the new and old ETag (Version), but currently it doesn't.
if(storageVersion == grainVersion || storageVersion == string.Empty)
{
//TODO: Note that this error message should be canonical across back-ends.
return new InconsistentStateException($"Version conflict ({operation}): ServiceId={serviceId} ProviderName={providerName} GrainType={normalizedGrainType} GrainId={grainId} ETag={grainVersion}.");
}
return null;
}
/// <summary>
/// Writes a consistent log message from the given parameters.
/// </summary>
/// <param name="operationProlog">A free form prolog information to log.</param>
/// <param name="serviceId">Service Id.</param>
/// <param name="providerName">The name of this storage provider.</param>
/// <param name="version">The grain version.</param>
/// <param name="normalizedGrainType">Grain type without generics information.</param>
/// <param name="grainId">The grain ID.</param>
/// <param name="exceptionMessage">An optional exception message information to log.</param>
/// <returns>A log string to be printed.</returns>
private string LogString(string operationProlog, string serviceId, string providerName, string version, string normalizedGrainType, string grainId, string exceptionMessage = null)
{
const string Exception = " Exception=";
return $"{operationProlog}: ServiceId={serviceId} ProviderName={providerName} GrainType={normalizedGrainType} GrainId={grainId} ETag={version}{(exceptionMessage != null ? Exception + exceptionMessage : string.Empty)}.";
}
/// <summary>
/// Extracts a grain ID as a string and appends the key extension with '#' infix is present.
/// </summary>
/// <param name="grainReference">The reference from which to extract the ID.</param>
/// <returns>The grain ID as a string.</returns>
/// <remarks>This likely should exist in Orleans core in more optimized form.</remarks>
private static AdoGrainKey GrainIdAndExtensionAsString(GrainReference grainReference)
{
//Kudos for https://github.com/tsibelman for the algorithm. See more at https://github.com/dotnet/orleans/issues/1905.
string keyExtension;
AdoGrainKey key;
if(grainReference.IsPrimaryKeyBasedOnLong())
{
key = new AdoGrainKey(grainReference.GetPrimaryKeyLong(out keyExtension), keyExtension);
}
else
{
key = new AdoGrainKey(grainReference.GetPrimaryKey(out keyExtension), keyExtension);
}
return key;
}
/// <summary>
/// Extracts a base class from a string that is either <see cref="Type.AssemblyQualifiedName"/> or
/// <see cref="Type.FullName"/> or returns the one given as a parameter if no type is given.
/// </summary>
/// <param name="typeName">The base class name to give.</param>
/// <returns>The extracted base class or the one given as a parameter if it didn't have a generic part.</returns>
private static string ExtractBaseClass(string typeName)
{
var genericPosition = typeName.IndexOf("`", StringComparison.OrdinalIgnoreCase);
if (genericPosition != -1)
{
//The following relies the generic argument list to be in form as described
//at https://msdn.microsoft.com/en-us/library/w3f99sx1.aspx.
var split = typeName.Split(BaseClassExtractionSplitDelimeters, StringSplitOptions.RemoveEmptyEntries);
var stripped = new Queue<string>(split.Where(i => i.Length > 1 && i[0] != ',').Select(WithoutAssemblyVersion));
return ReformatClassName(stripped);
}
return typeName;
string WithoutAssemblyVersion(string input)
{
var asmNameIndex = input.IndexOf(',');
if (asmNameIndex >= 0)
{
var asmVersionIndex = input.IndexOf(',', asmNameIndex + 1);
if (asmVersionIndex >= 0) return input.Substring(0, asmVersionIndex);
return input.Substring(0, asmNameIndex);
}
return input;
}
string ReformatClassName(Queue<string> segments)
{
var simpleTypeName = segments.Dequeue();
var arity = GetGenericArity(simpleTypeName);
if (arity <= 0) return simpleTypeName;
var args = new List<string>(arity);
for (var i = 0; i < arity; i++)
{
args.Add(ReformatClassName(segments));
}
return $"{simpleTypeName}[{string.Join(",", args.Select(arg => $"[{arg}]"))}]";
}
int GetGenericArity(string input)
{
var arityIndex = input.IndexOf("`", StringComparison.OrdinalIgnoreCase);
if (arityIndex != -1)
{
return int.Parse(input.Substring(arityIndex + 1));
}
return 0;
}
}
private ICollection<IStorageDeserializer> ConfigureDeserializers(AdoNetGrainStorageOptions options, IProviderRuntime providerRuntime)
{
var deserializers = new List<IStorageDeserializer>();
if(options.UseJsonFormat)
{
var typeResolver = providerRuntime.ServiceProvider.GetRequiredService<ITypeResolver>();
var jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(typeResolver, providerRuntime.GrainFactory), options.UseFullAssemblyNames, options.IndentJson, options.TypeNameHandling);
deserializers.Add(new OrleansStorageDefaultJsonDeserializer(jsonSettings, JsonFormatSerializerTag));
}
if(options.UseXmlFormat)
{
deserializers.Add(new OrleansStorageDefaultXmlDeserializer(XmlFormatSerializerTag));
}
//if none are set true, configure binary format serializer by default
if(!options.UseXmlFormat && !options.UseJsonFormat)
{
deserializers.Add(new OrleansStorageDefaultBinaryDeserializer(this.serializationManager, BinaryFormatSerializerTag));
}
return deserializers;
}
private ICollection<IStorageSerializer> ConfigureSerializers(AdoNetGrainStorageOptions options, IProviderRuntime providerRuntime)
{
var serializers = new List<IStorageSerializer>();
if(options.UseJsonFormat)
{
var typeResolver = providerRuntime.ServiceProvider.GetRequiredService<ITypeResolver>();
var jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(typeResolver, providerRuntime.GrainFactory),
options.UseFullAssemblyNames, options.IndentJson, options.TypeNameHandling);
serializers.Add(new OrleansStorageDefaultJsonSerializer(jsonSettings, JsonFormatSerializerTag));
}
if(options.UseXmlFormat)
{
serializers.Add(new OrleansStorageDefaultXmlSerializer(XmlFormatSerializerTag));
}
//if none are set true, configure binary format serializer by default
if (!options.UseXmlFormat && !options.UseJsonFormat)
{
serializers.Add(new OrleansStorageDefaultBinarySerializer(this.serializationManager, BinaryFormatSerializerTag));
}
return serializers;
}
}
}
| |
/********************************************************************++
* Copyright (c) Microsoft Corporation. All rights reserved.
* --********************************************************************/
using System.Threading;
using System.Collections.Generic;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting
{
/// <summary>
/// This class implements a Finite State Machine (FSM) to control the remote connection on the server side.
/// There is a similar but not identical FSM on the client side for this connection.
///
/// The FSM's states and events are defined to be the same for both the client FSM and the server FSM.
/// This design allows the client and server FSM's to
/// be as similar as possible, so that the complexity of maintaining them is minimized.
///
/// This FSM only controls the remote connection state. States related to runspace and pipeline are managed by runspace
/// pipeline themselves.
///
/// This FSM defines an event handling matrix, which is filled by the event handlers.
/// The state transitions can only be performed by these event handlers, which are private
/// to this class. The event handling is done by a single thread, which makes this
/// implementation solid and thread safe.
///
/// This implementation of the FSM does not allow the remote session to be reused for a connection
/// after it is been closed. This design decision is made to simplify the implementation.
/// However, the design can be easily modified to allow the reuse of the remote session
/// to reconnect after the connection is closed.
/// </summary>
internal class ServerRemoteSessionDSHandlerStateMachine
{
[TraceSourceAttribute("ServerRemoteSessionDSHandlerStateMachine", "ServerRemoteSessionDSHandlerStateMachine")]
private static PSTraceSource s_trace = PSTraceSource.GetTracer("ServerRemoteSessionDSHandlerStateMachine", "ServerRemoteSessionDSHandlerStateMachine");
private ServerRemoteSession _session;
private object _syncObject;
private Queue<RemoteSessionStateMachineEventArgs> _processPendingEventsQueue
= new Queue<RemoteSessionStateMachineEventArgs>();
// whether some thread is actively processing events
// in a loop. If this is set then other threads
// should simply add to the queue and not attempt
// at processing the events in the queue. This will
// guarantee that events will always be serialized
// and processed
private bool _eventsInProcess = false;
private EventHandler<RemoteSessionStateMachineEventArgs>[,] _stateMachineHandle;
private RemoteSessionState _state;
/// <summary>
/// timer used for key exchange
/// </summary>
private Timer _keyExchangeTimer;
#region Constructors
/// <summary>
/// This constructor instantiates a FSM object for the server side to control the remote connection.
/// It initializes the event handling matrix with event handlers.
/// It sets the initial state of the FSM to be Idle.
/// </summary>
/// <param name="session">
/// This is the remote session object.
/// </param>
/// <exception cref="ArgumentNullException">
/// If the parameter is null.
/// </exception>
internal ServerRemoteSessionDSHandlerStateMachine(ServerRemoteSession session)
{
if (session == null)
{
throw PSTraceSource.NewArgumentNullException("session");
}
_session = session;
_syncObject = new object();
_stateMachineHandle = new EventHandler<RemoteSessionStateMachineEventArgs>[(int)RemoteSessionState.MaxState, (int)RemoteSessionEvent.MaxEvent];
for (int i = 0; i < _stateMachineHandle.GetLength(0); i++)
{
_stateMachineHandle[i, (int)RemoteSessionEvent.FatalError] += DoFatalError;
_stateMachineHandle[i, (int)RemoteSessionEvent.Close] += DoClose;
_stateMachineHandle[i, (int)RemoteSessionEvent.CloseFailed] += DoCloseFailed;
_stateMachineHandle[i, (int)RemoteSessionEvent.CloseCompleted] += DoCloseCompleted;
_stateMachineHandle[i, (int)RemoteSessionEvent.NegotiationTimeout] += DoNegotiationTimeout;
_stateMachineHandle[i, (int)RemoteSessionEvent.SendFailed] += DoSendFailed;
_stateMachineHandle[i, (int)RemoteSessionEvent.ReceiveFailed] += DoReceiveFailed;
_stateMachineHandle[i, (int)RemoteSessionEvent.ConnectSession] += DoConnect;
}
_stateMachineHandle[(int)RemoteSessionState.Idle, (int)RemoteSessionEvent.CreateSession] += DoCreateSession;
_stateMachineHandle[(int)RemoteSessionState.NegotiationPending, (int)RemoteSessionEvent.NegotiationReceived] += DoNegotiationReceived;
_stateMachineHandle[(int)RemoteSessionState.NegotiationReceived, (int)RemoteSessionEvent.NegotiationSending] += DoNegotiationSending;
_stateMachineHandle[(int)RemoteSessionState.NegotiationSending, (int)RemoteSessionEvent.NegotiationSendCompleted] += DoNegotiationCompleted;
_stateMachineHandle[(int)RemoteSessionState.NegotiationSent, (int)RemoteSessionEvent.NegotiationCompleted] += DoEstablished;
_stateMachineHandle[(int)RemoteSessionState.NegotiationSent, (int)RemoteSessionEvent.NegotiationPending] += DoNegotiationPending;
_stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.MessageReceived] += DoMessageReceived;
_stateMachineHandle[(int)RemoteSessionState.NegotiationReceived, (int)RemoteSessionEvent.NegotiationFailed] += DoNegotiationFailed;
_stateMachineHandle[(int)RemoteSessionState.Connecting, (int)RemoteSessionEvent.ConnectFailed] += DoConnectFailed;
_stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeyReceived] += DoKeyExchange; //
_stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeyRequested] += DoKeyExchange; //
_stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeyReceiveFailed] += DoKeyExchange; //
_stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.KeyReceived] += DoKeyExchange; //
_stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.KeySent] += DoKeyExchange; //
_stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.KeyReceiveFailed] += DoKeyExchange; //
_stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyReceived, (int)RemoteSessionEvent.KeySendFailed] += DoKeyExchange;
_stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyReceived, (int)RemoteSessionEvent.KeySent] += DoKeyExchange;
//with connect, a new client can negotiate a key change to a server that has already negotiated key exchange with a previous client
_stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyExchanged, (int)RemoteSessionEvent.KeyReceived] += DoKeyExchange; //
_stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyExchanged, (int)RemoteSessionEvent.KeyRequested] += DoKeyExchange; //
_stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyExchanged, (int)RemoteSessionEvent.KeyReceiveFailed] += DoKeyExchange; //
for (int i = 0; i < _stateMachineHandle.GetLength(0); i++)
{
for (int j = 0; j < _stateMachineHandle.GetLength(1); j++)
{
if (_stateMachineHandle[i, j] == null)
{
_stateMachineHandle[i, j] += DoClose;
}
}
}
// Initially, set state to Idle
SetState(RemoteSessionState.Idle, null);
}
#endregion Constructors
/// <summary>
/// This is a readonly property available to all other classes. It gives the FSM state.
/// Other classes can query for this state. Only the FSM itself can change the state.
/// </summary>
internal RemoteSessionState State
{
get
{
return _state;
}
}
/// <summary>
/// Helper method used by dependents to figure out if the RaiseEvent
/// method can be short-circuited. This will be useful in cases where
/// the dependent code wants to take action immediately instead of
/// going through state machine.
/// </summary>
/// <param name="arg"></param>
internal bool CanByPassRaiseEvent(RemoteSessionStateMachineEventArgs arg)
{
if (arg.StateEvent == RemoteSessionEvent.MessageReceived)
{
if (_state == RemoteSessionState.Established ||
_state == RemoteSessionState.EstablishedAndKeySent || //server session will never be in this state.. TODO- remove this
_state == RemoteSessionState.EstablishedAndKeyReceived ||
_state == RemoteSessionState.EstablishedAndKeyExchanged)
{
return true;
}
}
return false;
}
/// <summary>
/// This method is used by all classes to raise a FSM event.
/// The method will queue the event. The event queue will be handled in
/// a thread safe manner by a single dedicated thread.
/// </summary>
/// <param name="fsmEventArg">
/// This parameter contains the event to be raised.
/// </param>
/// <exception cref="ArgumentNullException">
/// If the parameter is null.
/// </exception>
internal void RaiseEvent(RemoteSessionStateMachineEventArgs fsmEventArg)
{
// make sure only one thread is processing events.
lock (_syncObject)
{
s_trace.WriteLine("Event received : {0}", fsmEventArg.StateEvent);
_processPendingEventsQueue.Enqueue(fsmEventArg);
if (_eventsInProcess)
{
return;
}
_eventsInProcess = true;
}
ProcessEvents();
// currently server state machine doesn't raise events
// this will allow server state machine to raise events.
//RaiseStateMachineEvents();
}
/// <summary>
/// processes events in the queue. If there are no
/// more events to process, then sets eventsInProcess
/// variable to false. This will ensure that another
/// thread which raises an event can then take control
/// of processing the events
/// </summary>
private void ProcessEvents()
{
RemoteSessionStateMachineEventArgs eventArgs = null;
do
{
lock (_syncObject)
{
if (_processPendingEventsQueue.Count == 0)
{
_eventsInProcess = false;
break;
}
eventArgs = _processPendingEventsQueue.Dequeue();
}
RaiseEventPrivate(eventArgs);
} while (_eventsInProcess);
}
/// <summary>
/// This is the private version of raising a FSM event.
/// It can only be called by the dedicated thread that processes the event queue.
/// It calls the event handler
/// in the right position of the event handling matrix.
/// </summary>
/// <param name="fsmEventArg">
/// The parameter contains the actual FSM event.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If the parameter is null.
/// </exception>
private void RaiseEventPrivate(RemoteSessionStateMachineEventArgs fsmEventArg)
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException("fsmEventArg");
}
EventHandler<RemoteSessionStateMachineEventArgs> handler = _stateMachineHandle[(int)_state, (int)fsmEventArg.StateEvent];
if (handler != null)
{
s_trace.WriteLine("Before calling state machine event handler: state = {0}, event = {1}", _state, fsmEventArg.StateEvent);
handler(this, fsmEventArg);
s_trace.WriteLine("After calling state machine event handler: state = {0}, event = {1}", _state, fsmEventArg.StateEvent);
}
}
#region Event Handlers
/// <summary>
/// This is the handler for Start event of the FSM. This is the beginning of everything
/// else. From this moment on, the FSM will proceeds step by step to eventually reach
/// Established state or Closed state.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoCreateSession(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException("fsmEventArg");
}
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.CreateSession, "StateEvent must be CreateSession");
Dbg.Assert(_state == RemoteSessionState.Idle, "DoCreateSession cannot only be called in Idle state");
DoNegotiationPending(sender, fsmEventArg);
}
}
/// <summary>
/// This is the handler for NegotiationPending event.
/// NegotiationPending state can be in reached in the following cases
/// 1. From Idle to NegotiationPending (during startup)
/// 2. From Negotiation(Response)Sent to NegotiationPending.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoNegotiationPending(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException("fsmEventArg");
}
Dbg.Assert((_state == RemoteSessionState.Idle) || (_state == RemoteSessionState.NegotiationSent),
"DoNegotiationPending can only occur when the state is Idle or NegotiationSent.");
SetState(RemoteSessionState.NegotiationPending, null);
}
}
/// <summary>
/// This is the handler for the NegotiationReceived event.
/// It sets the new state to be NegotiationReceived.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If the parameter <paramref name="fsmEventArg"/> is not NegotiationReceived event or it does not hold the
/// client negotiation packet.
/// </exception>
private void DoNegotiationReceived(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException("fsmEventArg");
}
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationReceived, "StateEvent must be NegotiationReceived");
Dbg.Assert(fsmEventArg.RemoteSessionCapability != null, "RemoteSessioncapability must be non-null");
Dbg.Assert(_state == RemoteSessionState.NegotiationPending, "state must be in NegotiationPending state");
if (fsmEventArg.StateEvent != RemoteSessionEvent.NegotiationReceived)
{
throw PSTraceSource.NewArgumentException("fsmEventArg");
}
if (fsmEventArg.RemoteSessionCapability == null)
{
throw PSTraceSource.NewArgumentException("fsmEventArg");
}
SetState(RemoteSessionState.NegotiationReceived, null);
}
}
/// <summary>
/// This is the handler for NegotiationSending event.
/// It sets the new state to be NegotiationSending, and sends the server side
/// negotiation packet by queuing it on the output queue.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoNegotiationSending(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException("fsmEventArg");
}
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationSending, "Event must be NegotiationSending");
Dbg.Assert(_state == RemoteSessionState.NegotiationReceived, "State must be NegotiationReceived");
SetState(RemoteSessionState.NegotiationSending, null);
_session.SessionDataStructureHandler.SendNegotiationAsync();
}
/// <summary>
/// This is the handler for NegotiationSendCompleted event.
/// It sets the new state to be NegotiationSent.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoNegotiationCompleted(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException("fsmEventArg");
}
Dbg.Assert(_state == RemoteSessionState.NegotiationSending, "State must be NegotiationSending");
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationSendCompleted, "StateEvent must be NegotiationSendCompleted");
SetState(RemoteSessionState.NegotiationSent, null);
}
}
/// <summary>
/// This is the handler for the NegotiationCompleted event.
/// It sets the new state to be Established. It turns off the negotiation timeout timer.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoEstablished(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException("fsmEventArg");
}
Dbg.Assert(_state == RemoteSessionState.NegotiationSent, "State must be NegotiationReceived");
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationCompleted, "StateEvent must be NegotiationCompleted");
if (fsmEventArg.StateEvent != RemoteSessionEvent.NegotiationCompleted)
{
throw PSTraceSource.NewArgumentException("fsmEventArg");
}
if (_state != RemoteSessionState.NegotiationSent)
{
throw PSTraceSource.NewInvalidOperationException();
}
SetState(RemoteSessionState.Established, null);
}
}
/// <summary>
/// This is the handler for MessageReceived event. It dispatches the data to various components
/// that uses the data.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If the parameter <paramref name="fsmEventArg"/> does not contain remote data.
/// </exception>
internal void DoMessageReceived(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException("fsmEventArg");
}
if (fsmEventArg.RemoteData == null)
{
throw PSTraceSource.NewArgumentException("fsmEventArg");
}
Dbg.Assert(_state == RemoteSessionState.Established ||
_state == RemoteSessionState.EstablishedAndKeyExchanged ||
_state == RemoteSessionState.EstablishedAndKeyReceived ||
_state == RemoteSessionState.EstablishedAndKeySent, //server session will never be in this state.. TODO- remove this
"State must be Established or EstablishedAndKeySent or EstablishedAndKeyReceived or EstablishedAndKeyExchanged");
RemotingTargetInterface targetInterface = fsmEventArg.RemoteData.TargetInterface;
RemotingDataType dataType = fsmEventArg.RemoteData.DataType;
Guid clientRunspacePoolId;
ServerRunspacePoolDriver runspacePoolDriver;
//string errorMessage = null;
RemoteDataEventArgs remoteDataForSessionArg = null;
switch (targetInterface)
{
case RemotingTargetInterface.Session:
{
switch (dataType)
{
// GETBACK
case RemotingDataType.CreateRunspacePool:
remoteDataForSessionArg = new RemoteDataEventArgs(fsmEventArg.RemoteData);
_session.SessionDataStructureHandler.RaiseDataReceivedEvent(remoteDataForSessionArg);
break;
default:
Dbg.Assert(false, "Should never reach here");
break;
}
}
break;
case RemotingTargetInterface.RunspacePool:
// GETBACK
clientRunspacePoolId = fsmEventArg.RemoteData.RunspacePoolId;
runspacePoolDriver = _session.GetRunspacePoolDriver(clientRunspacePoolId);
if (runspacePoolDriver != null)
{
runspacePoolDriver.DataStructureHandler.ProcessReceivedData(fsmEventArg.RemoteData);
}
else
{
s_trace.WriteLine(@"Server received data for Runspace (id: {0}),
but the Runspace cannot be found", clientRunspacePoolId);
PSRemotingDataStructureException reasonOfFailure = new
PSRemotingDataStructureException(RemotingErrorIdStrings.RunspaceCannotBeFound,
clientRunspacePoolId);
RemoteSessionStateMachineEventArgs runspaceNotFoundArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.FatalError, reasonOfFailure);
RaiseEvent(runspaceNotFoundArg);
}
break;
case RemotingTargetInterface.PowerShell:
clientRunspacePoolId = fsmEventArg.RemoteData.RunspacePoolId;
runspacePoolDriver = _session.GetRunspacePoolDriver(clientRunspacePoolId);
runspacePoolDriver.DataStructureHandler.DispatchMessageToPowerShell(fsmEventArg.RemoteData);
break;
default:
s_trace.WriteLine("Server received data unknown targetInterface: {0}", targetInterface);
PSRemotingDataStructureException reasonOfFailure2 = new PSRemotingDataStructureException(RemotingErrorIdStrings.ReceivedUnsupportedRemotingTargetInterfaceType, targetInterface);
RemoteSessionStateMachineEventArgs unknownTargetArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.FatalError, reasonOfFailure2);
RaiseEvent(unknownTargetArg);
break;
}
}
}
/// <summary>
/// This is the handler for ConnectFailed event. In this implementation, this should never
/// happen. This is because the IO channel is stdin/stdout/stderr redirection.
/// Therefore, the connection is a dummy operation.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If the parameter <paramref name="fsmEventArg"/> does not contain ConnectFailed event.
/// </exception>
private void DoConnectFailed(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException("fsmEventArg");
}
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.ConnectFailed, "StateEvent must be ConnectFailed");
if (fsmEventArg.StateEvent != RemoteSessionEvent.ConnectFailed)
{
throw PSTraceSource.NewArgumentException("fsmEventArg");
}
Dbg.Assert(_state == RemoteSessionState.Connecting, "session State must be Connecting");
// This method should not be called in this implementation.
throw PSTraceSource.NewInvalidOperationException();
}
}
/// <summary>
/// This is the handler for FatalError event. It directly calls the DoClose, which
/// is the Close event handler.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
///
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> does not contains FatalError event.
/// </exception>
private void DoFatalError(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException("fsmEventArg");
}
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.FatalError, "StateEvent must be FatalError");
if (fsmEventArg.StateEvent != RemoteSessionEvent.FatalError)
{
throw PSTraceSource.NewArgumentException("fsmEventArg");
}
DoClose(this, fsmEventArg);
}
}
/// <summary>
/// Handle connect event - this is raised when a new client tries to connect to an existing session
/// No changes to state. Calls into the session to handle any post connect operations
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg"></param>
private void DoConnect(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
Dbg.Assert(_state != RemoteSessionState.Idle, "session should not be in idle state when SessionConnect event is queued");
if ((_state != RemoteSessionState.Closed) && (_state != RemoteSessionState.ClosingConnection))
{
_session.HandlePostConnect();
}
}
/// <summary>
/// This is the handler for Close event. It closes the connection.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoClose(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException("fsmEventArg");
}
RemoteSessionState oldState = _state;
switch (oldState)
{
case RemoteSessionState.ClosingConnection:
case RemoteSessionState.Closed:
// do nothing
break;
case RemoteSessionState.Connecting:
case RemoteSessionState.Connected:
case RemoteSessionState.Established:
case RemoteSessionState.EstablishedAndKeySent: //server session will never be in this state.. TODO- remove this
case RemoteSessionState.EstablishedAndKeyReceived:
case RemoteSessionState.EstablishedAndKeyExchanged:
case RemoteSessionState.NegotiationReceived:
case RemoteSessionState.NegotiationSent:
case RemoteSessionState.NegotiationSending:
SetState(RemoteSessionState.ClosingConnection, fsmEventArg.Reason);
_session.SessionDataStructureHandler.CloseConnectionAsync(fsmEventArg.Reason);
break;
case RemoteSessionState.Idle:
case RemoteSessionState.UndefinedState:
default:
Exception forcedCloseException = new PSRemotingTransportException(fsmEventArg.Reason, RemotingErrorIdStrings.ForceClosed);
SetState(RemoteSessionState.Closed, forcedCloseException);
break;
}
CleanAll();
}
}
/// <summary>
/// This is the handler for CloseFailed event.
/// It simply force the new state to be Closed.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoCloseFailed(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException("fsmEventArg");
}
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.CloseFailed, "StateEvent must be CloseFailed");
RemoteSessionState stateBeforeTransition = _state;
SetState(RemoteSessionState.Closed, fsmEventArg.Reason);
// ignore
CleanAll();
}
}
/// <summary>
/// This is the handler for CloseCompleted event. It sets the new state to be Closed.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoCloseCompleted(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException("fsmEventArg");
}
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.CloseCompleted, "StateEvent must be CloseCompleted");
SetState(RemoteSessionState.Closed, fsmEventArg.Reason);
// Close the session only after changing the state..this way
// state machine will not process anything.
_session.Close(fsmEventArg);
CleanAll();
}
}
/// <summary>
/// This is the handler for NegotiationFailed event.
/// It raises a Close event to trigger the connection to be shutdown.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoNegotiationFailed(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException("fsmEventArg");
}
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationFailed, "StateEvent must be NegotiationFailed");
RemoteSessionStateMachineEventArgs closeArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close);
RaiseEventPrivate(closeArg);
}
}
/// <summary>
/// This is the handler for NegotiationTimeout event.
/// If the connection is already Established, it ignores this event.
/// Otherwise, it raises a Close event to trigger a close of the connection.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoNegotiationTimeout(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException("fsmEventArg");
}
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationTimeout, "StateEvent must be NegotiationTimeout");
if (_state == RemoteSessionState.Established)
{
// ignore
return;
}
RemoteSessionStateMachineEventArgs closeArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close);
RaiseEventPrivate(closeArg);
}
}
/// <summary>
/// This is the handler for SendFailed event.
/// This is an indication that the wire layer IO is no longer connected. So it raises
/// a Close event to trigger a connection shutdown.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoSendFailed(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException("fsmEventArg");
}
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.SendFailed, "StateEvent must be SendFailed");
RemoteSessionStateMachineEventArgs closeArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close);
RaiseEventPrivate(closeArg);
}
}
/// <summary>
/// This is the handler for ReceivedFailed event.
/// This is an indication that the wire layer IO is no longer connected. So it raises
/// a Close event to trigger a connection shutdown.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoReceiveFailed(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException("fsmEventArg");
}
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.ReceiveFailed, "StateEvent must be ReceivedFailed");
RemoteSessionStateMachineEventArgs closeArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close);
RaiseEventPrivate(closeArg);
}
}
/// <summary>
/// This method contains all the logic for handling the state machine
/// for key exchange. All the different scenarios are covered in this
/// </summary>
/// <param name="sender">sender of this event, unused</param>
/// <param name="eventArgs">event args</param>
private void DoKeyExchange(object sender, RemoteSessionStateMachineEventArgs eventArgs)
{
//There are corner cases with disconnect that can result in client receiving outdated key exchange packets
//***TODO*** Deal with this on the client side. Key exchange packets should have additional information
//that identify the context of negotiation. Just like callId in SetMax and SetMinRunspaces messages
Dbg.Assert(_state >= RemoteSessionState.Established,
"Key Receiving can only be raised after reaching the Established state");
switch (eventArgs.StateEvent)
{
case RemoteSessionEvent.KeyReceived:
{
//does the server ever start key exchange process??? This may not be required
if (_state == RemoteSessionState.EstablishedAndKeyRequested)
{
// reset the timer
Timer tmp = Interlocked.Exchange(ref _keyExchangeTimer, null);
if (tmp != null)
{
tmp.Dispose();
}
}
// the key import would have been done
// set state accordingly
SetState(RemoteSessionState.EstablishedAndKeyReceived, eventArgs.Reason);
// you need to send an encrypted session key to the client
_session.SendEncryptedSessionKey();
}
break;
case RemoteSessionEvent.KeySent:
{
if (_state == RemoteSessionState.EstablishedAndKeyReceived)
{
// key exchange is now complete
SetState(RemoteSessionState.EstablishedAndKeyExchanged, eventArgs.Reason);
}
}
break;
case RemoteSessionEvent.KeyRequested:
{
if ((_state == RemoteSessionState.Established) || (_state == RemoteSessionState.EstablishedAndKeyExchanged))
{
// the key has been sent set state accordingly
SetState(RemoteSessionState.EstablishedAndKeyRequested, eventArgs.Reason);
// start the timer
_keyExchangeTimer = new Timer(HandleKeyExchangeTimeout, null, BaseTransportManager.ServerDefaultKeepAliveTimeoutMs, Timeout.Infinite);
}
}
break;
case RemoteSessionEvent.KeyReceiveFailed:
{
if ((_state == RemoteSessionState.Established) || (_state == RemoteSessionState.EstablishedAndKeyExchanged))
{
return;
}
DoClose(this, eventArgs);
}
break;
case RemoteSessionEvent.KeySendFailed:
{
DoClose(this, eventArgs);
}
break;
}
}
/// <summary>
/// Handles the timeout for key exchange
/// </summary>
/// <param name="sender">sender of this event</param>
private void HandleKeyExchangeTimeout(object sender)
{
Dbg.Assert(_state == RemoteSessionState.EstablishedAndKeyRequested, "timeout should only happen when waiting for a key");
Timer tmp = Interlocked.Exchange(ref _keyExchangeTimer, null);
if (tmp != null)
{
tmp.Dispose();
}
PSRemotingDataStructureException exception =
new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerKeyExchangeFailed);
RaiseEvent(new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.KeyReceiveFailed, exception));
} // SetStateHandler
#endregion Event Handlers
/// <summary>
/// This method is designed to be a cleanup routine after the connection is closed.
/// It can also be used for graceful shutdown of the server process, which is not currently
/// implemented.
/// </summary>
private void CleanAll()
{
}
/// <summary>
/// Set the FSM state to a new state.
/// </summary>
/// <param name="newState">
/// The new state.
/// </param>
/// <param name="reason">
/// Optional parameter that can provide additional information. This is currently not used.
/// </param>
private void SetState(RemoteSessionState newState, Exception reason)
{
RemoteSessionState oldState = _state;
if (newState != oldState)
{
_state = newState;
s_trace.WriteLine("state machine state transition: from state {0} to state {1}", oldState, _state);
}
// TODO: else should we close the session here?
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
internal class Node {
public Node Left;
public Node Right;
public int Data { get; set; }
}
internal class Problems {
internal static void Swap<T>(ref T data1, ref T data2) {
var temp = data1;
data1 = data2;
data2 = temp;
}
internal static void PreOrderRec(Node temp) {
if (temp == null)
return;
Console.WriteLine(temp.Data);
PreOrderRec(temp.Left);
PreOrderRec(temp.Right);
}
//Calculates the size of the tree http://www.geeksforgeeks.org/write-a-c-program-to-calculate-size-of-a-tree/
internal static int SizeofTree (Node temp) {
if (temp == null)
return 0;
var lh = SizeofTree(temp.Right);
var rh = SizeofTree(temp.Left);
return lh + rh + 1;
}
//Check if two tree are identical http://www.geeksforgeeks.org/write-a-c-program-to-find-the-maximum-depth-or-height-of-a-tree/
internal static bool CheckIfTreesAreIdentical (Node tree1, Node tree2) {
if (tree1 == null && tree2 == null)
return true;
if (tree1 == null || tree2 == null)
return false;
if (tree1.Data != tree2.Data)
return false;
return CheckIfTreesAreIdentical(tree1.Left, tree2.Left) &&
CheckIfTreesAreIdentical(tree1.Right, tree2.Right);
}
//Calculates the height of the tree http://www.geeksforgeeks.org/write-a-c-program-to-find-the-maximum-depth-or-height-of-a-tree/
internal static int HeightOfTree (Node root) {
if (root == null)
return 0;
var lh = HeightOfTree(root.Left);
var rh = HeightOfTree(root.Right);
return Math.Max(lh, rh) + 1;
}
//Deletes the Tree http://www.geeksforgeeks.org/write-a-c-program-to-delete-a-tree/
internal static void DeleteTree (Node root) {
if (root == null)
return;
DeleteTree(root.Left);
DeleteTree(root.Right);
root = null;
}
//Mirrors the Tree http://www.geeksforgeeks.org/write-an-efficient-c-function-to-convert-a-tree-into-its-mirror-tree/
internal static Node TreeMirroring (Node root) {
if (root == null)
return null;
TreeMirroring(root.Left);
TreeMirroring(root.Right);
Swap(ref root.Left, ref root.Right);
return root;
}
//http://www.geeksforgeeks.org/given-a-binary-tree-print-out-all-of-its-root-to-leaf-paths-one-per-line/
internal static void PrintRootToLeafPath(Node root, int [] arr, int idx) {
if (root == null)
return;
arr[idx] = root.Data;
if (root.Left == null && root.Right == null) {
for (int i = 0; i <= idx; i++)
Console.Write(arr[i]); Console.WriteLine();
}
PrintRootToLeafPath(root.Left, arr, idx + 1);
PrintRootToLeafPath(root.Right, arr, idx + 1);
}
internal static void TreeToList (Node root, ref Node list) {
if (root == null)
return;
TreeToList(root.Left, ref list);
if (list == null) {
list = root;
} else {
list.Right = root;
root.Left = list;
list = list.Right;
}
TreeToList(root.Right, ref list);
}
internal static void LevelOrderTraversal(Node root) {
var queue = new Queue<Node>();
queue.Enqueue(root);
while (queue.Count > 0) {
Console.WriteLine(queue.Peek().Data);
if (queue.Peek().Left != null)
queue.Enqueue(queue.Peek().Left);
if (queue.Peek().Right != null)
queue.Enqueue(queue.Peek().Right);
queue.Dequeue();
}
}
internal static void CountLeafNodes(Node root, ref int count) {
if (root == null)
return;
if (root.Left == null && root.Right == null) {
count++; return;
}
CountLeafNodes(root.Left, ref count);
CountLeafNodes(root.Right, ref count);
}
internal static void LevelOrderTraversalSpiral(Node root) {
if (root == null)
return;
LevelOrderTraversal(root);
var stack = new Stack<Node>();
stack.Push(root);
bool flag = false;
while (stack.Count > 0) {
var temp = new Stack<Node>();
flag = !flag;
while (stack.Count > 0) {
Console.Write(stack.Peek().Data + " ");
if (flag) {
if (stack.Peek().Right != null)
temp.Push(stack.Peek().Right);
if (stack.Peek().Left != null)
temp.Push(stack.Peek().Left);
} else {
if (stack.Peek().Left != null)
temp.Push(stack.Peek().Left);
if (stack.Peek().Right != null)
temp.Push(stack.Peek().Right);
}
stack.Pop();
}
Console.WriteLine();
stack = temp;
}
}
internal static bool ChildrenSumProperty(Node root) {
if (root == null)
return true;
if (root.Left == null && root.Right == null)
return true;
int left = 0, right = 0;
if (root.Left != null)
left = root.Left.Data;
if (root.Right != null)
right = root.Right.Data;
return (root.Data == left + right) && ChildrenSumProperty(root.Left) && ChildrenSumProperty(root.Right);
}
internal static void ConvertChildrenSum(Node root) {
if (root == null || (root.Left == null && root.Right == null))
return;
ConvertChildrenSum(root.Left);
ConvertChildrenSum(root.Right);
int left = 0, right = 0;
if (root.Left != null)
left = root.Left.Data;
if (root.Right != null)
right = root.Right.Data;
int diff = left + right - root.Data;
if (diff > 0)
root.Data = root.Data + diff;
if (diff < 0)
AddDiff(root, -diff);
}
internal static void AddDiff(Node root, int diff) {
if (root.Left != null) {
root.Left.Data += diff;
AddDiff(root.Left, diff);
}
if (root.Right != null) {
root.Right.Data += diff;
AddDiff(root.Right, diff);
}
}
internal static int Diameter(Node root, ref int dia) {
if (root == null)
return 0;
int lh = Diameter(root.Left, ref dia);
int rh = Diameter(root.Right, ref dia);
//Console.WriteLine(root.Data + " " + lh + " " + rh);
// Console.WriteLine(dia + " " + (lh + rh + 1));
dia = Math.Max(dia, lh + rh + 1);
return Math.Max(lh, rh) + 1;
}
}
internal class Program {
private static Node NewNode (int value) {
return new Node { Data = value, Left = null, Right = null };
}
private static Node GetTree() {
var node1 = NewNode(5);
node1.Left = NewNode(4);
node1.Right = NewNode(3);
node1.Right.Left = NewNode(100);
node1.Right.Left.Left = NewNode(100);
node1.Right.Left.Left.Left = NewNode(100);
node1.Right.Left.Left.Left.Left = NewNode(100);
node1.Right.Left.Left.Left.Left.Left = NewNode(100);
node1.Left.Left = NewNode(6);
node1.Left.Right = NewNode(7);
node1.Right.Right = NewNode(10);
node1.Right.Right.Right = NewNode(12);
node1.Right.Right.Right.Right = NewNode(12);
node1.Right.Right.Left = NewNode(12);
return node1;
}
private static Node GetSumTree() {
var node = NewNode(10);
node.Left = NewNode(6);
node.Right = NewNode(4);
node.Left.Left = NewNode(2);
node.Left.Right = NewNode(4);
node.Right.Left = NewNode(1);
node.Right.Right = NewNode(3);
return node;
}
private static void SizeofTreeCaller () {
var node = NewNode(5);
node.Left = NewNode(4);
node.Right = NewNode(3);
node.Left.Left = NewNode(6);
//node.Left.Right = NewNode(7);
node.Right.Right = NewNode(10);
Console.WriteLine(Problems.SizeofTree(node));
}
private static void CheckIfTreesAreIdenticalCaller () {
var node1 = NewNode(5);
node1.Left = NewNode(4);
node1.Right = NewNode(3);
node1.Left.Left = NewNode(6);
//node.Left.Right = NewNode(7);
node1.Right.Right = NewNode(10);
var node2 = NewNode(5);
node2.Left = NewNode(4);
node2.Right = NewNode(3);
node2.Left.Left = NewNode(6);
//node.Left.Right = NewNode(7);
node2.Right.Right = NewNode(10);
Console.WriteLine(Problems.CheckIfTreesAreIdentical(node1, node2));
node2.Left.Right = NewNode(7);
Console.WriteLine(Problems.CheckIfTreesAreIdentical(node1, node2));
}
private static void HeightOfTreeCaller() {
var node1 = NewNode(5);
node1.Left = NewNode(4);
node1.Right = NewNode(3);
node1.Left.Left = NewNode(6);
//node.Left.Right = NewNode(7);
node1.Right.Right = NewNode(10);
Console.WriteLine(Problems.HeightOfTree(node1));
node1.Left.Right = NewNode(7);
node1.Left.Right.Right = NewNode(7);
Console.WriteLine(Problems.HeightOfTree(node1));
}
private static void DeleteTreeCaller() {
var node1 = NewNode(5);
node1.Left = NewNode(4);
node1.Right = NewNode(3);
node1.Left.Left = NewNode(6);
//node.Left.Right = NewNode(7);
node1.Right.Right = NewNode(10);
Problems.DeleteTree(node1);
}
private static void PrintRootToLeafPathCaller() {
var node1 = NewNode(5);
node1.Left = NewNode(4);
node1.Right = NewNode(3);
node1.Left.Left = NewNode(6);
node1.Left.Right = NewNode(7);
node1.Right.Right = NewNode(10);
int [] arr = new int[Problems.HeightOfTree(node1) + 1];
Problems.PrintRootToLeafPath(node1, arr, 0);
}
private static void TreeToListCaller() {
Node node2 = null;
Problems.TreeToList(GetTree(), ref node2);
while (node2 != null) {
Console.WriteLine(node2.Data);
node2 = node2.Left;
}
}
private static void LevelOrderTraversalCaller() {
Problems.LevelOrderTraversal(GetTree());
}
private static void CountLeafNodesCaller() {
int count = 0;
Problems.CountLeafNodes(GetTree(), ref count);
Console.WriteLine(count);
}
private static void TreeMirroringCaller() {
Problems.TreeMirroring(GetTree());
}
private static void LevelOrderTraversalSpiralCaller() {
Problems.LevelOrderTraversalSpiral(GetTree());
}
private static void ChildrenSumPropertyCaller() {
Console.WriteLine(Problems.ChildrenSumProperty(GetTree()));
Console.WriteLine(Problems.ChildrenSumProperty(GetSumTree()));
}
private static void ConvertChildrenSumCaller() {
var node = GetTree();
var node1 = GetSumTree();
Console.WriteLine(Problems.ChildrenSumProperty(node));
Console.WriteLine(Problems.ChildrenSumProperty(node1));
Problems.ConvertChildrenSum(node);
Problems.ConvertChildrenSum(node1);
Console.WriteLine(Problems.ChildrenSumProperty(node));
Console.WriteLine(Problems.ChildrenSumProperty(node1));
}
static void DiameterCaller() {
int dia = 0;
Problems.Diameter(GetTree(), ref dia);
Console.WriteLine(dia); dia = 0;
Problems.Diameter(GetSumTree(), ref dia);
Console.WriteLine(dia);
}
private static void Main (string[] args) {
// SizeofTreeCaller();
// CheckIfTreesAreIdenticalCaller();
// HeightOfTreeCaller();
// DeleteTreeCaller();
// TreeMirroringCaller();
// PrintRootToLeafPathCaller();
// TreeToListCaller();
// LevelOrderTraversalCaller();
// CountLeafNodesCaller();
//LevelOrderTraversalSpiralCaller();
// ChildrenSumPropertyCaller();
//ConvertChildrenSumCaller();
DiameterCaller();
// //Console.ReadKey();
}
}
| |
// Copyright (C) 2012-2019 Luca Piccioni
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace OpenGL.Objects
{
/// <summary>
/// Generic collection for referencing <see cref="IResource"/> instances.
/// </summary>
/// <typeparam name="T">
/// A class that implements the <see cref="IResource"/> interface.
/// </typeparam>
public class ResourceCollection<T> : ICollection<T>, IDisposable where T : class, IResource
{
#region Collection Methods
/// <summary>
/// Add a set of items to this collection.
/// </summary>
/// <param name="items">
/// The set to add to this collection.
/// </param>
/// <exception cref="ArgumentNullException">
/// Exception thrown if <paramref name="items"/> is null.
/// </exception>
public void AddRange(IEnumerable items)
{
if (items == null)
throw new ArgumentNullException("items");
foreach (T item in items)
if (item != null)
Add(item);
}
/// <summary>
/// Add a set of items to this collection.
/// </summary>
/// <param name="items">
/// The set to add to this collection.
/// </param>
/// <exception cref="ArgumentNullException">
/// Exception thrown if <paramref name="items"/> is null.
/// </exception>
public void AddRange(IEnumerable<T> items)
{
if (items == null)
throw new ArgumentNullException("items");
foreach (T item in items)
if (item != null)
Add(item);
}
/// <summary>
///
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public T this[int index]
{
get { return (_Resources[index]); }
set { _Resources[index] = value; }
}
#endregion
#region ICollection<IGraphicsResource> Implementation
/// <summary>
/// Adds an item to this collection.
/// </summary>
/// <param name="item">
/// The object to add to this collection.
/// </param>
/// <exception cref="ArgumentNullException">
/// Exception thrown if <paramref name="item"/> is null.
/// </exception>
public void Add(T item)
{
if (IsDisposed)
throw new ObjectDisposedException("ResourceCollection");
if (item == null)
throw new ArgumentNullException("item");
// Reference the reasource
item.IncRef();
// Collect resource
_Resources.Add(item);
}
/// <summary>
/// Removes all items from ththis collection.
/// </summary>
public void Clear()
{
if (IsDisposed)
throw new ObjectDisposedException("ResourceCollection");
foreach (T resource in _Resources)
resource.DecRef();
_Resources.Clear();
}
/// <summary>
/// Determines whether this collection contains a specific value.
/// </summary>
/// <param name="item">
/// The object to locate in this collection.
/// </param>
/// <returns>
/// It returns true if item is found in this collection; otherwise, false.
/// </returns>
public bool Contains(T item)
{
if (IsDisposed)
throw new ObjectDisposedException("ResourceCollection");
return (_Resources.Contains(item));
}
/// <summary>
/// Copies the elements of this collection to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
/// </summary>
/// <param name="array">
/// The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from this collection.
/// The <see cref="T:System.Array"/> must have zero-based indexing.</param>
/// <param name="arrayIndex">
/// The zero-based index in array at which copying begins.
/// </param>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// exception thrown if <paramref name="arrayIndex"/> is less than 0.
/// </exception>
/// <exception cref="T:System.ArgumentNullException">
/// Exception thrown if <paramref name="array"/> is null.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// Exception thrown if array is multidimensional. or <paramref name="arrayIndex"/> is equal to or greater than the length of array; or
/// the number of elements in the source collection is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination
/// array; or Type T cannot be cast automatically to the type of the destination array.
/// </exception>
public void CopyTo(T[] array, int arrayIndex)
{
if (IsDisposed)
throw new ObjectDisposedException("ResourceCollection");
_Resources.CopyTo(array, arrayIndex);
}
/// <summary>
/// Removes the first occurrence of a specific object from this collection.
/// </summary>
/// <param name="item">
/// The object to remove from this collection.</param>
/// <returns>
/// It returns true if item was successfully removed from this collection; otherwise, false. This method also
/// returns false if item is not found in the this collection.
/// </returns>
public bool Remove(T item)
{
if (IsDisposed)
throw new ObjectDisposedException("ResourceCollection");
bool flag = _Resources.Remove(item);
if (flag)
item.DecRef();
return (flag);
}
/// <summary>
/// Gets the number of elements contained in this collection.
/// </summary>
/// <returns>
/// The number of elements contained in this collection.
/// </returns>
public int Count
{
get
{
if (IsDisposed)
throw new ObjectDisposedException("ResourceCollection");
return (_Resources.Count);
}
}
/// <summary>
/// Gets a value indicating whether this collection is read-only.
/// </summary>
/// <returns>
/// It returns true if this collection is read-only; otherwise, false.
/// </returns>
public bool IsReadOnly { get { return (false); } }
/// <summary>
/// The collection of resources.
/// </summary>
private readonly List<T> _Resources = new List<T>();
#endregion
#region IEnumerable Implementation
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<T> GetEnumerator()
{
if (IsDisposed)
throw new ObjectDisposedException("ResourceCollection");
return (_Resources.GetEnumerator());
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
if (IsDisposed)
throw new ObjectDisposedException("ResourceCollection");
return GetEnumerator();
}
#endregion
#region IDisposable Implementation
/// <summary>
/// Finalizer.
/// </summary>
~ResourceCollection()
{
Dispose(false);
}
/// <summary>
/// Get whether this instance has been disposed.
/// </summary>
public bool IsDisposed { get { return (_Disposed); } }
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting managed/unmanaged resources.
/// </summary>
/// <param name="disposing">
/// A <see cref="Boolean"/> indicating whether this method is called by <see cref="Dispose()"/>. If it is false,
/// this method is called by the finalizer.
/// </param>
protected virtual void Dispose(bool disposing)
{
// Clearing unreference all collected resources
if (disposing)
Clear();
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public virtual void Dispose()
{
// Do not call Dispose(bool) twice
GC.SuppressFinalize(this);
// Dispose this object
Dispose(true);
// Mask as disposed
_Disposed = true;
}
/// <summary>
/// Flag indicating that this instance has been disposed.
/// </summary>
private bool _Disposed;
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using BenchmarkDotNet.Attributes;
using System.Buffers.Text;
using System.IO;
using System.Text.Formatting;
namespace System.Text.JsonLab.Benchmarks
{
[MemoryDiagnoser]
public class JsonWriterPerf
{
private const int ExtraArraySize = 500;
private const int BufferSize = 1024 + (ExtraArraySize * 64);
private ArrayFormatter _arrayFormatter;
private MemoryStream _memoryStream;
private StreamWriter _streamWriter;
private StringBuilder _stringBuilder;
private int[] _data;
[Params(true, false)]
public bool IsUTF8Encoded;
[Params(true, false)]
public bool Formatted;
[GlobalSetup]
public void Setup()
{
_data = new int[ExtraArraySize];
Random rand = new Random(42);
for (int i = 0; i < ExtraArraySize; i++)
{
_data[i] = rand.Next(-10000, 10000);
}
if (IsUTF8Encoded)
{
var buffer = new byte[BufferSize];
_memoryStream = new MemoryStream(buffer);
_streamWriter = new StreamWriter(_memoryStream, new UTF8Encoding(false), BufferSize, true);
_arrayFormatter = new ArrayFormatter(BufferSize, SymbolTable.InvariantUtf8);
}
else
{
_stringBuilder = new StringBuilder();
_arrayFormatter = new ArrayFormatter(BufferSize, SymbolTable.InvariantUtf16);
}
}
[Benchmark]
public void WriterSystemTextJsonBasic()
{
_arrayFormatter.Clear();
if (IsUTF8Encoded)
WriterSystemTextJsonBasicUtf8(Formatted, _arrayFormatter, _data);
else
WriterSystemTextJsonBasicUtf16(Formatted, _arrayFormatter, _data);
}
[Benchmark]
public void WriterNewtonsoftBasic()
{
WriterNewtonsoftBasic(Formatted, GetWriter(), _data);
}
[Benchmark]
public void WriterSystemTextJsonHelloWorld()
{
_arrayFormatter.Clear();
if (IsUTF8Encoded)
WriterSystemTextJsonHelloWorldUtf8(Formatted, _arrayFormatter);
else
WriterSystemTextJsonHelloWorldUtf16(Formatted, _arrayFormatter);
}
[Benchmark]
public void WriterNewtonsoftHelloWorld()
{
WriterNewtonsoftHelloWorld(Formatted, GetWriter());
}
private TextWriter GetWriter()
{
TextWriter writer;
if (IsUTF8Encoded)
{
_memoryStream.Seek(0, SeekOrigin.Begin);
writer = _streamWriter;
}
else
{
_stringBuilder.Clear();
writer = new StringWriter(_stringBuilder);
}
return writer;
}
private static void WriterSystemTextJsonBasicUtf8(bool formatted, ArrayFormatter output, int[] data)
{
var json = new JsonWriter(output, true, formatted);
json.WriteObjectStart();
json.WriteAttribute("age", 42);
json.WriteAttribute("first", "John");
json.WriteAttribute("last", "Smith");
json.WriteArrayStart("phoneNumbers");
json.WriteValue("425-000-1212");
json.WriteValue("425-000-1213");
json.WriteArrayEnd();
json.WriteObjectStart("address");
json.WriteAttribute("street", "1 Microsoft Way");
json.WriteAttribute("city", "Redmond");
json.WriteAttribute("zip", 98052);
json.WriteObjectEnd();
// Add a large array of values
json.WriteArrayStart("ExtraArray");
for (var i = 0; i < ExtraArraySize; i++)
{
json.WriteValue(data[i]);
}
json.WriteArrayEnd();
json.WriteObjectEnd();
}
private static void WriterSystemTextJsonBasicUtf16(bool formatted, ArrayFormatter output, int[] data)
{
var json = new JsonWriter(output, false, formatted);
json.WriteObjectStart();
json.WriteAttribute("age", 42);
json.WriteAttribute("first", "John");
json.WriteAttribute("last", "Smith");
json.WriteArrayStart("phoneNumbers");
json.WriteValue("425-000-1212");
json.WriteValue("425-000-1213");
json.WriteArrayEnd();
json.WriteObjectStart("address");
json.WriteAttribute("street", "1 Microsoft Way");
json.WriteAttribute("city", "Redmond");
json.WriteAttribute("zip", 98052);
json.WriteObjectEnd();
// Add a large array of values
json.WriteArrayStart("ExtraArray");
for (var i = 0; i < ExtraArraySize; i++)
{
json.WriteValue(data[i]);
}
json.WriteArrayEnd();
json.WriteObjectEnd();
}
private static void WriterNewtonsoftBasic(bool formatted, TextWriter writer, int[] data)
{
using (var json = new Newtonsoft.Json.JsonTextWriter(writer))
{
json.Formatting = formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None;
json.WriteStartObject();
json.WritePropertyName("age");
json.WriteValue(42);
json.WritePropertyName("first");
json.WriteValue("John");
json.WritePropertyName("last");
json.WriteValue("Smith");
json.WritePropertyName("phoneNumbers");
json.WriteStartArray();
json.WriteValue("425-000-1212");
json.WriteValue("425-000-1213");
json.WriteEnd();
json.WritePropertyName("address");
json.WriteStartObject();
json.WritePropertyName("street");
json.WriteValue("1 Microsoft Way");
json.WritePropertyName("city");
json.WriteValue("Redmond");
json.WritePropertyName("zip");
json.WriteValue(98052);
json.WriteEnd();
// Add a large array of values
json.WritePropertyName("ExtraArray");
json.WriteStartArray();
for (var i = 0; i < ExtraArraySize; i++)
{
json.WriteValue(data[i]);
}
json.WriteEnd();
json.WriteEnd();
}
}
private static void WriterSystemTextJsonHelloWorldUtf8(bool formatted, ArrayFormatter output)
{
var json = new JsonWriter(output, true, formatted);
json.WriteObjectStart();
json.WriteAttribute("message", "Hello, World!");
json.WriteObjectEnd();
}
private static void WriterSystemTextJsonHelloWorldUtf16(bool formatted, ArrayFormatter output)
{
var json = new JsonWriter(output, false, formatted);
json.WriteObjectStart();
json.WriteAttribute("message", "Hello, World!");
json.WriteObjectEnd();
}
private static void WriterNewtonsoftHelloWorld(bool formatted, TextWriter writer)
{
using (var json = new Newtonsoft.Json.JsonTextWriter(writer))
{
json.Formatting = formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None;
json.WriteStartObject();
json.WritePropertyName("message");
json.WriteValue("Hello, World!");
json.WriteEnd();
}
}
}
}
| |
//
// RedirectFS.cs: Port of
// http://fuse.cvs.sourceforge.net/fuse/fuse/example/fusexmp.c?view=log
//
// Authors:
// Jonathan Pryor (jonpryor@vt.edu)
//
// (C) 2006 Jonathan Pryor
//
// Mono.Fuse example program
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using Mono.Fuse;
using Mono.Unix.Native;
namespace Mono.Fuse.Samples {
class RedirectFS : FileSystem {
private string basedir;
public RedirectFS ()
{
}
protected override Errno OnGetPathStatus (string path, out Stat buf)
{
int r = Syscall.lstat (basedir+path, out buf);
if (r == -1)
return Stdlib.GetLastError ();
return 0;
}
protected override Errno OnAccessPath (string path, AccessModes mask)
{
int r = Syscall.access (basedir+path, mask);
if (r == -1)
return Stdlib.GetLastError ();
return 0;
}
protected override Errno OnReadSymbolicLink (string path, out string target)
{
target = null;
StringBuilder buf = new StringBuilder (256);
do {
int r = Syscall.readlink (basedir+path, buf);
if (r < 0) {
return Stdlib.GetLastError ();
}
else if (r == buf.Capacity) {
buf.Capacity *= 2;
}
else {
target = buf.ToString (0, r);
return 0;
}
} while (true);
}
protected override Errno OnReadDirectory (string path, OpenedPathInfo fi,
out IEnumerable<DirectoryEntry> paths)
{
IntPtr dp = Syscall.opendir (basedir+path);
if (dp == IntPtr.Zero) {
paths = null;
return Stdlib.GetLastError ();
}
Dirent de;
List<DirectoryEntry> entries = new List<DirectoryEntry> ();
while ((de = Syscall.readdir (dp)) != null) {
DirectoryEntry e = new DirectoryEntry (de.d_name);
e.Stat.st_ino = de.d_ino;
e.Stat.st_mode = (FilePermissions) (de.d_type << 12);
entries.Add (e);
}
Syscall.closedir (dp);
paths = entries;
return 0;
}
protected override Errno OnCreateSpecialFile (string path, FilePermissions mode, ulong rdev)
{
int r;
// On Linux, this could just be `mknod(basedir+path, mode, rdev)' but this is
// more portable.
if ((mode & FilePermissions.S_IFMT) == FilePermissions.S_IFREG) {
r = Syscall.open (basedir+path, OpenFlags.O_CREAT | OpenFlags.O_EXCL |
OpenFlags.O_WRONLY, mode);
if (r >= 0)
r = Syscall.close (r);
}
else if ((mode & FilePermissions.S_IFMT) == FilePermissions.S_IFIFO) {
r = Syscall.mkfifo (basedir+path, mode);
}
else {
r = Syscall.mknod (basedir+path, mode, rdev);
}
if (r == -1)
return Stdlib.GetLastError ();
return 0;
}
protected override Errno OnCreateDirectory (string path, FilePermissions mode)
{
int r = Syscall.mkdir (basedir+path, mode);
if (r == -1)
return Stdlib.GetLastError ();
return 0;
}
protected override Errno OnRemoveFile (string path)
{
int r = Syscall.unlink (basedir+path);
if (r == -1)
return Stdlib.GetLastError ();
return 0;
}
protected override Errno OnRemoveDirectory (string path)
{
int r = Syscall.rmdir (basedir+path);
if (r == -1)
return Stdlib.GetLastError ();
return 0;
}
protected override Errno OnCreateSymbolicLink (string from, string to)
{
int r = Syscall.symlink (from, basedir+to);
if (r == -1)
return Stdlib.GetLastError ();
return 0;
}
protected override Errno OnRenamePath (string from, string to)
{
int r = Syscall.rename (basedir+from, basedir+to);
if (r == -1)
return Stdlib.GetLastError ();
return 0;
}
protected override Errno OnCreateHardLink (string from, string to)
{
int r = Syscall.link (basedir+from, basedir+to);
if (r == -1)
return Stdlib.GetLastError ();
return 0;
}
protected override Errno OnChangePathPermissions (string path, FilePermissions mode)
{
int r = Syscall.chmod (basedir+path, mode);
if (r == -1)
return Stdlib.GetLastError ();
return 0;
}
protected override Errno OnChangePathOwner (string path, long uid, long gid)
{
int r = Syscall.lchown (basedir+path, (uint) uid, (uint) gid);
if (r == -1)
return Stdlib.GetLastError ();
return 0;
}
protected override Errno OnTruncateFile (string path, long size)
{
int r = Syscall.truncate (basedir+path, size);
if (r == -1)
return Stdlib.GetLastError ();
return 0;
}
protected override Errno OnChangePathTimes (string path, ref Utimbuf buf)
{
int r = Syscall.utime (basedir+path, ref buf);
if (r == -1)
return Stdlib.GetLastError ();
return 0;
}
protected override Errno OnOpenHandle (string path, OpenedPathInfo info)
{
return ProcessFile (basedir+path, info.OpenFlags, delegate (int fd) {return 0;});
}
private delegate int FdCb (int fd);
private static Errno ProcessFile (string path, OpenFlags flags, FdCb cb)
{
int fd = Syscall.open (path, flags);
if (fd == -1)
return Stdlib.GetLastError ();
int r = cb (fd);
Errno res = 0;
if (r == -1)
res = Stdlib.GetLastError ();
Syscall.close (fd);
return res;
}
protected override unsafe Errno OnReadHandle (string path, OpenedPathInfo info, byte[] buf,
long offset, out int bytesRead)
{
int br = 0;
Errno e = ProcessFile (basedir+path, OpenFlags.O_RDONLY, delegate (int fd) {
fixed (byte *pb = buf) {
return br = (int) Syscall.pread (fd, pb, (ulong) buf.Length, offset);
}
});
bytesRead = br;
return e;
}
protected override unsafe Errno OnWriteHandle (string path, OpenedPathInfo info,
byte[] buf, long offset, out int bytesWritten)
{
int bw = 0;
Errno e = ProcessFile (basedir+path, OpenFlags.O_WRONLY, delegate (int fd) {
fixed (byte *pb = buf) {
return bw = (int) Syscall.pwrite (fd, pb, (ulong) buf.Length, offset);
}
});
bytesWritten = bw;
return e;
}
protected override Errno OnGetFileSystemStatus (string path, out Statvfs stbuf)
{
int r = Syscall.statvfs (basedir+path, out stbuf);
if (r == -1)
return Stdlib.GetLastError ();
return 0;
}
protected override Errno OnReleaseHandle (string path, OpenedPathInfo info)
{
return 0;
}
protected override Errno OnSynchronizeHandle (string path, OpenedPathInfo info, bool onlyUserData)
{
return 0;
}
protected override Errno OnSetPathExtendedAttribute (string path, string name, byte[] value, XattrFlags flags)
{
int r = Syscall.lsetxattr (basedir+path, name, value, (ulong) value.Length, flags);
if (r == -1)
return Stdlib.GetLastError ();
return 0;
}
protected override Errno OnGetPathExtendedAttribute (string path, string name, byte[] value, out int bytesWritten)
{
int r = bytesWritten = (int) Syscall.lgetxattr (basedir+path, name, value, (ulong) value.Length);
if (r == -1)
return Stdlib.GetLastError ();
return 0;
}
protected override Errno OnListPathExtendedAttributes (string path, out string[] names)
{
int r = (int) Syscall.llistxattr (basedir+path, out names);
if (r == -1)
return Stdlib.GetLastError ();
return 0;
}
protected override Errno OnRemovePathExtendedAttribute (string path, string name)
{
int r = Syscall.lremovexattr (basedir+path, name);
if (r == -1)
return Stdlib.GetLastError ();
return 0;
}
protected override Errno OnLockHandle (string file, OpenedPathInfo info, FcntlCommand cmd, ref Flock @lock)
{
Flock _lock = @lock;
Errno e = ProcessFile (basedir+file, info.OpenFlags, fd => Syscall.fcntl (fd, cmd, ref _lock));
@lock = _lock;
return e;
}
private bool ParseArguments (string[] args)
{
for (int i = 0; i < args.Length; ++i) {
switch (args [i]) {
case "-h":
case "--help":
ShowHelp ();
return false;
default:
if (base.MountPoint == null)
base.MountPoint = args [i];
else
basedir = args [i];
break;
}
}
if (base.MountPoint == null) {
return Error ("missing mountpoint");
}
if (basedir == null) {
return Error ("missing basedir");
}
return true;
}
private static void ShowHelp ()
{
Console.Error.WriteLine ("usage: redirectfs [options] mountpoint basedir:");
FileSystem.ShowFuseHelp ("redirectfs");
Console.Error.WriteLine ();
Console.Error.WriteLine ("redirectfs options:");
Console.Error.WriteLine (" basedir Directory to mirror");
}
private static bool Error (string message)
{
Console.Error.WriteLine ("redirectfs: error: {0}", message);
return false;
}
public static void Main (string[] args)
{
using (RedirectFS fs = new RedirectFS ()) {
string[] unhandled = fs.ParseFuseArguments (args);
if (!fs.ParseArguments (unhandled))
return;
fs.Start ();
}
}
}
}
| |
//
// This file is part of the game Voxalia, created by FreneticXYZ.
// This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license.
// See README.md or LICENSE.txt for contents of the MIT license.
// If these are not available, see https://opensource.org/licenses/MIT
//
using System.Collections.Generic;
using BEPUutilities;
using BEPUphysics.CollisionShapes;
using BEPUphysics.CollisionShapes.ConvexShapes;
namespace Voxalia.Shared.BlockShapes
{
/// <summary>
/// The default cubic block.
/// </summary>
public class BSD0: BlockShapeDetails
{
public BSD0()
{
BlockShapeCache = new BoxShape(1f, 1f, 1f);
OffsetCache = new Location(0.5);
ShrunkBlockShapeCache = new BoxShape(SHRINK_CONSTANT, SHRINK_CONSTANT, SHRINK_CONSTANT);
ShrunkOffsetCache = new Location(SHRINK_CONSTANT * 0.5);
}
public override List<Vector3> GetVertices(Vector3 pos, bool XP, bool XM, bool YP, bool YM, bool TOP, bool BOTTOM)
{
List<Vector3> Vertices = new List<Vector3>();
if (!TOP)
{
Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z + 1));
Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z + 1));
Vertices.Add(new Vector3(pos.X, pos.Y, pos.Z + 1));
Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z + 1));
Vertices.Add(new Vector3(pos.X + 1, pos.Y, pos.Z + 1));
Vertices.Add(new Vector3(pos.X, pos.Y, pos.Z + 1));
}
if (!BOTTOM)
{
Vertices.Add(new Vector3(pos.X, pos.Y, pos.Z));
Vertices.Add(new Vector3(pos.X + 1, pos.Y, pos.Z));
Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z));
Vertices.Add(new Vector3(pos.X, pos.Y, pos.Z));
Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z));
Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z));
}
if (!XP)
{
Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z + 1));
Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z));
Vertices.Add(new Vector3(pos.X + 1, pos.Y, pos.Z));
Vertices.Add(new Vector3(pos.X + 1, pos.Y, pos.Z + 1));
Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z + 1));
Vertices.Add(new Vector3(pos.X + 1, pos.Y, pos.Z));
}
if (!XM)
{
Vertices.Add(new Vector3(pos.X, pos.Y, pos.Z));
Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z));
Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z + 1));
Vertices.Add(new Vector3(pos.X, pos.Y, pos.Z));
Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z + 1));
Vertices.Add(new Vector3(pos.X, pos.Y, pos.Z + 1));
}
if (!YP)
{
Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z));
Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z));
Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z + 1));
Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z));
Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z + 1));
Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z + 1));
}
if (!YM)
{
Vertices.Add(new Vector3(pos.X + 1, pos.Y, pos.Z + 1));
Vertices.Add(new Vector3(pos.X + 1, pos.Y, pos.Z));
Vertices.Add(new Vector3(pos.X, pos.Y, pos.Z));
Vertices.Add(new Vector3(pos.X, pos.Y, pos.Z + 1));
Vertices.Add(new Vector3(pos.X + 1, pos.Y, pos.Z + 1));
Vertices.Add(new Vector3(pos.X, pos.Y, pos.Z));
}
return Vertices;
}
public override List<Vector3> GetNormals(Vector3 blockPos, bool XP, bool XM, bool YP, bool YM, bool TOP, bool BOTTOM)
{
List<Vector3> Norms = new List<Vector3>();
if (!TOP)
{
for (int i = 0; i < 6; i++)
{
Norms.Add(new Vector3(0, 0, 1));
}
}
if (!BOTTOM)
{
for (int i = 0; i < 6; i++)
{
Norms.Add(new Vector3(0, 0, -1));
}
}
if (!XP)
{
for (int i = 0; i < 6; i++)
{
Norms.Add(new Vector3(1, 0, 0));
}
}
if (!XM)
{
for (int i = 0; i < 6; i++)
{
Norms.Add(new Vector3(-1, 0, 0));
}
}
if (!YP)
{
for (int i = 0; i < 6; i++)
{
Norms.Add(new Vector3(0, 1, 0));
}
}
if (!YM)
{
for (int i = 0; i < 6; i++)
{
Norms.Add(new Vector3(0, -1, 0));
}
}
return Norms;
}
public override List<Vector3> GetTCoords(Vector3 blockPos, Material mat, bool XP, bool XM, bool YP, bool YM, bool TOP, bool BOTTOM)
{
List<Vector3> TCoords = new List<Vector3>();
if (!TOP)
{
int tID_TOP = mat.TextureID(MaterialSide.TOP);
TCoords.Add(new Vector3(0, 1, tID_TOP));
TCoords.Add(new Vector3(1, 1, tID_TOP));
TCoords.Add(new Vector3(0, 0, tID_TOP));
TCoords.Add(new Vector3(1, 1, tID_TOP));
TCoords.Add(new Vector3(1, 0, tID_TOP));
TCoords.Add(new Vector3(0, 0, tID_TOP));
}
if (!BOTTOM)
{
int tID_BOTTOM = mat.TextureID(MaterialSide.BOTTOM);
TCoords.Add(new Vector3(0, 0, tID_BOTTOM));
TCoords.Add(new Vector3(1, 1, tID_BOTTOM));
TCoords.Add(new Vector3(0, 1, tID_BOTTOM));
TCoords.Add(new Vector3(0, 0, tID_BOTTOM));
TCoords.Add(new Vector3(1, 0, tID_BOTTOM));
TCoords.Add(new Vector3(1, 1, tID_BOTTOM));
}
if (!XP)
{
int tID_XP = mat.TextureID(MaterialSide.XP);
TCoords.Add(new Vector3(1, 0, tID_XP));
TCoords.Add(new Vector3(1, 1, tID_XP));
TCoords.Add(new Vector3(0, 1, tID_XP));
TCoords.Add(new Vector3(0, 0, tID_XP));
TCoords.Add(new Vector3(1, 0, tID_XP));
TCoords.Add(new Vector3(0, 1, tID_XP));
}
if (!XM)
{
int tID_XM = mat.TextureID(MaterialSide.XM);
TCoords.Add(new Vector3(1, 1, tID_XM));
TCoords.Add(new Vector3(0, 1, tID_XM));
TCoords.Add(new Vector3(0, 0, tID_XM));
TCoords.Add(new Vector3(1, 1, tID_XM));
TCoords.Add(new Vector3(0, 0, tID_XM));
TCoords.Add(new Vector3(1, 0, tID_XM));
}
if (!YP)
{
int tID_YP = mat.TextureID(MaterialSide.YP);
TCoords.Add(new Vector3(1, 1, tID_YP));
TCoords.Add(new Vector3(0, 1, tID_YP));
TCoords.Add(new Vector3(0, 0, tID_YP));
TCoords.Add(new Vector3(1, 1, tID_YP));
TCoords.Add(new Vector3(0, 0, tID_YP));
TCoords.Add(new Vector3(1, 0, tID_YP));
}
if (!YM)
{
int tID_YM = mat.TextureID(MaterialSide.YM);
TCoords.Add(new Vector3(1, 0, tID_YM));
TCoords.Add(new Vector3(1, 1, tID_YM));
TCoords.Add(new Vector3(0, 1, tID_YM));
TCoords.Add(new Vector3(0, 0, tID_YM));
TCoords.Add(new Vector3(1, 0, tID_YM));
TCoords.Add(new Vector3(0, 1, tID_YM));
}
return TCoords;
}
public override KeyValuePair<List<Vector4>, List<Vector4>> GetStretchData(Vector3 blockpos, List<Vector3> vertices, BlockInternal XP, BlockInternal XM,
BlockInternal YP, BlockInternal YM, BlockInternal ZP, BlockInternal ZM, bool bxp, bool bxm, bool byp, bool bym, bool bzp, bool bzm)
{
List<Vector4> sdat = new List<Vector4>();
List<Vector4> swei = new List<Vector4>();
if (!bzp)
{
double txp = XP.Material.TextureID(MaterialSide.TOP);
double txm = XM.Material.TextureID(MaterialSide.TOP);
double typ = YP.Material.TextureID(MaterialSide.TOP);
double tym = YM.Material.TextureID(MaterialSide.TOP);
double zer = 0;
double vxp = XP.IsOpaque() ? 1 : 0;
double vxm = XM.IsOpaque() ? 1 : 0;
double vyp = YP.IsOpaque() ? 1 : 0;
double vym = XM.IsOpaque() ? 1 : 0;
for (int i = 0; i < 6; i++)
{
sdat.Add(new Vector4(txp, txm, typ, tym));
}
swei.Add(new Vector4(zer, vxm, vyp, zer));
swei.Add(new Vector4(vxp, zer, vyp, zer));
swei.Add(new Vector4(zer, vxm, zer, vym));
swei.Add(new Vector4(vxp, zer, vyp, zer));
swei.Add(new Vector4(vxp, zer, zer, vym));
swei.Add(new Vector4(zer, vxm, zer, vym));
}
if (!bzm)
{
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
}
if (!bxp)
{
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
}
if (!bxm)
{
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
}
if (!byp)
{
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
}
if (!bym)
{
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
sdat.Add(new Vector4(5, 5, 5, 5));
swei.Add(new Vector4(1, 1, 1, 1));
}
return new KeyValuePair<List<Vector4>, List<Vector4>>(sdat, swei);
}
public override bool OccupiesXP()
{
return true;
}
public override bool OccupiesYP()
{
return true;
}
public override bool OccupiesXM()
{
return true;
}
public override bool OccupiesYM()
{
return true;
}
public override bool OccupiesTOP()
{
return true;
}
public override bool OccupiesBOTTOM()
{
return true;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Cache
{
using System;
using System.Linq;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Impl.Transactions;
using Apache.Ignite.Core.Transactions;
using NUnit.Framework;
using NUnit.Framework.Constraints;
/// <summary>
/// Tests <see cref="ITransactions.GetLocalActiveTransactions"/>.
/// </summary>
public class CacheLocalActiveTransactionsTest : TestBase
{
/// <summary>
/// Tests that transaction properties are applied and propagated properly.
/// </summary>
[Test]
public void TestTxAttributes()
{
var cache = Cache();
var transactions = cache.Ignite.GetTransactions();
var label = TestUtils.TestName;
var timeout = TimeSpan.FromDays(1);
var isolations = new[]
{
TransactionIsolation.Serializable,
TransactionIsolation.ReadCommitted,
TransactionIsolation.RepeatableRead
};
var options = new[] {TransactionConcurrency.Optimistic, TransactionConcurrency.Pessimistic};
Assert.IsEmpty(transactions.GetLocalActiveTransactions());
foreach (var concurrency in options)
foreach (var isolation in isolations)
{
using (var tx = transactions.WithLabel(label).TxStart(concurrency, isolation, timeout, 1))
{
var activeTransactions = transactions.GetLocalActiveTransactions();
Assert.AreEqual(1, activeTransactions.Count);
var txView = activeTransactions.First();
Assert.AreEqual(concurrency, txView.Concurrency);
Assert.AreEqual(isolation, txView.Isolation);
Assert.AreEqual(tx.NodeId, txView.NodeId);
Assert.AreEqual(tx.State, txView.State);
Assert.AreEqual(label, txView.Label);
Assert.AreEqual(timeout, txView.Timeout);
Assert.IsTrue(txView.IsRollbackOnly);
}
}
Assert.IsEmpty(transactions.GetLocalActiveTransactions());
}
/// <summary>
/// Test that rollbacks.
/// </summary>
[Test]
[TestCase(true)]
[TestCase(false)]
public void TestRollbacks(bool async)
{
var cache = Cache();
var transactions = cache.Ignite.GetTransactions();
cache.Put(1, 1);
cache.Put(2, 2);
using (transactions.TxStart())
{
var local = transactions.GetLocalActiveTransactions().Single();
cache.Put(1, 10);
cache.Put(2, 20);
if (async)
{
local.RollbackAsync().Wait();
}
else
{
local.Rollback();
}
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(2, cache.Get(2));
}
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(2, cache.Get(2));
}
/// <summary>
/// Test that Dispose does not end transaction.
/// </summary>
[Test]
public void TestDisposeDoesNotEndTx()
{
var cache = Cache();
var transactions = cache.Ignite.GetTransactions();
cache.Put(1, 1);
cache.Put(2, 2);
using (transactions.TxStart())
{
var local = transactions.GetLocalActiveTransactions().Single();
cache.Put(1, 10);
cache.Put(2, 20);
local.Dispose();
cache.Put(2, 200);
Assert.AreEqual(10, cache.Get(1));
Assert.AreEqual(200, cache.Get(2));
}
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(2, cache.Get(2));
}
/// <summary>
/// Test that operation throws.
/// </summary>
[Test]
public void TestUnsupportedOperationsThrow()
{
var cache = Cache();
var transactions = cache.Ignite.GetTransactions();
Action<object> dummy = obj => { };
Action<ITransaction>[] actions =
{
t => t.Commit(),
t => t.CommitAsync(),
t => dummy(t.StartTime),
t => dummy(t.ThreadId),
t => t.AddMeta("test", "test"),
t => t.Meta<string>("test"),
t => t.RemoveMeta<string>("test"),
};
using (transactions.TxStart())
{
var local = transactions.GetLocalActiveTransactions().Single();
var constraint = new ReusableConstraint(Is.TypeOf<InvalidOperationException>()
.And.Message.EqualTo("Operation is not supported by rollback only transaction."));
foreach (var action in actions)
{
Assert.Throws(constraint, () => action(local));
}
}
}
/// <summary>
/// Tests that multiple rollback attempts will throw.
/// </summary>
[Test]
public void TestMultipleRollbackThrows()
{
var cache = Cache();
var transactions = cache.Ignite.GetTransactions();
using (transactions.TxStart())
{
var local = (TransactionRollbackOnlyProxy)transactions.GetLocalActiveTransactions().Single();
local.Rollback();
var constraint = new ReusableConstraint(Is.TypeOf<InvalidOperationException>()
.And.Message.Contains("Transaction " + local.Id + " is closed"));
Assert.Throws(constraint, () => local.Rollback());
Assert.Throws(constraint, () => local.RollbackAsync().Wait());
}
}
/// <summary>
/// Gets cache.
/// </summary>
private ICache<int, int> Cache()
{
var ignite = Ignition.GetIgnite();
return ignite.GetOrCreateCache<int, int>(new CacheConfiguration
{
Name = TestUtils.TestName,
AtomicityMode = CacheAtomicityMode.Transactional
});
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Axiom.MathLib;
using Axiom.Animating;
using Axiom.Collections;
namespace Multiverse.Tools.ModelViewer {
public partial class BoneDisplay : Form {
SkeletonInstance skeleton;
Skeleton helperSkeleton;
string selectedBone = null;
public ModelViewer modelViewer;
public BoneDisplay() {
InitializeComponent();
this.FormClosed += new FormClosedEventHandler(this.BoneDisplay_Close);
}
public BoneDisplay(ModelViewer parent) : this() {
modelViewer = parent;
}
private void BoneDisplay_Load(object sender, EventArgs e) {
}
private void BoneDisplay_Close(object sender, FormClosedEventArgs e) {
if (modelViewer != null)
modelViewer.boneDisplay = null;
}
public void SetSkeleton(SkeletonInstance skel) {
Bone bone = skel.RootBone;
TreeNode node = new TreeNode();
node.Name = bone.Name;
node.Text = bone.Name;
boneTreeView.Nodes.Add(node);
AddChildBones(node, bone);
skeleton = skel;
string skeletonName = skel.MasterSkeleton.Name;
helperSkeleton = SkeletonManager.Instance.Load(skeletonName);
}
private void AddChildBones(TreeNode node, Bone bone) {
foreach (Bone childBone in bone.Children) {
TreeNode childNode = new TreeNode();
childNode.Name = childBone.Name;
childNode.Text = childBone.Name;
node.Nodes.Add(childNode);
AddChildBones(childNode, childBone);
}
}
public void UpdateFields() {
boneNameLabel.Text = selectedBone;
if (skeleton.ContainsBone(boneNameLabel.Text)) {
Bone bone = skeleton.GetBone(boneNameLabel.Text);
Quaternion q = ModelViewer.GetRotation(bone.FullTransform);
boneNameLabel.Text = bone.Name;
bonePosition.Text = bone.FullTransform.Translation.ToString();
boneRotation.Text = q.ToString();
boneRotation2.Text = string.Format("X:{0} Y:{1} Z:{2}", q.PitchInDegrees, q.YawInDegrees, q.RollInDegrees);
q = bone.Orientation;
relPosition.Text = bone.Position.ToString();
relRotation.Text = q.ToString();
relRotation2.Text = string.Format("X:{0} Y:{1} Z:{2}", q.PitchInDegrees, q.YawInDegrees, q.RollInDegrees);
Bone bindBone = skeleton.GetBone(boneNameLabel.Text);
Matrix4 bindBoneFullTransform = bindBone.BindDerivedInverseTransform.Inverse();
q = ModelViewer.GetRotation(bindBoneFullTransform);
bindPosition.Text = bindBoneFullTransform.Translation.ToString();
bindRotation.Text = q.ToString();
bindRotation2.Text = string.Format("X:{0} Y:{1} Z:{2}", q.PitchInDegrees, q.YawInDegrees, q.RollInDegrees);
AnimationState currentAnimation = modelViewer.CurrentAnimation;
if (currentAnimation != null) {
animationName.Text = "Animation: " + currentAnimation.Name;
float currentTime = currentAnimation.Time;
animationTime.Text = "Time: " + currentTime.ToString();
Animation anim = skeleton.GetAnimation(currentAnimation.Name);
NodeAnimationTrack animTrack = anim.NodeTracks[bone.Handle];
KeyFrame keyFrame1, keyFrame2;
ushort dummy;
animTrack.GetKeyFramesAtTime(currentTime, out keyFrame1, out keyFrame2, out dummy);
AnimationStateSet helperAnimSet = new AnimationStateSet();
helperSkeleton.InitAnimationState(helperAnimSet);
AnimationState helperAnimation = helperAnimSet.GetAnimationState(currentAnimation.Name);
helperAnimation.IsEnabled = true;
helperAnimation.Time = keyFrame1.Time;
helperSkeleton.SetAnimationState(helperAnimSet);
Bone helperBone = helperSkeleton.GetBone(bone.Handle);
// currentAnimation.Time;
keyFrame1Time.Text = helperAnimation.Time.ToString();
q = ModelViewer.GetRotation(helperBone.FullTransform);
keyFrame1Position.Text = helperBone.FullTransform.Translation.ToString();
keyFrame1Rotation.Text = q.ToString();
keyFrame1Rotation2.Text = string.Format("X:{0} Y:{1} Z:{2}", q.PitchInDegrees, q.YawInDegrees, q.RollInDegrees);
helperAnimation.Time = keyFrame2.Time;
helperSkeleton.SetAnimationState(helperAnimSet);
keyFrame2Time.Text = helperAnimation.Time.ToString();
q = ModelViewer.GetRotation(helperBone.FullTransform);
keyFrame2Position.Text = helperBone.FullTransform.Translation.ToString();
keyFrame2Rotation.Text = q.ToString();
keyFrame2Rotation2.Text = string.Format("X:{0} Y:{1} Z:{2}", q.PitchInDegrees, q.YawInDegrees, q.RollInDegrees);
#if NOT
keyFrame1Time.Text = keyFrame1.Time.ToString();
q = keyFrame1.Rotation;
keyFrame1Position.Text = helperBone.Translate.ToString();
keyFrame1Rotation.Text = q.ToString();
keyFrame1Rotation2.Text = string.Format("X:{0} Y:{1} Z:{2}", q.PitchInDegrees, q.YawInDegrees, q.RollInDegrees);
keyFrame2Time.Text = keyFrame2.Time.ToString();
q = keyFrame2.Rotation;
keyFrame2Position.Text = keyFrame2.Translate.ToString();
keyFrame2Rotation.Text = q.ToString();
keyFrame2Rotation2.Text = string.Format("X:{0} Y:{1} Z:{2}", q.PitchInDegrees, q.YawInDegrees, q.RollInDegrees);
#endif
} else {
animationName.Text = "No animation selected";
}
bonePosition.Show();
boneRotation.Show();
boneRotation2.Show();
relPosition.Show();
relRotation.Show();
relRotation2.Show();
bindPosition.Show();
bindRotation.Show();
bindRotation2.Show();
if (currentAnimation != null) {
prevKeyframeLabel.Show();
keyFrame1TimeLabel.Show();
keyFrame1PositionLabel.Show();
keyFrame1RotationLabel.Show();
keyFrame1Time.Show();
keyFrame1Position.Show();
keyFrame1Rotation.Show();
keyFrame1Rotation2.Show();
nextKeyframeLabel.Show();
keyFrame2TimeLabel.Show();
keyFrame2PositionLabel.Show();
keyFrame2RotationLabel.Show();
keyFrame2Time.Show();
keyFrame2Position.Show();
keyFrame2Rotation.Show();
keyFrame2Rotation2.Show();
} else {
prevKeyframeLabel.Hide();
keyFrame1TimeLabel.Hide();
keyFrame1PositionLabel.Hide();
keyFrame1RotationLabel.Hide();
keyFrame1Time.Hide();
keyFrame1Position.Hide();
keyFrame1Rotation.Hide();
keyFrame1Rotation2.Hide();
nextKeyframeLabel.Hide();
keyFrame2TimeLabel.Hide();
keyFrame2PositionLabel.Hide();
keyFrame2RotationLabel.Hide();
keyFrame2Time.Hide();
keyFrame2Position.Hide();
keyFrame2Rotation.Hide();
keyFrame2Rotation2.Hide();
}
} else {
boneNameLabel.Text = "Invalid Bone Selected";
bonePosition.Hide();
boneRotation.Hide();
boneRotation2.Hide();
relPosition.Hide();
relRotation.Hide();
relRotation2.Hide();
bindPosition.Hide();
bindRotation.Hide();
bindRotation2.Hide();
prevKeyframeLabel.Hide();
keyFrame1TimeLabel.Hide();
keyFrame1PositionLabel.Hide();
keyFrame1RotationLabel.Hide();
keyFrame1Time.Hide();
keyFrame1Position.Hide();
keyFrame1Rotation.Hide();
keyFrame1Rotation2.Hide();
nextKeyframeLabel.Hide();
keyFrame2TimeLabel.Hide();
keyFrame2PositionLabel.Hide();
keyFrame2RotationLabel.Hide();
keyFrame2Time.Hide();
keyFrame2Position.Hide();
keyFrame2Rotation.Hide();
keyFrame2Rotation2.Hide();
}
}
private void boneTreeView_AfterSelect(object sender, TreeViewEventArgs e) {
selectedBone = e.Node.Text;
UpdateFields();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Magecrawl.Actors;
using Magecrawl.EngineInterfaces;
using Magecrawl.GameEngine.Magic;
using Magecrawl.GameEngine.Physics;
using Magecrawl.Interfaces;
using Magecrawl.Items;
using Magecrawl.Maps;
using Magecrawl.Maps.MapObjects;
using Magecrawl.StatusEffects.Interfaces;
using Magecrawl.Utilities;
namespace Magecrawl.GameEngine
{
internal sealed class PhysicsEngine
{
private CoreTimingEngine m_timingEngine;
private FOVManager m_fovManager;
private CombatEngine m_combatEngine;
private MagicEffectsEngine m_magicEffects;
// Fov FilterNotMovablePointsFromList
private Dictionary<Point, bool> m_movableHash;
// Cared and fed by CoreGameEngine, local copy for convenience
private Player m_player;
private Map m_map;
public PhysicsEngine(Player player, Map map)
{
m_player = player;
m_map = map;
m_timingEngine = new CoreTimingEngine();
m_fovManager = new FOVManager(this, map);
m_combatEngine = new CombatEngine(this, player, map);
m_movableHash = new Dictionary<Point, bool>(PointEqualityComparer.Instance);
m_magicEffects = new MagicEffectsEngine(this, m_combatEngine);
UpdatePlayerVisitedStatus();
}
internal CombatEngine CombatEngine
{
get { return m_combatEngine; }
}
internal FOVManager FOVManager
{
get
{
return m_fovManager;
}
}
internal void NewMapPlayerInfo(Player player, Map map)
{
m_player = player;
m_map = map;
m_combatEngine.NewMapPlayerInfo(player, map);
// We have a new map, recalc LOS with a new map
m_fovManager.UpdateNewMap(this, m_map);
UpdatePlayerVisitedStatus();
}
// This needs to be really _fast_. We're going to stick the not moveable points in a has table,
// then compare each pointList to the terrian and if still good see if in hash table
// Please keep in sync with Point version below
public void FilterNotTargetablePointsFromList(List<EffectivePoint> pointList, Point characterPosition, int visionRange, bool needsToBeVisible)
{
if (pointList == null)
return;
m_fovManager.CalculateForMultipleCalls(m_map, characterPosition, visionRange);
m_movableHash.Clear();
foreach (MapObject obj in m_map.MapObjects)
{
if (obj.IsSolid)
m_movableHash[obj.Position] = true;
}
// Remove it if it's not on map, or is wall, or same square as something solid from above, is it's not visible.
pointList.RemoveAll(point =>
!m_map.IsPointOnMap(point.Position) ||
m_map.GetTerrainAt(point.Position) == TerrainType.Wall ||
m_movableHash.ContainsKey(point.Position) ||
(needsToBeVisible && !m_fovManager.Visible(point.Position)));
}
// This needs to be really _fast_, and so we're going to violate a rule of duplication.
// Please keep in sync with EffectPoint version above
public void FilterNotTargetablePointsFromList(List<Point> pointList, Point characterPosition, int visionRange, bool needsToBeVisible)
{
if (pointList == null)
return;
m_fovManager.CalculateForMultipleCalls(m_map, characterPosition, visionRange);
m_movableHash.Clear();
foreach (MapObject obj in m_map.MapObjects)
{
if (obj.IsSolid)
m_movableHash[obj.Position] = true;
}
// Remove it if it's not on map, or is wall, or same square as something solid from above, is it's not visible.
pointList.RemoveAll(point =>
!m_map.IsPointOnMap(point) ||
m_map.GetTerrainAt(point) == TerrainType.Wall ||
m_movableHash.ContainsKey(point) ||
(needsToBeVisible && !m_fovManager.Visible(point)));
}
// This is a slow operation. It should not be called multiple times in a row!
// Call CalculateMoveablePointGrid instead~!
public bool IsMovablePointSingleShot(Map map, Point p)
{
// If it's not a floor, it's not movable
if (map.GetTerrainAt(p) != TerrainType.Floor)
return false;
// If there's a map object there that is solid, it's not movable
if (map.MapObjects.SingleOrDefault(m => m.Position == p && m.IsSolid) != null)
return false;
// If there's a monster there, it's not movable
if (map.Monsters.SingleOrDefault(m => m.Position == p) != null)
return false;
// If the player is there, it's not movable
if (m_player.Position == p)
return false;
return true;
}
public TileVisibility[,] CalculateTileVisibility()
{
TileVisibility[,] visibilityArray = new TileVisibility[m_map.Width, m_map.Height];
m_fovManager.CalculateForMultipleCalls(m_map, m_player.Position, m_player.Vision);
for (int i = 0; i < m_map.Width; ++i)
{
for (int j = 0; j < m_map.Height; ++j)
{
Point p = new Point(i, j);
if (m_fovManager.Visible(p))
{
visibilityArray[i, j] = TileVisibility.Visible;
}
else
{
if (m_map.IsVisitedAt(p))
visibilityArray[i, j] = TileVisibility.Visited;
else
visibilityArray[i, j] = TileVisibility.Unvisited;
}
}
}
return visibilityArray;
}
internal bool Move(Character c, Direction direction)
{
bool didAnything = false;
Point newPosition = PointDirectionUtils.ConvertDirectionToDestinationPoint(c.Position, direction);
if (m_map.IsPointOnMap(newPosition) && IsMovablePointSingleShot(m_map, newPosition))
{
c.Position = newPosition;
m_timingEngine.ActorMadeMove(c);
didAnything = true;
}
return didAnything;
}
internal bool WarpToPosition(Character c, Point p)
{
c.Position = p;
return true;
}
internal List<Point> TargettedDrawablePoints(object targettingObject, Point target)
{
Spell asSpell = targettingObject as Spell;
if (asSpell != null)
return m_magicEffects.TargettedDrawablePoints(asSpell.Targeting, m_player.SpellStrength(asSpell.School), target);
Item asItem = targettingObject as Item;
if (asItem != null)
return m_magicEffects.TargettedDrawablePoints(asItem.GetAttribute("InvokeSpellEffect"), int.Parse(asItem.GetAttribute("CasterLevel"), CultureInfo.InvariantCulture), target);
return null;
}
public bool IsRangedPathBetweenPoints(Point x, Point y)
{
return GenerateRangedAttackListOfPoints(m_map, x, y) != null;
}
internal List<Point> GenerateRangedAttackListOfPoints(Map map, Point attcker, Point target)
{
return RangedAttackPathfinder.RangedListOfPoints(map, attcker, target, false, false);
}
internal List<Point> GenerateBlastListOfPoints(Map map, Point caster, Point target, bool bounceOffWalls)
{
return RangedAttackPathfinder.RangedListOfPoints(map, caster, target, true, bounceOffWalls);
}
// So if we're previewing the position of a blast, and we can't see the wall we're going to bounce
// off of, don't show the bounce at all...
internal List<Point> GenerateBlastListOfPointsShowBounceIfSeeWall(Map map, ICharacter caster, Point target)
{
Point wallPosition = RangedAttackPathfinder.GetWallHitByBlast(map, caster.Position, target);
if (m_fovManager.VisibleSingleShot(map, caster.Position, caster.Vision, wallPosition))
return RangedAttackPathfinder.RangedListOfPoints(map, caster.Position, target, true, true);
else
return RangedAttackPathfinder.RangedListOfPoints(map, caster.Position, target, true, false);
}
private void UpdatePlayerVisitedStatus()
{
m_fovManager.CalculateForMultipleCalls(m_map, m_player.Position, m_player.Vision);
// Only need Vision really, but to catch off by one errors and such, make it bigger
// We're doing this instead of all cells for performance anyway
int minX = m_player.Position.X - (m_player.Vision * 2);
int minY = m_player.Position.Y - (m_player.Vision * 2);
int maxX = m_player.Position.X + (m_player.Vision * 2);
int maxY = m_player.Position.Y + (m_player.Vision * 2);
for (int i = minX; i < maxX; ++i)
{
for (int j = minY; j < maxY; ++j)
{
Point p = new Point(i, j);
if (m_map.IsPointOnMap(p) && m_fovManager.Visible(p))
m_map.SetVisitedAt(p, true);
}
}
}
public bool PlayerGetItem()
{
Pair<Item, Point> itemToPickup = m_map.InternalItems.Where(i => i.Second == m_player.Position).FirstOrDefault();
if (itemToPickup != null)
{
m_map.RemoveItem(itemToPickup);
m_player.TakeItem(itemToPickup.First);
m_timingEngine.ActorDidAction(m_player);
CoreGameEngine.Instance.SendTextOutput(string.Format("Picked up a {0}.", itemToPickup.First.DisplayName));
return true;
}
return false;
}
public bool PlayerGetItem(IItem item)
{
List<Pair<Item, Point>> items = m_map.InternalItems.Where(i => i.Second == m_player.Position).ToList();
Pair<Item, Point> itemPair = items.Where(i => i.First == item).FirstOrDefault();
if (itemPair != null)
{
m_map.RemoveItem(itemPair);
m_player.TakeItem(itemPair.First);
m_timingEngine.ActorDidAction(m_player);
CoreGameEngine.Instance.SendTextOutput(string.Format("Picked up a {0}.", itemPair.First.DisplayName));
return true;
}
return false;
}
public bool PlayerDropItem(Item item)
{
if (m_player.Items.Contains(item))
{
m_map.AddItem(new Pair<Item, Point>(item, m_player.Position));
m_player.RemoveItem(item);
return true;
}
return false;
}
public bool DangerPlayerInLOS()
{
FOVManager.CalculateForMultipleCalls(m_map, m_player.Position, m_player.Vision);
foreach (Monster m in m_map.Monsters)
{
if (FOVManager.Visible(m.Position))
return true;
}
return false;
}
public bool CurrentOrRecentDanger()
{
const int TurnsMonsterOutOfLOSToBeSafe = 8;
bool dangerInLOS = DangerPlayerInLOS();
if (dangerInLOS)
{
m_player.LastTurnSeenAMonster = CoreGameEngine.Instance.TurnCount;
return true;
}
// This is wrong - BUG 225
if (m_player.LastTurnSeenAMonster + TurnsMonsterOutOfLOSToBeSafe > CoreGameEngine.Instance.TurnCount)
return true;
if (m_player.Effects.Any(x => !x.IsPositiveEffect))
return true;
return false;
}
public bool UseItemWithEffect(Item item, Point targetedPoint)
{
if (m_player.Items.Contains(item))
{
bool itemUsedSucessfully = m_magicEffects.UseItemWithEffect(m_player, item, targetedPoint);
if (itemUsedSucessfully)
{
int currentCharges = int.Parse(item.GetAttribute("Charges"), CultureInfo.InvariantCulture) - 1;
if (currentCharges <= 0)
{
m_player.RemoveItem((Item)item);
if (item.GetAttribute("Type") == "Wand")
CoreGameEngine.Instance.SendTextOutput(string.Format("The {0} disintegrates as its last bit of magic is wrested from it.", item.DisplayName));
}
else
{
item.SetExistentAttribute("Charges", currentCharges.ToString());
}
}
return itemUsedSucessfully;
}
return false;
}
public bool Operate(Character characterOperating, Point pointToOperateAt)
{
// We can't operate if anyone is at that location.
if (m_combatEngine.FindTargetAtPosition(pointToOperateAt) != null)
return false;
OperableMapObject operateObj = m_map.MapObjects.OfType<OperableMapObject>().SingleOrDefault(x => x.Position == pointToOperateAt);
if (operateObj != null)
{
operateObj.Operate(characterOperating);
m_timingEngine.ActorDidAction(characterOperating);
return true;
}
return false;
}
internal bool Wait(Character c)
{
m_timingEngine.ActorDidAction(c);
return true;
}
internal bool Attack(Character attacker, Point target)
{
bool didAnything = m_combatEngine.Attack(attacker, target);
if (didAnything)
m_timingEngine.ActorDidWeaponAttack(attacker);
return didAnything;
}
internal bool CastSpell(Player caster, Spell spell, Point target)
{
bool didAnything = m_magicEffects.CastSpell(caster, spell, target);
if (didAnything)
m_timingEngine.ActorDidAction(caster);
return didAnything;
}
internal bool ReloadWeapon(Character character)
{
if (!character.CurrentWeapon.IsRanged)
throw new InvalidOperationException("ReloadWeapon on non-ranged weapon?");
((Weapon)character.CurrentWeapon).LoadWeapon();
m_timingEngine.ActorDidMinorAction(character);
return true;
}
internal bool PlayerMoveUpStairs(Player player, Map map)
{
Stairs s = map.MapObjects.OfType<Stairs>().Where(x => x.Type == MapObjectType.StairsUp && x.Position == player.Position).SingleOrDefault();
if (s != null)
{
// The position must come first, as changing levels checks FOV
m_player.Position = StairsMapping.Instance.GetMapping(s.UniqueID);
CoreGameEngine.Instance.CurrentLevel--;
m_timingEngine.ActorMadeMove(m_player);
return true;
}
return false;
}
internal bool PlayerMoveDownStairs(Player player, Map map)
{
Stairs s = map.MapObjects.OfType<Stairs>().Where(x => x.Type == MapObjectType.StairsDown && x.Position == player.Position).SingleOrDefault();
if (s != null)
{
if (CoreGameEngine.Instance.CurrentLevel == CoreGameEngine.Instance.NumberOfLevels - 1)
throw new InvalidOperationException("Win dialog should have come up instead.");
// The position must come first, as changing levels checks FOV
m_player.Position = StairsMapping.Instance.GetMapping(s.UniqueID);
CoreGameEngine.Instance.CurrentLevel++;
m_timingEngine.ActorMadeMove(m_player);
return true;
}
return false;
}
// Called by PublicGameEngine after any call that could pass time.
internal void BeforePlayerAction(CoreGameEngine engine)
{
UpdatePlayerVisitedStatus();
}
// Called by PublicGameEngine after any call to CoreGameEngine which passes time.
internal void AfterPlayerAction(CoreGameEngine engine)
{
UpdatePlayerVisitedStatus();
// Regenerate health mana if out of combat for a bit.
const int NumberOfRoundsUntilHealthFull = 20;
if (!CurrentOrRecentDanger())
{
// Always heal at least 1 point if we're not topped off. Thanks integer math!
int hpToHeal = m_player.MaxHP / NumberOfRoundsUntilHealthFull;
if (m_player.CurrentHP < m_player.MaxHP && hpToHeal <= 0)
hpToHeal = 1;
int mpToHeal = m_player.MaxMP / NumberOfRoundsUntilHealthFull;
if (m_player.CurrentMP < m_player.MaxMP && mpToHeal <= 0)
mpToHeal = 1;
bool magicalHeal = m_player.HasAttribute("Regeneration");
m_player.Heal(hpToHeal, magicalHeal);
m_player.GainMP(mpToHeal);
}
// Until the player gets a turn
while (true)
{
Character nextCharacter = m_timingEngine.GetNextActor(m_player, m_map);
if (nextCharacter is Player)
return;
Monster monster = nextCharacter as Monster;
monster.Action(CoreGameEngineInstance.Instance);
}
}
internal ILongTermStatusEffect GetLongTermEffectSpellWouldProduce(string effectName)
{
return m_magicEffects.GetLongTermEffectSpellWouldProduce(effectName);
}
internal bool HandleItemAction(IItem item, string option, object argument)
{
// Some actions take longer than 1 turn, so spend the extra time here
switch (option)
{
case "Equip":
case "Equip as Secondary":
case "Unequip":
case "Unequip as Secondary":
{
m_timingEngine.ActorDidAction(m_player);
m_timingEngine.ActorDidAction(m_player);
m_timingEngine.ActorDidAction(m_player);
break;
}
}
switch (option)
{
case "Drop":
{
return PlayerDropItem(item as Item);
}
case "Equip":
{
// This probally should live in the player code
m_player.RemoveItem(item as Item);
Item oldWeapon = m_player.Equip(item) as Item;
if (oldWeapon != null)
m_player.TakeItem(oldWeapon);
return true;
}
case "Equip as Secondary":
{
// This probally should live in the player code
m_player.RemoveItem(item as Item);
Item oldWeapon = m_player.EquipSecondaryWeapon(item as IWeapon) as Item;
if (oldWeapon != null)
m_player.TakeItem(oldWeapon);
return true;
}
case "Unequip":
{
Item oldWeapon = m_player.Unequip(item) as Item;
if (oldWeapon != null)
m_player.TakeItem(oldWeapon);
return true;
}
case "Unequip as Secondary":
{
Item oldWeapon = m_player.UnequipSecondaryWeapon() as Item;
if (oldWeapon != null)
m_player.TakeItem(oldWeapon);
return true;
}
case "Drink":
case "Read":
case "Zap":
{
return UseItemWithEffect((Item)item, (Point)argument);
}
default:
{
throw new NotImplementedException();
}
}
}
}
}
| |
//! \file ArcAi5Win.cs
//! \date Mon Jun 29 04:41:29 2015
//! \brief Ai5Win engine resource archive.
//
// Copyright (C) 2015 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using GameRes.Compression;
using GameRes.Utility;
namespace GameRes.Formats.Elf
{
[Serializable]
public class ArcIndexScheme
{
public int NameLength;
public byte NameKey;
public uint SizeKey;
public uint OffsetKey;
}
[Serializable]
public class Ai5Scheme : ResourceScheme
{
public Dictionary<string, ArcIndexScheme> KnownSchemes;
}
[Export(typeof(ArchiveFormat))]
public class ArcAI5Opener : ArchiveFormat
{
public override string Tag { get { return "ARC/AI5WIN"; } }
public override string Description { get { return "AI5WIN engine resource archive"; } }
public override uint Signature { get { return 0; } }
public override bool IsHierarchic { get { return false; } }
public override bool CanCreate { get { return false; } }
public static Dictionary<string, ArcIndexScheme> KnownSchemes = new Dictionary<string, ArcIndexScheme>();
public ArcAI5Opener ()
{
Extensions = new string[] { "arc" };
}
public override ResourceScheme Scheme
{
get { return new Ai5Scheme { KnownSchemes = KnownSchemes }; }
set { KnownSchemes = ((Ai5Scheme)value).KnownSchemes; }
}
public override ArcFile TryOpen (ArcView file)
{
if (0 == KnownSchemes.Count)
return null;
int count = file.View.ReadInt32 (0);
if (!IsSaneCount (count))
return null;
var reader = new IndexReader (file, count);
foreach (var scheme in KnownSchemes.Values)
{
try
{
var dir = reader.Read (scheme);
if (dir != null)
return new ArcFile (file, this, dir);
}
catch { /* ignore parse errors */ }
}
return null;
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
var input = arc.File.CreateStream (entry.Offset, entry.Size);
if (entry.Name.EndsWith (".mes", StringComparison.InvariantCultureIgnoreCase)
|| entry.Name.EndsWith (".lib", StringComparison.InvariantCultureIgnoreCase))
return new LzssStream (input);
return input;
}
internal class IndexReader
{
ArcView m_file;
int m_count;
List<Entry> m_dir;
byte[] m_name_buf = new byte[0x100];
public IndexReader (ArcView file, int count)
{
m_file = file;
m_count = count;
m_dir = new List<Entry> (m_count);
}
public List<Entry> Read (ArcIndexScheme scheme)
{
if (scheme.NameLength > m_name_buf.Length)
m_name_buf = new byte[scheme.NameLength];
m_dir.Clear();
int index_offset = 4;
uint index_size = (uint)(m_count * (scheme.NameLength + 8));
if (index_size > m_file.View.Reserve (index_offset, index_size))
return null;
for (int i = 0; i < m_count; ++i)
{
m_file.View.Read (index_offset, m_name_buf, 0, (uint)scheme.NameLength);
int n;
for (n = 0; n < m_name_buf.Length; ++n)
{
m_name_buf[n] ^= scheme.NameKey;
if (0 == m_name_buf[n])
break;
if (m_name_buf[n] < 0x20)
return null;
}
if (0 == n)
return null;
string name = Encodings.cp932.GetString (m_name_buf, 0, n);
index_offset += scheme.NameLength;
var entry = FormatCatalog.Instance.Create<Entry> (name);
entry.Size = m_file.View.ReadUInt32 (index_offset) ^ scheme.SizeKey;
entry.Offset = m_file.View.ReadUInt32 (index_offset+4) ^ scheme.OffsetKey;
if (entry.Offset < index_size+4 || !entry.CheckPlacement (m_file.MaxOffset))
return null;
m_dir.Add (entry);
index_offset += 8;
}
return m_dir;
}
}
/*
internal class IndexReader
{
ArcView m_file;
int m_count;
byte[] m_first = new byte[0x108];
public const int MinNameLength = 0x10;
public const int MaxNameLength = 0x100;
public IndexReader (ArcView file)
{
m_file = file;
m_count = m_file.View.ReadInt32 (0);
m_file.View.Read (4, m_first, 0, m_first.Length);
}
ArcIndexScheme m_scheme = new ArcIndexScheme();
public ArcIndexScheme Parse ()
{
if (m_count <= 0 || m_count > 0xfffff)
return null;
uint supposed_first_offset = (uint)(m_count * (name_length + 8));
uint first_size = LittleEndian.ToUInt32 (first_entry, name_length);
uint first_offset = LittleEndian.ToUInt32 (first_entry, name_length+4);
uint supposed_offset_key = first_offset ^ supposed_first_offset;
int last_index_offset = 4 + (m_count - 1) * (name_length + 8);
uint last_size = m_file.View.ReadUInt32 (last_index_offset + name_length);
uint last_offset = m_file.View.ReadUInt32 (last_index_offset + name_length + 4);
last_offset ^= supposed_offset_key;
}
bool ParseFirstEntry (int name_length)
{
int index_offset = 4;
}
public byte NameKey { get; private set; }
int GuessNameLength (int initial)
{
int name_pos = initial;
byte sym;
do
{
do
{
sym = first_entry[name_pos++];
}
while (name_pos < MaxNameLength && sym != first_entry[name_pos]);
if (MaxNameLength == name_pos)
return 0;
while (name_pos < MaxNameLength && sym == first_entry[name_pos])
{
++name_pos;
}
if (MaxNameLength == name_pos && sym == first_entry[name_pos] && sym == first_entry[name_pos+1])
return 0;
}
while (name_pos < MinNameLength || 0 != (name_pos & 1));
NameKey = sym;
return name_pos;
}
}
*/
}
}
| |
/************************************************************************
* Copyright (c) 2006-2008, Jason Whitehorn (jason.whitehorn@gmail.com)
* All rights reserved.
*
* Source code and binaries distributed under the terms of the included
* license, see license.txt for details.
************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Web;
using System.Web.Hosting;
using System.IO;
namespace aspNETserve.Core {
public sealed class AspNetWorker : HttpWorkerRequest, IAspNetWorker {
public AspNetWorker(IAspNetRuntime aspNetWorker, string virtualDir, string physicalDir) {
_physicalDir = physicalDir;
_virtualDir = virtualDir;
_aspNetWorker = aspNetWorker;
_serverVariables = new Dictionary<string, string>();
_appPoolId = AppDomain.CurrentDomain.Id.ToString();
}
public AspNetWorker(IAspNetRuntime aspNetWorker, string virtualDir, string physicalDir, IDictionary<string, string> serverVariables) : this(aspNetWorker, virtualDir, physicalDir) {
_serverVariables = serverVariables;
}
public void ProcessTransaction(ITransaction transaction) {
Trace.TraceInformation("Entering AspNetWorker.ProcessTransaction");
try {
ParseRequest(transaction.Request);
string page = _filePath;
if (IsRestricted(page)) {
throw new NotImplementedException("not implemented yet.");
//TODO: Find a way to implement the below line
//return Response.Error403Forbidden;
}
_request = transaction.Request;
_response = transaction.Response;
_aspNetWorker.ProcessRequest(this);
if (_callback != null)
_callback(this, _callbackPayload);
}finally {
Trace.TraceInformation("Leaving AspNetWorker.ProcessTransaction");
}
}
public IDictionary<string, string> ServerVariables {
get { return _serverVariables; }
set { _serverVariables = value; }
}
#region HttpWorkerRequest methods
public override string GetAppPath() {
return _virtualDir;
}
public override string GetAppPathTranslated() {
return _physicalDir;
}
public override string GetAppPoolID() {
return _appPoolId;
}
public override long GetBytesRead() {
return _request.PostData.Length;
}
public override long GetConnectionID() {
return 0; //this is suppose to always return 0.
}
public override string GetFilePath() {
return _virtualFilePath;
}
public override string GetFilePathTranslated() {
string result = _request.RawUrl;
if (result.Contains("?"))
result = result.Remove(result.IndexOf('?'));
if (result.Contains("#"))
result = result.Remove(result.IndexOf('#'));
result = MapPath(result);
return result;
}
public override string GetHttpVerbName() {
return _request.HttpMethod;
}
public override string GetHttpVersion() {
return _request.HttpVersion;
}
public override string GetKnownRequestHeader(int index) {
return _request.GetKnownRequestHeader(index);
}
public override string GetLocalAddress() {
return _request.LocalEndPoint.Address.ToString();
}
public override int GetLocalPort() {
return _request.LocalEndPoint.Port;
}
public override string GetPathInfo() {
return _pathInfo;
}
public override byte[] GetPreloadedEntityBody() {
return _request.PostData;
}
public override string GetProtocol() {
return IsSecure() ? "HTTPS" : "HTTP";
}
public override bool HeadersSent() {
return _response.HeadersSent;
}
public override void FlushResponse(bool finalFlush) {
_response.Flush();
}
public override string GetQueryString() {
return GetQueryString(_request.RawUrl);
}
public override byte[] GetQueryStringRawBytes() {
return Encoding.ASCII.GetBytes(GetQueryString());
}
public override string GetRawUrl() {
return _request.RawUrl;
}
public override string GetRemoteAddress() {
return _request.RemoteEndPoint.Address.ToString();
}
public override string GetRemoteName() {
string result = _request.RemoteEndPoint.Address.ToString();
//if (result == "127.0.0.1")
// result = "localhost";
return result;
}
public override int GetRemotePort() {
return _request.RemoteEndPoint.Port;
}
public override int GetRequestReason() {
return HttpWorkerRequest.ReasonDefault;
}
public override string GetServerName() {
string result = _request.LocalEndPoint.Address.ToString();
if (result == "127.0.0.1")
result = "localhost";
return result;
}
public override string GetServerVariable(string name) {
if (_serverVariables.ContainsKey(name))
return _serverVariables[name];
return "";
}
public override Guid RequestTraceIdentifier {
get {
return _request.RequestId;
}
}
public override string GetUnknownRequestHeader(string name) {
return _request.GetUnknownRequestHeader(name);
}
public override string GetUriPath() {
return _virtualFilePath;
}
public override long GetUrlContextID() {
return 0; //this is suppose to always return 0.
}
public override IntPtr GetUserToken() {
/*
*
*/
//System.Security.Principal.WindowsIdentity f = System.Security.Principal.WindowsIdentity.GetCurrent();
//return f.Token;
return IntPtr.Zero;
}
public override bool IsClientConnected() {
return true; //<<HACK
}
public override bool IsSecure() {
return _request.IsSecure && _response.IsSecure;
}
public override string MachineConfigPath {
get { return string.Format("{0}CONFIG\\machine.config", HttpRuntime.AspInstallDirectory); }
}
public override string MachineInstallDirectory {
get { return HttpRuntime.AspInstallDirectory; }
}
public override string MapPath(string path) {
string result = _physicalDir + path.Remove(0, _virtualDir.Length);
result = result.Replace("/", "\\");
if (result.EndsWith("\\") && !result.EndsWith(":\\\\"))
result = result.Substring(0, result.Length - 1);
result = result.Replace("\\\\", "\\");
return result;
}
public override string RootWebConfigPath {
get { return string.Format("{0}CONFIG\\web.config", HttpRuntime.AspInstallDirectory); }
}
public override void SendCalculatedContentLength(int contentLength) {
SendCalculatedContentLength((long)contentLength);
}
public override void SendCalculatedContentLength(long contentLength) {
_response.SendKnownResponseHeader((int)HttpWorkerRequest.HeaderContentLength, contentLength.ToString());
}
public override void SetEndOfSendNotification(HttpWorkerRequest.EndOfSendNotification callback, object extraData) {
_callback = callback;
_callbackPayload = extraData;
}
public override void SendKnownResponseHeader(int index, string value) {
_response.SendKnownResponseHeader(index, value);
}
public override void SendResponseFromMemory(byte[] data, int length) {
int curLength = 0;
if (_response.RawData != null)
curLength += _response.RawData.Length;
byte[] buffer = new byte[length + curLength];
if (_response.RawData != null)
Buffer.BlockCopy(_response.RawData, 0, buffer, 0, _response.RawData.Length);
Buffer.BlockCopy(data, 0, buffer, curLength, length);
_response.RawData = buffer;
}
public override void SendResponseFromMemory(IntPtr data, int length) {
byte[] buffer = new byte[length];
for (int i = 0; i < length; i++) {
buffer[i] = System.Runtime.InteropServices.Marshal.ReadByte(data, i);
}
SendResponseFromMemory(buffer, length);
}
public override void SendResponseFromFile(string filename, long offset, long length) {
/*
* Opens a file given its filename, and writes the entire contents out
* to the client.
*/
using (FileStream file = File.OpenRead(filename)) {
byte[] buffer = new byte[file.Length];
file.Read(buffer, 0, (int)file.Length);
SendResponseFromMemory(buffer, buffer.Length);
file.Close();
}
}
public override void SendStatus(int statusCode, string statusDescription) {
_response.StatusCode = statusCode;
_response.StatusDescription = statusDescription;
}
public override void SendUnknownResponseHeader(string name, string value) {
_response.SendUnknownResponseHeader(name, value);
}
#region I DONT KNOW
public override void CloseConnection() {
//???
}
public override void EndOfRequest() {
//???
}
public override byte[] GetClientCertificate() {
return base.GetClientCertificate();
}
public override byte[] GetClientCertificateBinaryIssuer() {
return base.GetClientCertificateBinaryIssuer();
}
public override int GetClientCertificateEncoding() {
return base.GetClientCertificateEncoding();
}
public override byte[] GetClientCertificatePublicKey() {
return base.GetClientCertificatePublicKey();
}
public override DateTime GetClientCertificateValidFrom() {
return base.GetClientCertificateValidFrom();
}
public override DateTime GetClientCertificateValidUntil() {
return base.GetClientCertificateValidUntil();
}
public override int GetPreloadedEntityBody(byte[] buffer, int offset) {
return base.GetPreloadedEntityBody(buffer, offset);
}
public override int GetPreloadedEntityBodyLength() {
return base.GetPreloadedEntityBodyLength();
}
public override int GetTotalEntityBodyLength() {
return base.GetTotalEntityBodyLength();
}
public override string[][] GetUnknownRequestHeaders() {
return base.GetUnknownRequestHeaders();
}
public override IntPtr GetVirtualPathToken() {
return base.GetVirtualPathToken();
}
public override bool IsEntireEntityBodyIsPreloaded() {
return base.IsEntireEntityBodyIsPreloaded();
}
public override int ReadEntityBody(byte[] buffer, int offset, int size) {
return base.ReadEntityBody(buffer, offset, size);
}
public override int ReadEntityBody(byte[] buffer, int size) {
return base.ReadEntityBody(buffer, size);
}
public override void SendResponseFromFile(IntPtr handle, long offset, long length) {
throw new Exception("The method or operation is not implemented.");
}
#endregion
#endregion
//-------------------------
private bool IsRestricted(string fileName) {
bool restricted = false;
foreach (string dir in _secureDirs) {
if (fileName.StartsWith(dir)) {
restricted = true;
break;
}
}
return restricted;
}
private string GetQueryString(string rawUrl) {
string result = "";
if (rawUrl.Contains("?")) {
result = rawUrl.Split(new char[] { '?' })[1];
}
return result;
}
private void ParseRequest(IRequest req){
string rawUrl = req.RawUrl;
int idxQuery = rawUrl.IndexOf('?');
if (idxQuery != -1)
_virtualFilePath = rawUrl.Substring(0, rawUrl.IndexOf('?'));
else
_virtualFilePath = rawUrl;
int idxLastSlash = _virtualFilePath.LastIndexOf('/');
int idxFirstDot = _virtualFilePath.IndexOf('.'); //this will not get the dots in the www.domain.com, because that is not part of the rawUrl
if ((idxFirstDot != -1 && idxLastSlash != -1) && (idxFirstDot < idxLastSlash)) {
//if the url has a dot (.) and a slash (/), and the dot occurs before the last slash
//i.e., /site/something.aspx/foo
int idxEndOfPreTail = _virtualFilePath.IndexOf('/', idxFirstDot); //the first slash following the first dot.
_pathInfo = _virtualFilePath.Substring(idxEndOfPreTail); //save the tail
_virtualFilePath = _virtualFilePath.Substring(0, idxEndOfPreTail);
} else {
_pathInfo = string.Empty;
}
if (_virtualFilePath[_virtualFilePath.Length-1] == '/') {
foreach (string defaultPage in _defaultPages) {
string path = MapPath(_virtualFilePath + defaultPage);
if (File.Exists(path)) {
_virtualFilePath += defaultPage;
break;
}
}
}
if (_virtualDir.Length > 1) {
_filePath = _virtualFilePath.Substring(_virtualDir.Length);
if (_filePath.StartsWith("/"))
_filePath = _filePath.Substring(1);
} else {
_filePath = _virtualFilePath;
}
}
private string _virtualDir;
private string _physicalDir;
private static string[] _secureDirs = new string[] {
"/bin/",
"/app_browsers/",
"/app_code/",
"/app_data/",
"/app_localresources/",
"/app_globalresources/",
"/app_webreferences/"
};
private string[] _defaultPages = { "default.aspx", "index.html", "index.htm" };
private IResponse _response;
private IRequest _request;
private HttpWorkerRequest.EndOfSendNotification _callback;
private object _callbackPayload;
private IDictionary<string, string> _serverVariables;
private string _virtualFilePath;
private string _filePath;
private string _pathInfo;
private IAspNetRuntime _aspNetWorker;
private readonly string _appPoolId;
}
}
| |
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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 MassTransit.Transports.InMemory
{
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Logging;
using Pipeline;
using Util;
/// <summary>
/// Support in-memory message queue that is not durable, but supports parallel delivery of messages
/// based on TPL usage.
/// </summary>
public class InMemoryTransport :
IReceiveTransport,
ISendTransport,
IDisposable
{
static readonly ILog _log = Logger.Get<InMemoryTransport>();
readonly ReceiveEndpointObservable _endpointObservable;
readonly Uri _inputAddress;
readonly ITaskParticipant _participant;
readonly ReceiveObservable _receiveObservable;
readonly QueuedTaskScheduler _scheduler;
readonly SendObservable _sendObservable;
readonly TaskSupervisor _supervisor;
int _currentPendingDeliveryCount;
long _deliveryCount;
int _maxPendingDeliveryCount;
IPipe<ReceiveContext> _receivePipe;
public InMemoryTransport(Uri inputAddress, int concurrencyLimit)
{
_inputAddress = inputAddress;
_sendObservable = new SendObservable();
_receiveObservable = new ReceiveObservable();
_endpointObservable = new ReceiveEndpointObservable();
_supervisor = new TaskSupervisor();
_participant = _supervisor.CreateParticipant();
_scheduler = new QueuedTaskScheduler(TaskScheduler.Default, concurrencyLimit);
}
public void Dispose()
{
_participant.SetComplete();
TaskUtil.Await(() => _supervisor.Stop("Disposed"));
TaskUtil.Await(() => _supervisor.Completed);
_scheduler.Dispose();
}
public void Probe(ProbeContext context)
{
var scope = context.CreateScope("transport");
scope.Set(new
{
Address = _inputAddress
});
}
ReceiveTransportHandle IReceiveTransport.Start(IPipe<ReceiveContext> receivePipe)
{
try
{
_receivePipe = receivePipe;
TaskUtil.Await(() => _endpointObservable.Ready(new Ready(_inputAddress)));
_participant.SetReady();
return new Handle(_supervisor, _participant, this);
}
catch (Exception exception)
{
_participant.SetNotReady(exception);
throw;
}
}
public ConnectHandle ConnectReceiveObserver(IReceiveObserver observer)
{
return _receiveObservable.Connect(observer);
}
public ConnectHandle ConnectReceiveEndpointObserver(IReceiveEndpointObserver observer)
{
return _endpointObservable.Connect(observer);
}
async Task ISendTransport.Send<T>(T message, IPipe<SendContext<T>> pipe, CancellationToken cancelSend)
{
var context = new InMemorySendContext<T>(message, cancelSend);
try
{
await pipe.Send(context).ConfigureAwait(false);
var messageId = context.MessageId ?? NewId.NextGuid();
await _sendObservable.PreSend(context).ConfigureAwait(false);
var transportMessage = new InMemoryTransportMessage(messageId, context.Body, context.ContentType.MediaType, TypeMetadataCache<T>.ShortName);
#pragma warning disable 4014
Task.Factory.StartNew(() => DispatchMessage(transportMessage), _supervisor.StopToken, TaskCreationOptions.HideScheduler, _scheduler);
#pragma warning restore 4014
context.DestinationAddress.LogSent(context.MessageId?.ToString("N") ?? "", TypeMetadataCache<T>.ShortName);
await _sendObservable.PostSend(context).ConfigureAwait(false);
}
catch (Exception ex)
{
_log.Error($"SEND FAULT: {_inputAddress} {context.MessageId} {TypeMetadataCache<T>.ShortName}", ex);
await _sendObservable.SendFault(context, ex).ConfigureAwait(false);
throw;
}
}
async Task ISendTransport.Move(ReceiveContext context, IPipe<SendContext> pipe)
{
var messageId = GetMessageId(context);
byte[] body;
using (var bodyStream = context.GetBody())
{
body = await GetMessageBody(bodyStream).ConfigureAwait(false);
}
var messageType = "Unknown";
InMemoryTransportMessage receivedMessage;
if (context.TryGetPayload(out receivedMessage))
messageType = receivedMessage.MessageType;
var transportMessage = new InMemoryTransportMessage(messageId, body, context.ContentType.MediaType, messageType);
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
Task.Factory.StartNew(() => DispatchMessage(transportMessage), _supervisor.StopToken, TaskCreationOptions.HideScheduler, _scheduler);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
}
public ConnectHandle ConnectSendObserver(ISendObserver observer)
{
return _sendObservable.Connect(observer);
}
async Task DispatchMessage(InMemoryTransportMessage message)
{
await _supervisor.Ready.ConfigureAwait(false);
if (_supervisor.StopToken.IsCancellationRequested)
return;
if (_receivePipe == null)
throw new ArgumentException("ReceivePipe not configured");
var context = new InMemoryReceiveContext(_inputAddress, message, _receiveObservable);
Interlocked.Increment(ref _deliveryCount);
var current = Interlocked.Increment(ref _currentPendingDeliveryCount);
while (current > _maxPendingDeliveryCount)
Interlocked.CompareExchange(ref _maxPendingDeliveryCount, current, _maxPendingDeliveryCount);
try
{
await _receiveObservable.PreReceive(context).ConfigureAwait(false);
await _receivePipe.Send(context).ConfigureAwait(false);
await context.CompleteTask.ConfigureAwait(false);
await _receiveObservable.PostReceive(context).ConfigureAwait(false);
_inputAddress.LogReceived(message.MessageId.ToString("N"), message.MessageType);
}
catch (Exception ex)
{
_log.Error($"RCV FAULT: {message.MessageId}", ex);
await _receiveObservable.ReceiveFault(context, ex).ConfigureAwait(false);
message.DeliveryCount++;
}
finally
{
Interlocked.Decrement(ref _currentPendingDeliveryCount);
}
}
async Task<byte[]> GetMessageBody(Stream body)
{
using (var ms = new MemoryStream())
{
await body.CopyToAsync(ms).ConfigureAwait(false);
return ms.ToArray();
}
}
static Guid GetMessageId(ReceiveContext context)
{
object messageIdValue;
return context.TransportHeaders.TryGetHeader("MessageId", out messageIdValue)
? new Guid(messageIdValue.ToString())
: NewId.NextGuid();
}
class Handle :
ReceiveTransportHandle
{
readonly ITaskParticipant _participant;
readonly TaskSupervisor _supervisor;
readonly InMemoryTransport _transport;
public Handle(TaskSupervisor supervisor, ITaskParticipant participant, InMemoryTransport transport)
{
_supervisor = supervisor;
_participant = participant;
_transport = transport;
}
async Task ReceiveTransportHandle.Stop(CancellationToken cancellationToken)
{
_participant.SetComplete();
await _supervisor.Stop("Stopped").ConfigureAwait(false);
await _supervisor.Completed.ConfigureAwait(false);
await _transport._endpointObservable.Completed(new Completed(_transport._inputAddress, _transport._deliveryCount,
_transport._maxPendingDeliveryCount)).ConfigureAwait(false);
}
}
class Ready :
ReceiveEndpointReady
{
public Ready(Uri inputAddress)
{
InputAddress = inputAddress;
}
public Uri InputAddress { get; }
}
class Completed :
ReceiveEndpointCompleted
{
public Completed(Uri inputAddress, long deliveryCount, long concurrentDeliveryCount)
{
InputAddress = inputAddress;
DeliveryCount = deliveryCount;
ConcurrentDeliveryCount = concurrentDeliveryCount;
}
public Uri InputAddress { get; }
public long DeliveryCount { get; }
public long ConcurrentDeliveryCount { get; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using LibGit2Sharp;
namespace GitIStage
{
internal sealed class PatchDocument : Document
{
public PatchDocument(IReadOnlyList<PatchEntry> entries, IReadOnlyList<PatchLine> lines)
{
Entries = entries;
Lines = lines;
Width = lines.Select(l => l.Text).DefaultIfEmpty(string.Empty).Max(t => t.LengthVisual());
}
public IReadOnlyList<PatchEntry> Entries { get; }
public IReadOnlyList<PatchLine> Lines { get; }
public override int Height => Lines.Count;
public override int Width { get; }
public override string GetLine(int index)
{
return Lines[index].Text;
}
public PatchEntry FindEntry(int lineIndex)
{
var index = FindEntryIndex(lineIndex);
return index < 0 ? null : Entries[index];
}
public int FindEntryIndex(int lineIndex)
{
// TODO: binary search would be more appropriate
for (var i = 0; i < Entries.Count; i++)
{
var e = Entries[i];
if (e.Offset <= lineIndex && lineIndex < e.Offset + e.Length)
return i;
}
return -1;
}
public static PatchDocument Parse(Patch patch)
{
if (patch == null)
return new PatchDocument(Array.Empty<PatchEntry>(), Array.Empty<PatchLine>());
var lines = new List<PatchLine>();
var entries = new List<PatchEntry>();
foreach (var change in patch)
{
var changeLines = ParseLines(change.Patch);
var entryOffset = lines.Count;
var entryLength = changeLines.Count;
lines.AddRange(changeLines);
var hunks = new List<PatchHunk>();
var hunkOffset = GetNextHunk(changeLines, -1);
while (hunkOffset < changeLines.Count)
{
var hunkEnd = GetNextHunk(changeLines, hunkOffset) - 1;
var hunkLength = hunkEnd - hunkOffset + 1;
var hunkLine = changeLines[hunkOffset].Text;
int oldStart;
int oldLength;
int newStart;
int newLength;
if (TryGetHunkInformation(hunkLine, out oldStart, out oldLength, out newStart, out newLength))
{
var hunk = new PatchHunk(entryOffset + hunkOffset, hunkLength, oldStart, oldLength, newStart, newLength);
hunks.Add(hunk);
}
hunkOffset = hunkEnd + 1;
}
var entry = new PatchEntry(entryOffset, entryLength, patch, change, hunks);
entries.Add(entry);
}
return new PatchDocument(entries, lines);
}
private static int GetNextHunk(IReadOnlyList<PatchLine> lines, int index)
{
index++;
while (index < lines.Count && lines[index].Kind != PatchLineKind.Hunk)
index++;
return index;
}
private static bool TryGetHunkInformation(string hunkLine,
out int oldStart,
out int oldLength,
out int newStart,
out int newLength)
{
oldStart = 0;
oldLength = 0;
newStart = 0;
newLength = 0;
if (!hunkLine.StartsWith("@@"))
return false;
var hunkMarkerEnd = hunkLine.IndexOf("@@", 2, StringComparison.Ordinal);
if (hunkMarkerEnd < 0)
return false;
var rangeInformation = hunkLine.Substring(2, hunkMarkerEnd - 2).Trim();
var ranges = rangeInformation.Split(' ');
if (ranges.Length != 2)
return false;
if (!TryParseRange(ranges[0], "-", out oldStart, out oldLength))
return false;
if (!TryParseRange(ranges[1], "+", out newStart, out newLength))
return false;
return true;
}
private static bool TryParseRange(string s, string marker, out int start, out int length)
{
start = 0;
length = 0;
if (!s.StartsWith(marker))
return false;
var numbers = s.Substring(1).Split(',');
if (numbers.Length != 1 && numbers.Length != 2)
return false;
if (!Int32.TryParse(numbers[0], out start))
return false;
if (numbers.Length == 1)
length = 1;
else if (!Int32.TryParse(numbers[1], out length))
return false;
return true;
}
private static IReadOnlyList<PatchLine> ParseLines(string content)
{
var lines = GetLines(content);
var headerEnd = GetHeaderEnd(lines);
var result = new List<PatchLine>(lines.Count);
for (var i = 0; i <= headerEnd; i++)
{
var kind = PatchLineKind.Header;
var text = lines[i];
var line = new PatchLine(kind, text);
result.Add(line);
}
for (var i = headerEnd + 1; i < lines.Count; i++)
{
var text = lines[i];
PatchLineKind kind;
if (text.StartsWith("@@"))
kind = PatchLineKind.Hunk;
else if (text.StartsWith("+"))
kind = PatchLineKind.Addition;
else if (text.StartsWith("-"))
kind = PatchLineKind.Removal;
else if (text.StartsWith(@"\"))
kind = PatchLineKind.NoEndOfLine;
else
kind = PatchLineKind.Context;
var line = new PatchLine(kind, text);
result.Add(line);
}
return result;
}
private static int GetHeaderEnd(IReadOnlyList<string> lines)
{
for (var i = 0; i < lines.Count; i++)
{
if (lines[i].StartsWith("+++"))
return i;
}
return -1;
}
private static IReadOnlyList<string> GetLines(string content)
{
var lines = new List<string>();
using (var sr = new StringReader(content))
{
string line;
while ((line = sr.ReadLine()) != null)
lines.Add(line);
}
return lines.ToArray();
}
}
}
| |
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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 MassTransit.Util.Scanning
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Internals.Extensions;
public class AssemblyScanner :
IAssemblyScanner
{
readonly List<Assembly> _assemblies = new List<Assembly>();
readonly CompositeFilter<string> _assemblyFilter = new CompositeFilter<string>();
readonly CompositeFilter<Type> _filter = new CompositeFilter<Type>();
public int Count => _assemblies.Count;
public string Description { get; set; }
public void Assembly(Assembly assembly)
{
if (!_assemblies.Contains(assembly))
_assemblies.Add(assembly);
}
public void Assembly(string assemblyName)
{
var asm = System.Reflection.Assembly.Load(assemblyName);
Assembly(asm);
}
public void AssemblyContainingType<T>()
{
AssemblyContainingType(typeof(T));
}
public void AssemblyContainingType(Type type)
{
_assemblies.Add(type.GetTypeInfo().Assembly);
}
public void Exclude(Func<Type, bool> exclude)
{
_filter.Excludes += exclude;
}
public void ExcludeNamespace(string nameSpace)
{
Exclude(type => type.IsInNamespace(nameSpace));
}
public void ExcludeNamespaceContainingType<T>()
{
ExcludeNamespace(typeof(T).Namespace);
}
public void Include(Func<Type, bool> predicate)
{
_filter.Includes += predicate;
}
public void IncludeNamespace(string nameSpace)
{
Include(type => type.IsInNamespace(nameSpace));
}
public void IncludeNamespaceContainingType<T>()
{
IncludeNamespace(typeof(T).Namespace);
}
public void ExcludeType<T>()
{
Exclude(type => type == typeof(T));
}
public void AssembliesFromApplicationBaseDirectory()
{
IEnumerable<Assembly> assemblies = AssemblyFinder.FindAssemblies(OnAssemblyLoadFailure, false, _assemblyFilter.Matches);
foreach (var assembly in assemblies)
{
Assembly(assembly);
}
}
public void AssembliesAndExecutablesFromPath(string path)
{
IEnumerable<Assembly> assemblies = AssemblyFinder.FindAssemblies(path, OnAssemblyLoadFailure, true, _assemblyFilter.Matches);
foreach (var assembly in assemblies)
{
Assembly(assembly);
}
}
public void AssembliesFromPath(string path)
{
IEnumerable<Assembly> assemblies = AssemblyFinder.FindAssemblies(path, OnAssemblyLoadFailure, false, _assemblyFilter.Matches);
foreach (var assembly in assemblies)
{
Assembly(assembly);
}
}
public void AssembliesAndExecutablesFromPath(string path, Func<Assembly, bool> assemblyFilter)
{
IEnumerable<Assembly> assemblies = AssemblyFinder.FindAssemblies(path, OnAssemblyLoadFailure, true, _assemblyFilter.Matches)
.Where(assemblyFilter);
foreach (var assembly in assemblies)
{
Assembly(assembly);
}
}
public void AssembliesFromPath(string path, Func<Assembly, bool> assemblyFilter)
{
IEnumerable<Assembly> assemblies = AssemblyFinder.FindAssemblies(path, OnAssemblyLoadFailure, false, _assemblyFilter.Matches)
.Where(assemblyFilter);
foreach (var assembly in assemblies)
{
Assembly(assembly);
}
}
public void ExcludeFileNameStartsWith(params string[] startsWith)
{
for (var i = 0; i < startsWith.Length; i++)
{
var value = startsWith[i];
_assemblyFilter.Excludes += name => name.StartsWith(value, StringComparison.OrdinalIgnoreCase);
}
}
public void IncludeFileNameStartsWith(params string[] startsWith)
{
for (var i = 0; i < startsWith.Length; i++)
{
var value = startsWith[i];
_assemblyFilter.Includes += name => name.StartsWith(value, StringComparison.OrdinalIgnoreCase);
}
}
public void AssembliesAndExecutablesFromApplicationBaseDirectory()
{
IEnumerable<Assembly> assemblies = AssemblyFinder.FindAssemblies(OnAssemblyLoadFailure, true, _assemblyFilter.Matches);
foreach (var assembly in assemblies)
{
Assembly(assembly);
}
}
static void OnAssemblyLoadFailure(string assemblyName, Exception exception)
{
Console.WriteLine("MassTransit could not load assembly from " + assemblyName);
}
public Task<TypeSet> ScanForTypes()
{
return AssemblyTypeCache.FindTypes(_assemblies, _filter.Matches);
}
public bool Contains(string assemblyName)
{
return _assemblies
.Select(assembly => new AssemblyName(assembly.FullName))
.Any(aName => aName.Name == assemblyName);
}
public bool HasAssemblies()
{
return _assemblies.Any();
}
public void TheCallingAssembly()
{
var callingAssembly = FindTheCallingAssembly();
if (callingAssembly != null)
{
Assembly(callingAssembly);
}
else
{
throw new ConfigurationException("Could not determine the calling assembly, you may need to explicitly call IAssemblyScanner.Assembly()");
}
}
static Assembly FindTheCallingAssembly()
{
var trace = new StackTrace(false);
var thisAssembly = System.Reflection.Assembly.GetExecutingAssembly();
var mtAssembly = typeof(IBus).GetTypeInfo().Assembly;
Assembly callingAssembly = null;
for (var i = 0; i < trace.FrameCount; i++)
{
var frame = trace.GetFrame(i);
var declaringType = frame.GetMethod().DeclaringType;
if (declaringType != null)
{
var assembly = declaringType.GetTypeInfo().Assembly;
if (assembly != thisAssembly && assembly != mtAssembly)
{
callingAssembly = assembly;
break;
}
}
}
return callingAssembly;
}
}
}
| |
// 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.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.UseExpressionBody;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody
{
public class UseExpressionBodyForMethodsTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new UseExpressionBodyForMethodsDiagnosticAnalyzer(), new UseExpressionBodyForMethodsCodeFixProvider());
private IDictionary<OptionKey, object> UseExpressionBody =>
this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement);
private IDictionary<OptionKey, object> UseBlockBody =>
this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.NeverWithNoneEnforcement);
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public void TestOptionSerialization1()
{
// Verify that bool-options can migrate to ExpressionBodyPreference-options.
var option = new CodeStyleOption<bool>(false, NotificationOption.None);
var serialized = option.ToXElement();
var deserialized = CodeStyleOption<ExpressionBodyPreference>.FromXElement(serialized);
Assert.Equal(ExpressionBodyPreference.Never, deserialized.Value);
option = new CodeStyleOption<bool>(true, NotificationOption.None);
serialized = option.ToXElement();
deserialized = CodeStyleOption<ExpressionBodyPreference>.FromXElement(serialized);
Assert.Equal(ExpressionBodyPreference.WhenPossible, deserialized.Value);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public void TestOptionSerialization2()
{
// Verify that ExpressionBodyPreference-options can migrate to bool-options.
var option = new CodeStyleOption<ExpressionBodyPreference>(ExpressionBodyPreference.Never, NotificationOption.None);
var serialized = option.ToXElement();
var deserialized = CodeStyleOption<bool>.FromXElement(serialized);
Assert.Equal(false, deserialized.Value);
option = new CodeStyleOption<ExpressionBodyPreference>(ExpressionBodyPreference.WhenPossible, NotificationOption.None);
serialized = option.ToXElement();
deserialized = CodeStyleOption<bool>.FromXElement(serialized);
Assert.Equal(true, deserialized.Value);
// This new values can't actually translate back to a bool. So we'll just get the default
// value for this option.
option = new CodeStyleOption<ExpressionBodyPreference>(ExpressionBodyPreference.WhenOnSingleLine, NotificationOption.None);
serialized = option.ToXElement();
deserialized = CodeStyleOption<bool>.FromXElement(serialized);
Assert.Equal(default(bool), deserialized.Value);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public void TestOptionEditorConfig1()
{
Assert.Null(CSharpCodeStyleOptions.ParseExpressionBodyPreference("true", null));
Assert.Null(CSharpCodeStyleOptions.ParseExpressionBodyPreference("false", null));
Assert.Null(CSharpCodeStyleOptions.ParseExpressionBodyPreference("when_on_single_line", null));
Assert.Null(CSharpCodeStyleOptions.ParseExpressionBodyPreference("true:blah", null));
Assert.Null(CSharpCodeStyleOptions.ParseExpressionBodyPreference("when_blah:error", null));
var option = CSharpCodeStyleOptions.ParseExpressionBodyPreference("false:error", null);
Assert.Equal(ExpressionBodyPreference.Never, option.Value);
Assert.Equal(NotificationOption.Error, option.Notification);
option = CSharpCodeStyleOptions.ParseExpressionBodyPreference("true:warning", null);
Assert.Equal(ExpressionBodyPreference.WhenPossible, option.Value);
Assert.Equal(NotificationOption.Warning, option.Notification);
option = CSharpCodeStyleOptions.ParseExpressionBodyPreference("when_on_single_line:suggestion", null);
Assert.Equal(ExpressionBodyPreference.WhenOnSingleLine, option.Value);
Assert.Equal(NotificationOption.Suggestion, option.Notification);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseExpressionBody1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void Foo()
{
[|Bar|]();
}
}",
@"class C
{
void Foo() => Bar();
}", options: UseExpressionBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseExpressionBody2()
{
await TestInRegularAndScriptAsync(
@"class C
{
int Foo()
{
return [|Bar|]();
}
}",
@"class C
{
int Foo() => Bar();
}", options: UseExpressionBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseExpressionBody3()
{
await TestInRegularAndScriptAsync(
@"class C
{
int Foo()
{
[|throw|] new NotImplementedException();
}
}",
@"class C
{
int Foo() => throw new NotImplementedException();
}", options: UseExpressionBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseExpressionBody4()
{
await TestInRegularAndScriptAsync(
@"class C
{
int Foo()
{
[|throw|] new NotImplementedException(); // comment
}
}",
@"class C
{
int Foo() => throw new NotImplementedException(); // comment
}", ignoreTrivia: false, options: UseExpressionBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseBlockBody1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void Foo() [|=>|] Bar();
}",
@"class C
{
void Foo()
{
Bar();
}
}", options: UseBlockBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseBlockBody2()
{
await TestInRegularAndScriptAsync(
@"class C
{
int Foo() [|=>|] Bar();
}",
@"class C
{
int Foo()
{
return Bar();
}
}", options: UseBlockBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseBlockBody3()
{
await TestInRegularAndScriptAsync(
@"class C
{
int Foo() [|=>|] throw new NotImplementedException();
}",
@"class C
{
int Foo()
{
throw new NotImplementedException();
}
}", options: UseBlockBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseBlockBody4()
{
await TestInRegularAndScriptAsync(
@"class C
{
int Foo() [|=>|] throw new NotImplementedException(); // comment
}",
@"class C
{
int Foo()
{
throw new NotImplementedException(); // comment
}
}", ignoreTrivia: false, options: UseBlockBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestComments1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void Foo()
{
// Comment
[|Bar|]();
}
}",
@"class C
{
void Foo() =>
// Comment
Bar();
}", options: UseExpressionBody, ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestComments2()
{
await TestInRegularAndScriptAsync(
@"class C
{
void Foo()
{
// Comment
return [|Bar|]();
}
}",
@"class C
{
void Foo() =>
// Comment
Bar();
}", options: UseExpressionBody, ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestComments3()
{
await TestInRegularAndScriptAsync(
@"class C
{
void Foo()
{
// Comment
throw [|Bar|]();
}
}",
@"class C
{
void Foo() =>
// Comment
throw Bar();
}", options: UseExpressionBody, ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestComments4()
{
await TestInRegularAndScriptAsync(
@"class C
{
void Foo()
{
[|Bar|](); // Comment
}
}",
@"class C
{
void Foo() => Bar(); // Comment
}", options: UseExpressionBody, ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestComments5()
{
await TestInRegularAndScriptAsync(
@"class C
{
void Foo()
{
return [|Bar|](); // Comment
}
}",
@"class C
{
void Foo() => Bar(); // Comment
}", options: UseExpressionBody, ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestComments6()
{
await TestInRegularAndScriptAsync(
@"class C
{
void Foo()
{
throw [|Bar|](); // Comment
}
}",
@"class C
{
void Foo() => throw Bar(); // Comment
}", options: UseExpressionBody, ignoreTrivia: false);
}
[WorkItem(17120, "https://github.com/dotnet/roslyn/issues/17120")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestDirectives1()
{
await TestInRegularAndScriptAsync(
@"
#define DEBUG
using System;
class Program
{
void Method()
{
#if DEBUG
[|Console|].WriteLine();
#endif
}
}",
@"
#define DEBUG
using System;
class Program
{
void Method() =>
#if DEBUG
Console.WriteLine();
#endif
}", options: UseExpressionBody, ignoreTrivia: false);
}
[WorkItem(17120, "https://github.com/dotnet/roslyn/issues/17120")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestDirectives2()
{
await TestInRegularAndScriptAsync(
@"
#define DEBUG
using System;
class Program
{
void Method()
{
#if DEBUG
[|Console|].WriteLine(a);
#else
Console.WriteLine(b);
#endif
}
}",
@"
#define DEBUG
using System;
class Program
{
void Method() =>
#if DEBUG
Console.WriteLine(a);
#else
Console.WriteLine(b);
#endif
}", options: UseExpressionBody, ignoreTrivia: false);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Configuration;
using System.Diagnostics;
namespace PortiLog.Monitor
{
public partial class ProgramForm : Form
{
long position = 0;
public ProgramForm()
{
InitializeComponent();
try
{
this.Bounds = Properties.Settings.Default.FormBounds;
this.WindowState = Properties.Settings.Default.WindowsState;
Program.LogFileName = Properties.Settings.Default.Filename;
Program.ReloadRecent();
}
catch// (Exception ex)
{
// i had some exceptions here..
}
}
void UpdateRecentMenuItems()
{
btnRecent.DropDownItems.Clear();
int i = 0;
foreach (var recent in Program.Recent)
{
i++;
ToolStripMenuItem item = new ToolStripMenuItem(string.Format("{0} {1}", i, recent));
item.Tag = recent;
item.Click += item_Click;
btnRecent.DropDownItems.Add(item);
}
}
void item_Click(object sender, EventArgs e)
{
var item = (ToolStripMenuItem)sender;
var recent = (string)item.Tag;
Program.SelectLogFile(recent);
UpdateRecentMenuItems();
UpdateView();
}
Exception _lastException;
bool UpdateView()
{
string filename = Program.LogFileName;
if (string.IsNullOrEmpty(filename))
return false;
this.Text = filename + " - PortiLog.Monitor";
try
{
using (FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
if (position == stream.Length)
{
return true;
}
else if (position > stream.Length)
{
this.txtFile.Text = "";
position = 0;
}
stream.Position = position;
using (StreamReader s = new StreamReader(stream))
{
string logtext = s.ReadToEnd();
int logtextLength = logtext.Length;
logtext = logtext.TrimEnd((char)20);
this.txtFile.AppendText(logtext);
position = stream.Position;
Application.DoEvents();
}
}
// reset last exception
_lastException = null;
lblStatus.Text = "Ok";
return true;
}
catch (Exception ex)
{
// only write an exception once
if (_lastException == null || ex.GetType() != _lastException.GetType())
{
lblStatus.Text = string.Format("Error occured: {0}\r\n", ex.Message);
}
_lastException = ex;
return false;
}
}
void ProgramForm_FormClosed(object sender, FormClosedEventArgs e)
{
try
{
if(this.WindowState == FormWindowState.Normal)
Properties.Settings.Default.FormBounds = this.Bounds;
Properties.Settings.Default.WindowsState = this.WindowState;
Properties.Settings.Default.Save();
}
catch //(Exception ex)
{
}
}
void reloadToolStripButton_Click(object sender, EventArgs e)
{
this.txtFile.Text = "";
this.position = 0;
UpdateView();
}
void timer_Tick(object sender, EventArgs e)
{
UpdateView();
}
void btnStartStopUpdates_Click(object sender, EventArgs e)
{
if (btnAutoUpdates.Checked)
{
timer.Start();
}
else
{
timer.Stop();
}
btnAutoUpdates.Checked = !btnAutoUpdates.Checked;
}
void btnOpen_Click(object sender, EventArgs e)
{
OpenFile();
}
void btnOpenInPackages_Click(object sender, EventArgs e)
{
var appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var packages = Path.Combine(appData, "packages");
openFileDialog.InitialDirectory = packages;
OpenFile();
}
void OpenFile()
{
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
OpenFile(openFileDialog.FileName);
}
}
void OpenFile(string filename)
{
Program.SelectLogFile(filename);
txtFile.Text = string.Empty;
UpdateRecentMenuItems();
UpdateView();
}
void timerStartup_Tick(object sender, EventArgs e)
{
timerStartup.Stop();
UpdateRecentMenuItems();
UpdateView();
}
void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
txtFile.Copy();
}
void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
ProcessStartInfo sInfo = new ProcessStartInfo("https://portilog.codeplex.com/");
Process.Start(sInfo);
}
void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the PnDirectoriosArchivo class.
/// </summary>
[Serializable]
public partial class PnDirectoriosArchivoCollection : ActiveList<PnDirectoriosArchivo, PnDirectoriosArchivoCollection>
{
public PnDirectoriosArchivoCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnDirectoriosArchivoCollection</returns>
public PnDirectoriosArchivoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnDirectoriosArchivo o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the PN_directorios_archivos table.
/// </summary>
[Serializable]
public partial class PnDirectoriosArchivo : ActiveRecord<PnDirectoriosArchivo>, IActiveRecord
{
#region .ctors and Default Settings
public PnDirectoriosArchivo()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnDirectoriosArchivo(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnDirectoriosArchivo(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnDirectoriosArchivo(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("PN_directorios_archivos", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdDirectoriosArchivosSerial = new TableSchema.TableColumn(schema);
colvarIdDirectoriosArchivosSerial.ColumnName = "id_directorios_archivos_serial";
colvarIdDirectoriosArchivosSerial.DataType = DbType.Int32;
colvarIdDirectoriosArchivosSerial.MaxLength = 0;
colvarIdDirectoriosArchivosSerial.AutoIncrement = true;
colvarIdDirectoriosArchivosSerial.IsNullable = false;
colvarIdDirectoriosArchivosSerial.IsPrimaryKey = true;
colvarIdDirectoriosArchivosSerial.IsForeignKey = false;
colvarIdDirectoriosArchivosSerial.IsReadOnly = false;
colvarIdDirectoriosArchivosSerial.DefaultSetting = @"";
colvarIdDirectoriosArchivosSerial.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdDirectoriosArchivosSerial);
TableSchema.TableColumn colvarIdDirectoriosArchivos = new TableSchema.TableColumn(schema);
colvarIdDirectoriosArchivos.ColumnName = "id_directorios_archivos";
colvarIdDirectoriosArchivos.DataType = DbType.AnsiString;
colvarIdDirectoriosArchivos.MaxLength = -1;
colvarIdDirectoriosArchivos.AutoIncrement = false;
colvarIdDirectoriosArchivos.IsNullable = false;
colvarIdDirectoriosArchivos.IsPrimaryKey = false;
colvarIdDirectoriosArchivos.IsForeignKey = false;
colvarIdDirectoriosArchivos.IsReadOnly = false;
colvarIdDirectoriosArchivos.DefaultSetting = @"";
colvarIdDirectoriosArchivos.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdDirectoriosArchivos);
TableSchema.TableColumn colvarNombreNodo = new TableSchema.TableColumn(schema);
colvarNombreNodo.ColumnName = "nombre_nodo";
colvarNombreNodo.DataType = DbType.AnsiString;
colvarNombreNodo.MaxLength = -1;
colvarNombreNodo.AutoIncrement = false;
colvarNombreNodo.IsNullable = true;
colvarNombreNodo.IsPrimaryKey = false;
colvarNombreNodo.IsForeignKey = false;
colvarNombreNodo.IsReadOnly = false;
colvarNombreNodo.DefaultSetting = @"";
colvarNombreNodo.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombreNodo);
TableSchema.TableColumn colvarIdNodoPadre = new TableSchema.TableColumn(schema);
colvarIdNodoPadre.ColumnName = "id_nodo_padre";
colvarIdNodoPadre.DataType = DbType.AnsiString;
colvarIdNodoPadre.MaxLength = -1;
colvarIdNodoPadre.AutoIncrement = false;
colvarIdNodoPadre.IsNullable = true;
colvarIdNodoPadre.IsPrimaryKey = false;
colvarIdNodoPadre.IsForeignKey = false;
colvarIdNodoPadre.IsReadOnly = false;
colvarIdNodoPadre.DefaultSetting = @"";
colvarIdNodoPadre.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdNodoPadre);
TableSchema.TableColumn colvarNombreNodoPadre = new TableSchema.TableColumn(schema);
colvarNombreNodoPadre.ColumnName = "nombre_nodo_padre";
colvarNombreNodoPadre.DataType = DbType.AnsiString;
colvarNombreNodoPadre.MaxLength = -1;
colvarNombreNodoPadre.AutoIncrement = false;
colvarNombreNodoPadre.IsNullable = true;
colvarNombreNodoPadre.IsPrimaryKey = false;
colvarNombreNodoPadre.IsForeignKey = false;
colvarNombreNodoPadre.IsReadOnly = false;
colvarNombreNodoPadre.DefaultSetting = @"";
colvarNombreNodoPadre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombreNodoPadre);
TableSchema.TableColumn colvarPath = new TableSchema.TableColumn(schema);
colvarPath.ColumnName = "path";
colvarPath.DataType = DbType.AnsiString;
colvarPath.MaxLength = -1;
colvarPath.AutoIncrement = false;
colvarPath.IsNullable = true;
colvarPath.IsPrimaryKey = false;
colvarPath.IsForeignKey = false;
colvarPath.IsReadOnly = false;
colvarPath.DefaultSetting = @"";
colvarPath.ForeignKeyTableName = "";
schema.Columns.Add(colvarPath);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_directorios_archivos",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdDirectoriosArchivosSerial")]
[Bindable(true)]
public int IdDirectoriosArchivosSerial
{
get { return GetColumnValue<int>(Columns.IdDirectoriosArchivosSerial); }
set { SetColumnValue(Columns.IdDirectoriosArchivosSerial, value); }
}
[XmlAttribute("IdDirectoriosArchivos")]
[Bindable(true)]
public string IdDirectoriosArchivos
{
get { return GetColumnValue<string>(Columns.IdDirectoriosArchivos); }
set { SetColumnValue(Columns.IdDirectoriosArchivos, value); }
}
[XmlAttribute("NombreNodo")]
[Bindable(true)]
public string NombreNodo
{
get { return GetColumnValue<string>(Columns.NombreNodo); }
set { SetColumnValue(Columns.NombreNodo, value); }
}
[XmlAttribute("IdNodoPadre")]
[Bindable(true)]
public string IdNodoPadre
{
get { return GetColumnValue<string>(Columns.IdNodoPadre); }
set { SetColumnValue(Columns.IdNodoPadre, value); }
}
[XmlAttribute("NombreNodoPadre")]
[Bindable(true)]
public string NombreNodoPadre
{
get { return GetColumnValue<string>(Columns.NombreNodoPadre); }
set { SetColumnValue(Columns.NombreNodoPadre, value); }
}
[XmlAttribute("Path")]
[Bindable(true)]
public string Path
{
get { return GetColumnValue<string>(Columns.Path); }
set { SetColumnValue(Columns.Path, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varIdDirectoriosArchivos,string varNombreNodo,string varIdNodoPadre,string varNombreNodoPadre,string varPath)
{
PnDirectoriosArchivo item = new PnDirectoriosArchivo();
item.IdDirectoriosArchivos = varIdDirectoriosArchivos;
item.NombreNodo = varNombreNodo;
item.IdNodoPadre = varIdNodoPadre;
item.NombreNodoPadre = varNombreNodoPadre;
item.Path = varPath;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdDirectoriosArchivosSerial,string varIdDirectoriosArchivos,string varNombreNodo,string varIdNodoPadre,string varNombreNodoPadre,string varPath)
{
PnDirectoriosArchivo item = new PnDirectoriosArchivo();
item.IdDirectoriosArchivosSerial = varIdDirectoriosArchivosSerial;
item.IdDirectoriosArchivos = varIdDirectoriosArchivos;
item.NombreNodo = varNombreNodo;
item.IdNodoPadre = varIdNodoPadre;
item.NombreNodoPadre = varNombreNodoPadre;
item.Path = varPath;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdDirectoriosArchivosSerialColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdDirectoriosArchivosColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn NombreNodoColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn IdNodoPadreColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn NombreNodoPadreColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn PathColumn
{
get { return Schema.Columns[5]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdDirectoriosArchivosSerial = @"id_directorios_archivos_serial";
public static string IdDirectoriosArchivos = @"id_directorios_archivos";
public static string NombreNodo = @"nombre_nodo";
public static string IdNodoPadre = @"id_nodo_padre";
public static string NombreNodoPadre = @"nombre_nodo_padre";
public static string Path = @"path";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using Hydra.Framework;
using Hydra.SharedCache.Common;
using Hydra.SharedCache.Common.Provider;
using Hydra.SharedCache.Common.Provider.Cache;
namespace Hydra.SharedCache.Notify
{
//
// **********************************************************************
/// <summary>
/// Network Form
/// </summary>
// **********************************************************************
//
public partial class Network
: Form
{
#region Delegates
//
// **********************************************************************
/// <summary>
/// Display Server Node
/// </summary>
// **********************************************************************
//
private delegate void DisplayServerNodes();
//
// **********************************************************************
/// <summary>
/// Update Statistics
/// </summary>
// **********************************************************************
//
private delegate void UpdateStats();
//
// **********************************************************************
/// <summary>
/// Display Node Selection
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
// **********************************************************************
//
private delegate void DelegateDisplayNodeSelectionResult(object sender, EventArgs e);
//
// **********************************************************************
/// <summary>
/// Search Regex
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
// **********************************************************************
//
private delegate void DelegateSearchRegEx(object sender, EventArgs e);
//
// **********************************************************************
/// <summary>
/// Button Search
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
// **********************************************************************
//
private delegate void DelegateBtnSearch(object sender, EventArgs e);
//
// **********************************************************************
/// <summary>
/// Clear Server Nodes
/// </summary>
// **********************************************************************
//
private delegate void DelegateClearLbxServerNodes();
//
// **********************************************************************
/// <summary>
/// Clear Node Key
/// </summary>
// **********************************************************************
//
private delegate void DelegateClearLbxNodeKey();
//
// **********************************************************************
/// <summary>
/// Clear Text Search Regex
/// </summary>
// **********************************************************************
//
private delegate void DelegateClearTxtSearchRegEx();
//
// **********************************************************************
/// <summary>
/// Clear Text Search Key
/// </summary>
// **********************************************************************
//
private delegate void DelegateClearTxtSearchKey();
//
// **********************************************************************
/// <summary>
/// Unselect Server List
/// </summary>
// **********************************************************************
//
private delegate void DelegateUnselectServerList();
//
// **********************************************************************
/// <summary>
/// Update Amount
/// </summary>
// **********************************************************************
//
private delegate void DelegateUpdateLblAmount();
//
// **********************************************************************
/// <summary>
/// Button Clear
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
// **********************************************************************
//
private delegate void DelegateBtnClearCache(object sender, EventArgs e);
#endregion
#region Member Variables
//
// **********************************************************************
/// <summary>
/// Worker Thread
/// </summary>
// **********************************************************************
//
private Thread m_Worker = null;
//
// **********************************************************************
/// <summary>
/// Statistics Thread
/// </summary>
// **********************************************************************
//
private Thread m_Statistics = null;
#endregion
#region Constructors
//
// **********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="Network"/> class.
/// </summary>
// **********************************************************************
//
public Network()
{
InitializeComponent();
StartUpThread();
LblClrVersion.Text = Environment.Version.ToString();
LblScVersion.Text = new AssemblyInfo().Version;
LoadServerClrVersions();
}
#endregion
#region Private Methods
//
// **********************************************************************
/// <summary>
/// Sets the tool tips.
/// </summary>
// **********************************************************************
//
private void SetToolTips()
{
Cursor.Current = Cursors.WaitCursor;
TtCacheNodes.SetToolTip(LblCacheNodes, "If you can't see all your Cache Nodes check your configuraiton file.");
TtCacheNodeKeys.SetToolTip(LblAvailableKeys, "A list with all selecte node key's - you able to select more then one server at once.");
TtRegularExpression.SetToolTip(TxtSearchRegEx, "If you're using Prefixes for your Key's you can simple get all Items based on regular expressions (e.g.: 'Prefix = ClientRelated_Xxxx then you search for 'ClientRelated_*.')");
TtSearch.SetToolTip(TxtSearchKey, "If you search a specific Key you can find it easly with this search form");
Cursor.Current = Cursors.Default;
}
//
// **********************************************************************
/// <summary>
/// Binds the stats.
/// </summary>
// **********************************************************************
//
private void BindStats()
{
if (InvokeRequired)
{
UpdateStats inv = new UpdateStats(BindStats);
Invoke(inv, new object[] { });
}
else
{
Cursor.Current = Cursors.WaitCursor;
LBSStatistic stat = LBSDistributionCache.SharedCache.GetStats();
//
// Put the words data in a DataTable so that column sorting works.
//
DataTable dataTable = new DataTable();
dataTable.Columns.Add("IP/Name", typeof(string));
dataTable.Columns.Add("Amount", typeof(long));
dataTable.Columns.Add("Size KB", typeof(long));
foreach (ServerStats st in stat.NodeDate)
{
dataTable.Rows.Add(new object[] { st.Name, st.AmountOfObjects, st.CacheSize / 1024 });
}
GvStats.DataSource = dataTable;
Cursor.Current = Cursors.Default;
}
}
//
// **********************************************************************
/// <summary>
/// Starts up thread.
/// </summary>
// **********************************************************************
//
private void StartUpThread()
{
SetToolTips();
m_Worker = new Thread(new ThreadStart(FullResetForm));
m_Worker.Start();
BindStats();
UpdateLblAmount();
}
//
// **********************************************************************
/// <summary>
/// Loads the server CLR versions.
/// </summary>
// **********************************************************************
//
private void LoadServerClrVersions()
{
IDictionary<string, string> serverNodeVersionsSharedCache = LBSDistributionCache.SharedCache.ServerNodeVersionSharedCache();
IDictionary<string, string> serverNodeVersionsClr = LBSDistributionCache.SharedCache.ServerNodeVersionClr();
foreach (string srv in LBSDistributionCache.SharedCache.Servers)
{
if (
serverNodeVersionsClr.ContainsKey(srv) &&
serverNodeVersionsSharedCache.ContainsKey(srv))
{
if (!serverNodeVersionsClr[srv].Equals(Environment.Version.ToString(), StringComparison.InvariantCultureIgnoreCase))
{
}
ComboBoxItem item = new ComboBoxItem(string.Format("Node:{0} - Shared Cache Ver.:{1} - CLR Ver.: {2}", srv, serverNodeVersionsSharedCache[srv], serverNodeVersionsClr[srv]), 0);
LbxServerClrVersion.Items.Add(item);
}
}
LbxServerClrVersion.Sorted = true;
}
//
// **********************************************************************
/// <summary>
/// Displays the node selection result.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
// **********************************************************************
//
private void DisplayNodeSelectionResult(object sender, EventArgs e)
{
if (InvokeRequired)
{
DelegateDisplayNodeSelectionResult inv = new DelegateDisplayNodeSelectionResult(DisplayNodeSelectionResult);
Invoke(inv, new object[] { sender, e });
}
else
{
Cursor.Current = Cursors.WaitCursor;
string msg = "Selected node(s) does not contain any key's." + Environment.NewLine;
int nodeCounter = 1;
if(LbxNodeKey.Items.Count > 0) LbxNodeKey.Items.Clear();
ListBox.SelectedObjectCollection coll = LbxServerNodes.SelectedItems;
foreach (ComboBoxItem node in coll)
{
List<string> items = LBSDistributionCache.SharedCache.GetAllKeys(node.Name);
if (items.Count == 0)
{
msg += Environment.NewLine +nodeCounter.ToString()+ " - [ " + node + " ]";
nodeCounter++;
}
foreach (string key in items)
{
LbxNodeKey.Items.Add(new ComboBoxItem(key, -1));
}
}
LbxNodeKey.Sorted = true;
if (LbxNodeKey.Items.Count == 0)
{
MessageBox.Show(msg, "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
Cursor.Current = Cursors.Default;
UpdateLblAmount();
UpdateLblAmount();
BindStats();
}
}
//
// **********************************************************************
/// <summary>
/// Starts the form.
/// </summary>
// **********************************************************************
//
private void StartForm()
{
try
{
if (InvokeRequired)
{
DisplayServerNodes utvd = new DisplayServerNodes(StartForm);
Invoke(utvd, new object[] { });
}
else
{
Cursor.Current = Cursors.WaitCursor;
foreach (string node in LBSDistributionCache.SharedCache.Servers)
{
LbxServerNodes.Items.Add(new ComboBoxItem(node, -1));
}
Cursor.Current = Cursors.Default;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
//
// **********************************************************************
/// <summary>
/// Fulls the reset form.
/// </summary>
// **********************************************************************
//
private void FullResetForm()
{
Cursor.Current = Cursors.WaitCursor;
if (LbxServerNodes.Items.Count > 0) ClearLbxServerNodes();
if (LbxNodeKey.Items.Count > 0) ClearLbxNodeKey();
if (!string.IsNullOrEmpty(TxtSearchRegEx.Text)) ClearTxtSearchRegEx();
if (!string.IsNullOrEmpty(TxtSearchKey.Text)) ClearTxtSearchKey();
StartForm();
Cursor.Current = Cursors.Default;
}
//
// **********************************************************************
/// <summary>
/// Clears the LBX server nodes.
/// </summary>
// **********************************************************************
//
private void ClearLbxServerNodes()
{
if (InvokeRequired)
{
DelegateClearLbxServerNodes inv = new DelegateClearLbxServerNodes(ClearLbxServerNodes);
Invoke(inv, new object[] { });
}
else
{
Cursor.Current = Cursors.WaitCursor;
LbxServerNodes.Items.Clear();
Cursor.Current = Cursors.Default;
}
}
//
// **********************************************************************
/// <summary>
/// Clears the LBX node key.
/// </summary>
// **********************************************************************
//
private void ClearLbxNodeKey()
{
if (InvokeRequired)
{
DelegateClearLbxNodeKey inv = new DelegateClearLbxNodeKey(ClearLbxNodeKey);
Invoke(inv, new object[] { });
}
else
{
Cursor.Current = Cursors.WaitCursor;
LbxNodeKey.Items.Clear();
Cursor.Current = Cursors.Default;
}
}
//
// **********************************************************************
/// <summary>
/// Clears the TXT search reg ex.
/// </summary>
// **********************************************************************
//
private void ClearTxtSearchRegEx()
{
if (InvokeRequired)
{
DelegateClearTxtSearchRegEx inv = new DelegateClearTxtSearchRegEx(ClearTxtSearchRegEx);
Invoke(inv, new object[] { });
}
else
{
Cursor.Current = Cursors.WaitCursor;
TxtSearchRegEx.Text = string.Empty;
Cursor.Current = Cursors.Default;
}
}
//
// **********************************************************************
/// <summary>
/// Clears the TXT search key.
/// </summary>
// **********************************************************************
//
private void ClearTxtSearchKey()
{
if (InvokeRequired)
{
DelegateClearTxtSearchKey inv = new DelegateClearTxtSearchKey(ClearTxtSearchKey);
Invoke(inv, new object[] { });
}
else
{
Cursor.Current = Cursors.WaitCursor;
TxtSearchKey.Text = string.Empty;
Cursor.Current = Cursors.Default;
}
}
//
// **********************************************************************
/// <summary>
/// Handles the Click event of the BtnRegularExpressionSearch control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
// **********************************************************************
//
private void BtnRegularExpressionSearch_Click(object sender, EventArgs e)
{
if (InvokeRequired)
{
DelegateSearchRegEx inv = new DelegateSearchRegEx(BtnRegularExpressionSearch_Click);
Invoke(inv, new object [] {sender, e} );
}
else
{
Cursor.Current = Cursors.WaitCursor;
if (LbxNodeKey.Items.Count > 0) LbxNodeKey.Items.Clear();
if (string.IsNullOrEmpty(TxtSearchRegEx.Text))
{
MessageBox.Show("Please enter search pattern.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
TxtSearchRegEx.Focus();
UnselectServerList();
Cursor.Current = Cursors.Default;
return;
}
try
{
Regex objNotNaturalPattern1 = new Regex(TxtSearchRegEx.Text);
}
catch (Exception ex)
{
MessageBox.Show("RegEx Parser Error: " + ex.Message + Environment.NewLine + "Please re-check you pattern and search again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
TxtSearchRegEx.Focus();
UnselectServerList();
Cursor.Current = Cursors.Default;
return;
}
IDictionary<string, byte[]> dict = LBSDistributionCache.SharedCache.RegexGet(TxtSearchRegEx.Text);
if (dict != null && dict.Count > 0)
{
if (LbxNodeKey.Items.Count > 0) LbxNodeKey.Items.Clear();
foreach (KeyValuePair<string, byte[]> item in dict)
{
LbxNodeKey.Items.Add(
new ComboBoxItem(item.Key, -1)
);
}
LbxNodeKey.Sorted = true;
}
else
{
MessageBox.Show("Your search term does not return any result, please revalidate your term: '" + TxtSearchRegEx.Text + "'",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
UnselectServerList();
Cursor.Current = Cursors.Default;
return;
}
Cursor.Current = Cursors.Default;
BindStats();
UnselectServerList();
UpdateLblAmount();
}
}
//
// **********************************************************************
/// <summary>
/// Handles the Click event of the BtnSearch control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
// **********************************************************************
//
private void BtnSearch_Click(object sender, EventArgs e)
{
if (InvokeRequired)
{
DelegateBtnSearch inv = new DelegateBtnSearch(BtnSearch_Click);
Invoke(inv, new object[] { sender, e });
}
else
{
Cursor.Current = Cursors.WaitCursor;
if (LbxNodeKey.Items.Count > 0) LbxNodeKey.Items.Clear();
if (string.IsNullOrEmpty(TxtSearchKey.Text))
{
MessageBox.Show("Please enter search pattern.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
TxtSearchKey.Focus();
UnselectServerList();
Cursor.Current = Cursors.Default;
return;
}
List<string> keys = LBSDistributionCache.SharedCache.GetAllKeys();
if (keys != null && keys.Count > 0)
{
if (LbxNodeKey.Items.Count > 0) LbxNodeKey.Items.Clear();
foreach (string item in keys)
{
if(item.Equals(TxtSearchKey.Text, StringComparison.InvariantCultureIgnoreCase))
LbxNodeKey.Items.Add(
new ComboBoxItem(item, -1)
);
}
}
else
{
MessageBox.Show("Your search term does not return any result, please revalidate your term: '" + TxtSearchKey.Text + "'",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Cursor.Current = Cursors.Default;
UnselectServerList();
return;
}
Cursor.Current = Cursors.Default;
UnselectServerList();
BindStats();
UpdateLblAmount();
}
}
//
// **********************************************************************
/// <summary>
/// Unselects the server list.
/// </summary>
// **********************************************************************
//
private void UnselectServerList()
{
if (InvokeRequired)
{
DelegateUnselectServerList inv = new DelegateUnselectServerList(UnselectServerList);
Invoke(inv, new object[] { });
}
else
{
LbxServerNodes.SelectedItem = null;
}
}
//
// **********************************************************************
/// <summary>
/// Handles the Click event of the BtnResetForm control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
// **********************************************************************
//
private void BtnResetForm_Click(object sender, EventArgs e)
{
StartUpThread();
}
//
// **********************************************************************
/// <summary>
/// Handles the Click event of the BtnClearSelectedKeys control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
// **********************************************************************
//
private void BtnClearSelectedKeys_Click(object sender, EventArgs e)
{
if (InvokeRequired)
{
DelegateDisplayNodeSelectionResult inv = new DelegateDisplayNodeSelectionResult(DisplayNodeSelectionResult);
Invoke(inv, new object[] { sender, e });
}
else
{
Cursor.Current = Cursors.WaitCursor;
string msg = "Please select single or multible key's you wish to delete" + Environment.NewLine;
ListBox.SelectedObjectCollection coll = LbxNodeKey.SelectedItems;
if (coll.Count > 0)
{
List<string> keysToDelete = new List<string>();
foreach (ComboBoxItem node in coll)
{
if (!string.IsNullOrEmpty(node.Name))
{
keysToDelete.Add(node.Name);
}
}
LBSDistributionCache.SharedCache.MultiDelete(keysToDelete);
List<string> a = LBSDistributionCache.SharedCache.GetAllKeys();
if (a != null && a.Count > 0)
{
foreach (string key in keysToDelete)
{
LBSDistributionCache.SharedCache.Remove(key);
}
}
FullResetForm();
UpdateLblAmount();
BindStats();
MessageBox.Show("All requested key(s) have been successfully deleted.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
else
{
MessageBox.Show(msg, "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Cursor.Current = Cursors.Default;
}
}
//
// **********************************************************************
/// <summary>
/// Updates the LBL amount.
/// </summary>
// **********************************************************************
//
private void UpdateLblAmount()
{
if (InvokeRequired)
{
DelegateUpdateLblAmount inv = new DelegateUpdateLblAmount(UpdateLblAmount);
Invoke(inv, new object[] { });
}
else
{
int amount = LbxNodeKey.Items.Count;
if (amount == 0)
LblAmount.Text = string.Empty;
else
LblAmount.Text = amount.ToString();
}
}
//
// **********************************************************************
/// <summary>
/// Sets the focus to delete.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
// **********************************************************************
//
private void SetFocusToDelete(object sender, EventArgs e)
{
LbxNodeKey.Focus();
}
//
// **********************************************************************
/// <summary>
/// Handles the Click event of the BtnClearCache control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
// **********************************************************************
//
private void BtnClearCache_Click(object sender, EventArgs e)
{
if (InvokeRequired)
{
DelegateBtnClearCache inv = new DelegateBtnClearCache(BtnClearCache_Click);
Invoke(inv, new object[] { sender, e} );
}
else
{
DialogResult result = MessageBox.Show("Are you sure you want to delete all items in configured Shared Cache nodes?",
"Your Attention is needed!",
MessageBoxButtons.YesNo);
switch (result)
{
case DialogResult.Yes:
{
LBSDistributionCache.SharedCache.Clear();
FullResetForm();
UpdateLblAmount();
BindStats();
break;
}
case DialogResult.Abort:
case DialogResult.Cancel:
case DialogResult.Ignore:
case DialogResult.No:
case DialogResult.None:
case DialogResult.OK:
case DialogResult.Retry:
default:
break;
}
}
}
#endregion
}
}
| |
/*
* DateAndTime.cs - Implementation of the
* "Microsoft.VisualBasic.DateAndTime" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace Microsoft.VisualBasic
{
using System;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.InteropServices;
using Microsoft.VisualBasic.CompilerServices;
[StandardModule]
public sealed class DateAndTime
{
// This class cannot be instantiated.
private DateAndTime() {}
// Convert the string representation of an interval into a "DateInterval".
private static DateInterval StringToInterval(String Interval)
{
if(Interval == null)
{
throw new ArgumentException
(S._("VB_InvalidInterval"), "Interval");
}
Interval = Interval.ToLower(CultureInfo.InvariantCulture);
switch(Interval)
{
case "yyyy": return DateInterval.Year;
case "q": return DateInterval.Quarter;
case "m": return DateInterval.Month;
case "y": return DateInterval.DayOfYear;
case "d": return DateInterval.Day;
case "ww": return DateInterval.WeekOfYear;
case "w": return DateInterval.Weekday;
case "h": return DateInterval.Hour;
case "n": return DateInterval.Minute;
case "s": return DateInterval.Second;
}
throw new ArgumentException
(S._("VB_InvalidInterval"), "Interval");
}
// Convert a number into an integer, rounded for the purposes of DateAdd.
private static int ToInt(double Number)
{
return checked((int)(Math.Round(Conversion.Fix(Number))));
}
// Add a time interval to a date value.
public static DateTime DateAdd
(String Interval, double Number, Object DateValue)
{
return DateAdd(StringToInterval(Interval), Number,
DateType.FromObject(DateValue));
}
public static DateTime DateAdd
(DateInterval Interval, double Number, DateTime DateValue)
{
Calendar calendar = CultureInfo.CurrentCulture.Calendar;
switch(Interval)
{
case DateInterval.Year:
return calendar.AddYears(DateValue, ToInt(Number));
case DateInterval.Quarter:
return calendar.AddMonths
(DateValue, ToInt(Number * 3.0));
case DateInterval.Month:
return calendar.AddMonths(DateValue, ToInt(Number));
case DateInterval.DayOfYear:
case DateInterval.Day:
case DateInterval.Weekday:
return DateValue.AddDays(ToInt(Number));
case DateInterval.WeekOfYear:
return DateValue.AddDays(ToInt(Number * 7.0));
case DateInterval.Hour:
return DateValue.AddHours(Number);
case DateInterval.Minute:
return DateValue.AddMinutes(Number);
case DateInterval.Second:
return DateValue.AddSeconds(Number);
}
throw new ArgumentException
(S._("VB_InvalidInterval"), "Interval");
}
// Adjust a tick difference.
private static long AdjustDiff(long ticks, long period)
{
return ToInt(((double)ticks) / ((double)period));
}
// Get the difference between two dates.
public static long DateDiff
(DateInterval Interval, DateTime Date1, DateTime Date2,
[Optional] [DefaultValue(FirstDayOfWeek.Sunday)]
FirstDayOfWeek DayOfWeek,
[Optional] [DefaultValue(FirstWeekOfYear.Jan1)]
FirstWeekOfYear WeekOfYear)
{
Calendar calendar = CultureInfo.CurrentCulture.Calendar;
switch(Interval)
{
case DateInterval.Year:
return calendar.GetYear(Date2) -
calendar.GetYear(Date1);
case DateInterval.Quarter:
return (calendar.GetYear(Date2) -
calendar.GetYear(Date1)) * 4 +
((calendar.GetMonth(Date2) - 1) / 3) -
((calendar.GetMonth(Date1) - 1) / 3);
case DateInterval.Month:
return (calendar.GetYear(Date2) -
calendar.GetYear(Date1)) * 12 +
calendar.GetMonth(Date2) -
calendar.GetMonth(Date1);
case DateInterval.DayOfYear:
case DateInterval.Day:
return AdjustDiff(Date2.Ticks - Date1.Ticks,
TimeSpan.TicksPerDay);
case DateInterval.WeekOfYear:
{
Date1.AddDays(-Weekday(Date1, DayOfWeek));
Date2.AddDays(-Weekday(Date2, DayOfWeek));
return AdjustDiff(Date2.Ticks - Date1.Ticks,
TimeSpan.TicksPerDay * 7);
}
// Not reached.
case DateInterval.Weekday:
return AdjustDiff(Date2.Ticks - Date1.Ticks,
TimeSpan.TicksPerDay * 7);
case DateInterval.Hour:
return AdjustDiff(Date2.Ticks - Date1.Ticks,
TimeSpan.TicksPerHour);
case DateInterval.Minute:
return AdjustDiff(Date2.Ticks - Date1.Ticks,
TimeSpan.TicksPerMinute);
case DateInterval.Second:
return AdjustDiff(Date2.Ticks - Date1.Ticks,
TimeSpan.TicksPerSecond);
}
throw new ArgumentException
(S._("VB_InvalidInterval"), "Interval");
}
public static long DateDiff
(String Interval, Object Date1, Object Date2,
[Optional] [DefaultValue(FirstDayOfWeek.Sunday)]
FirstDayOfWeek DayOfWeek,
[Optional] [DefaultValue(FirstWeekOfYear.Jan1)]
FirstWeekOfYear WeekOfYear)
{
return DateDiff(StringToInterval(Interval),
DateType.FromObject(Date1),
DateType.FromObject(Date2),
DayOfWeek, WeekOfYear);
}
// Get the system setting for the first day of week.
private static FirstDayOfWeek SystemFirstDay()
{
#if !ECMA_COMPAT
return (FirstDayOfWeek)
(((int)CultureInfo.CurrentCulture
.DateTimeFormat.FirstDayOfWeek) + 1);
#else
return FirstDayOfWeek.Sunday;
#endif
}
// Get a particular date part.
public static int DatePart
(DateInterval Interval, DateTime DateValue,
[Optional] [DefaultValue(FirstDayOfWeek.Sunday)]
FirstDayOfWeek FirstDayOfWeekValue,
[Optional] [DefaultValue(FirstWeekOfYear.Jan1)]
FirstWeekOfYear FirstWeekOfYearValue)
{
Calendar calendar = CultureInfo.CurrentCulture.Calendar;
switch(Interval)
{
case DateInterval.Year:
return calendar.GetYear(DateValue);
case DateInterval.Quarter:
return ((calendar.GetMonth(DateValue) - 1) % 3) + 1;
case DateInterval.Month:
return calendar.GetMonth(DateValue);
case DateInterval.DayOfYear:
return calendar.GetDayOfYear(DateValue);
case DateInterval.Day:
return calendar.GetDayOfMonth(DateValue);
case DateInterval.WeekOfYear:
{
if(FirstDayOfWeekValue == FirstDayOfWeek.System)
{
FirstDayOfWeekValue = SystemFirstDay();
}
CalendarWeekRule rule;
switch(FirstWeekOfYearValue)
{
case FirstWeekOfYear.System:
{
#if !ECMA_COMPAT
rule = CultureInfo.CurrentCulture
.DateTimeFormat.CalendarWeekRule;
#else
rule = CalendarWeekRule.FirstDay;
#endif
}
break;
case FirstWeekOfYear.Jan1:
{
rule = CalendarWeekRule.FirstDay;
}
break;
case FirstWeekOfYear.FirstFourDays:
{
rule = CalendarWeekRule.FirstFourDayWeek;
}
break;
case FirstWeekOfYear.FirstFullWeek:
{
rule = CalendarWeekRule.FirstFullWeek;
}
break;
default:
{
throw new ArgumentException
(S._("VB_InvalidWeekOfYear"),
"FirstWeekOfYearValue");
}
// Not reached.
}
return calendar.GetWeekOfYear
(DateValue, rule,
(DayOfWeek)(((int)FirstDayOfWeekValue) - 1));
}
// Not reached.
case DateInterval.Weekday:
return Weekday(DateValue, FirstDayOfWeekValue);
case DateInterval.Hour:
return DateValue.Hour;
case DateInterval.Minute:
return DateValue.Minute;
case DateInterval.Second:
return DateValue.Second;
}
throw new ArgumentException
(S._("VB_InvalidInterval"), "Interval");
}
public static int DatePart
(String Interval, Object DateValue,
[Optional] [DefaultValue(FirstDayOfWeek.Sunday)]
FirstDayOfWeek FirstDayOfWeekValue,
[Optional] [DefaultValue(FirstWeekOfYear.Jan1)]
FirstWeekOfYear FirstWeekOfYearValue)
{
return DatePart(StringToInterval(Interval),
DateType.FromObject(DateValue),
FirstDayOfWeekValue, FirstWeekOfYearValue);
}
// Build a date value.
public static DateTime DateSerial(int Year, int Month, int Day)
{
// Fix up the year value.
if(Year < 0)
{
Year = DateTime.Now.Year + Year;
}
else if(Year < 30)
{
Year += 2000;
}
else if(Year < 100)
{
Year += 1900;
}
// Fix up the month value.
while(Month < 1)
{
--Year;
Month += 12;
}
while(Month > 12)
{
++Year;
Month -= 12;
}
// Fix up the day value.
int extraDays;
int daysInMonth = DateTime.DaysInMonth(Year, Month);
if(Day < 1)
{
extraDays = (Day - 1);
}
else if(Day > daysInMonth)
{
extraDays = (Day - daysInMonth);
}
else
{
extraDays = 0;
}
// Build and return the date.
DateTime date = new DateTime(Year, Month, Day);
// Adjust the date for extra days.
if(extraDays != 0)
{
return date.AddDays((double)extraDays);
}
else
{
return date;
}
}
// Convert a string into a date value.
public static DateTime DateValue(String StringDate)
{
return (DateType.FromString(StringDate)).Date;
}
// Get the day from a date value.
public static int Day(DateTime DateValue)
{
return CultureInfo.CurrentCulture.Calendar
.GetDayOfMonth(DateValue);
}
// Get the hour from a date value.
public static int Hour(DateTime TimeValue)
{
return CultureInfo.CurrentCulture.Calendar.GetHour(TimeValue);
}
// Get the minute from a date value.
public static int Minute(DateTime TimeValue)
{
return CultureInfo.CurrentCulture.Calendar.GetMinute(TimeValue);
}
// Get the month from a date value.
public static int Month(DateTime DateValue)
{
return CultureInfo.CurrentCulture.Calendar.GetMonth(DateValue);
}
// Get the name of a specific month.
public static String MonthName
(int Month, [Optional] [DefaultValue(false)] bool Abbreviate)
{
if(Month < 1 || Month > 13) // Some calendars have 13 months.
{
throw new ArgumentException(S._("VB_MonthRange"), "Month");
}
if(Abbreviate)
{
return CultureInfo.CurrentCulture.DateTimeFormat
.GetAbbreviatedMonthName(Month);
}
else
{
return CultureInfo.CurrentCulture.DateTimeFormat
.GetMonthName(Month);
}
}
// Get the second from a date value.
public static int Second(DateTime TimeValue)
{
return CultureInfo.CurrentCulture.Calendar.GetSecond(TimeValue);
}
// Convert hour, minute, and second values into a time value.
public static DateTime TimeSerial(int Hour, int Minute, int Second)
{
return new DateTime(Hour * TimeSpan.TicksPerHour +
Minute * TimeSpan.TicksPerMinute +
Second * TimeSpan.TicksPerSecond);
}
// Extract the time portion of a value.
public static DateTime TimeValue(String StringTime)
{
long ticks = (DateType.FromString(StringTime)).Ticks;
return new DateTime(ticks % TimeSpan.TicksPerDay);
}
// Get the weekday from a date value.
public static int Weekday
(DateTime DateValue,
[Optional] [DefaultValue(FirstDayOfWeek.Sunday)]
FirstDayOfWeek DayOfWeek)
{
if(DayOfWeek == FirstDayOfWeek.System)
{
DayOfWeek = SystemFirstDay();
}
if(((int)DayOfWeek) < 1 || ((int)DayOfWeek) > 7)
{
throw new ArgumentException
(S._("VB_InvalidWeekday"), "DayOfWeek");
}
int day = (int)(CultureInfo.CurrentCulture.Calendar
.GetDayOfWeek(DateValue)) + 1;
return ((day - (int)DayOfWeek + 7) % 7) + 1;
}
// Get the name of a specific weekday.
public static String WeekdayName
(int Weekday,
[Optional] [DefaultValue(false)] bool Abbreviate,
[Optional] [DefaultValue(FirstDayOfWeek.Sunday)]
FirstDayOfWeek FirstDayOfWeekValue)
{
if(Weekday < 1 || Weekday > 7)
{
throw new ArgumentException
(S._("VB_InvalidWeekday"), "Weekday");
}
if(((int)FirstDayOfWeekValue) < 0 ||
((int)FirstDayOfWeekValue) > 7)
{
throw new ArgumentException
(S._("VB_InvalidWeekday"), "FirstDayOfWeekValue");
}
if(FirstDayOfWeekValue == FirstDayOfWeek.System)
{
FirstDayOfWeekValue = SystemFirstDay();
}
int day = (Weekday + (int)FirstDayOfWeekValue - 2) % 7;
if(Abbreviate)
{
return CultureInfo.CurrentCulture.DateTimeFormat
.GetAbbreviatedDayName((DayOfWeek)day);
}
else
{
return CultureInfo.CurrentCulture.DateTimeFormat
.GetDayName((DayOfWeek)day);
}
}
// Get the year from a date value.
public static int Year(DateTime DateValue)
{
return CultureInfo.CurrentCulture.Calendar.GetYear(DateValue);
}
// Get the current date as a string.
public static String DateString
{
get
{
return DateTime.Today.ToString
("MM\\-dd\\-yyyy", CultureInfo.InvariantCulture);
}
set
{
// Ignored - not used in this implementation.
}
}
// Get the current date and time.
public static DateTime Now
{
get
{
return DateTime.Now;
}
}
// Get the current time of day.
public static DateTime TimeOfDay
{
get
{
return new DateTime(DateTime.Now.TimeOfDay.Ticks);
}
set
{
// Ignored - not used in this implementation.
}
}
// Get the current time as a string.
public static String TimeString
{
get
{
return (new DateTime(DateTime.Now.TimeOfDay.Ticks))
.ToString("HH:mm:ss",
CultureInfo.InvariantCulture);
}
set
{
// Ignored - not used in this implementation.
}
}
// Get a timer value from the current time.
public static double Timer
{
get
{
return (double)(DateTime.Now.Ticks % TimeSpan.TicksPerDay)
/ (double)(TimeSpan.TicksPerSecond);
}
}
// Get today's date.
public static DateTime Today
{
get
{
return DateTime.Today;
}
set
{
// Ignored - not used in this implementation.
}
}
}; // class DateAndTime
}; // namespace Microsoft.VisualBasic
| |
/*
* (c) 2008 MOSA - The Managed Operating System Alliance
*
* Licensed under the terms of the New BSD License.
*
* Authors:
* Simon Wollwage (rootnode) <kintaro@think-in-co.de>
*/
using System;
namespace Pictor.Transform
{
//----------------------------------------------------------trans_viewport
public sealed class Viewport
{
private double m_world_x1;
private double m_world_y1;
private double m_world_x2;
private double m_world_y2;
private double m_device_x1;
private double m_device_y1;
private double m_device_x2;
private double m_device_y2;
private EAspectRatio m_aspect;
private bool m_is_valid;
private double m_align_x;
private double m_align_y;
private double m_wx1;
private double m_wy1;
private double m_wx2;
private double m_wy2;
private double m_dx1;
private double m_dy1;
private double m_kx;
private double m_ky;
public enum EAspectRatio
{
Stretch,
Meet,
aspect_ratio_slice
};
//-------------------------------------------------------------------
public Viewport()
{
m_world_x1 = (0.0);
m_world_y1 = (0.0);
m_world_x2 = (1.0);
m_world_y2 = (1.0);
m_device_x1 = (0.0);
m_device_y1 = (0.0);
m_device_x2 = (1.0);
m_device_y2 = (1.0);
m_aspect = EAspectRatio.Stretch;
m_is_valid = (true);
m_align_x = (0.5);
m_align_y = (0.5);
m_wx1 = (0.0);
m_wy1 = (0.0);
m_wx2 = (1.0);
m_wy2 = (1.0);
m_dx1 = (0.0);
m_dy1 = (0.0);
m_kx = (1.0);
m_ky = (1.0);
}
//-------------------------------------------------------------------
public void PreserveAspectRatio(double alignx,
double aligny,
EAspectRatio aspect)
{
m_align_x = alignx;
m_align_y = aligny;
m_aspect = aspect;
Update();
}
//-------------------------------------------------------------------
public void DeviceViewport(double x1, double y1, double x2, double y2)
{
m_device_x1 = x1;
m_device_y1 = y1;
m_device_x2 = x2;
m_device_y2 = y2;
Update();
}
//-------------------------------------------------------------------
public void WorldViewport(double x1, double y1, double x2, double y2)
{
m_world_x1 = x1;
m_world_y1 = y1;
m_world_x2 = x2;
m_world_y2 = y2;
Update();
}
//-------------------------------------------------------------------
public void DeviceViewport(out double x1, out double y1, out double x2, out double y2)
{
x1 = m_device_x1;
y1 = m_device_y1;
x2 = m_device_x2;
y2 = m_device_y2;
}
//-------------------------------------------------------------------
public void WorldViewport(out double x1, out double y1, out double x2, out double y2)
{
x1 = m_world_x1;
y1 = m_world_y1;
x2 = m_world_x2;
y2 = m_world_y2;
}
//-------------------------------------------------------------------
public void WorldViewportActual(out double x1, out double y1,
out double x2, out double y2)
{
x1 = m_wx1;
y1 = m_wy1;
x2 = m_wx2;
y2 = m_wy2;
}
//-------------------------------------------------------------------
public bool IsValid
{
get { return m_is_valid; }
}
public double xAlignment
{
get { return m_align_x; }
}
public double yAlignment
{
get { return m_align_y; }
}
public EAspectRatio AspectRatio
{
get { return m_aspect; }
}
//-------------------------------------------------------------------
public void Transform(ref double x, ref double y)
{
x = (x - m_wx1) * m_kx + m_dx1;
y = (y - m_wy1) * m_ky + m_dy1;
}
//-------------------------------------------------------------------
public void TransformScaleOnly(ref double x, ref double y)
{
x *= m_kx;
y *= m_ky;
}
//-------------------------------------------------------------------
public void InverseTransform(ref double x, ref double y)
{
x = (x - m_dx1) / m_kx + m_wx1;
y = (y - m_dy1) / m_ky + m_wy1;
}
//-------------------------------------------------------------------
public void InverseTransformScaleOnly(ref double x, ref double y)
{
x /= m_kx;
y /= m_ky;
}
//-------------------------------------------------------------------
public double DeviceDx
{
get { return m_dx1 - m_wx1 * m_kx; }
}
public double DeviceDy
{
get { return m_dy1 - m_wy1 * m_ky; }
}
//-------------------------------------------------------------------
public double xScale
{
get { return m_kx; }
}
//-------------------------------------------------------------------
public double yScale
{
get { return m_ky; }
}
//-------------------------------------------------------------------
public double Scale
{
get { return (m_kx + m_ky) * 0.5; }
}
//-------------------------------------------------------------------
public Affine ToAffine()
{
Affine mtx = Affine.NewTranslation(-m_wx1, -m_wy1);
mtx *= Affine.NewScaling(m_kx, m_ky);
mtx *= Affine.NewTranslation(m_dx1, m_dy1);
return mtx;
}
//-------------------------------------------------------------------
public Affine ToAffineScaleOnly()
{
return Affine.NewScaling(m_kx, m_ky);
}
private void Update()
{
double epsilon = 1e-30;
if (Math.Abs(m_world_x1 - m_world_x2) < epsilon ||
Math.Abs(m_world_y1 - m_world_y2) < epsilon ||
Math.Abs(m_device_x1 - m_device_x2) < epsilon ||
Math.Abs(m_device_y1 - m_device_y2) < epsilon)
{
m_wx1 = m_world_x1;
m_wy1 = m_world_y1;
m_wx2 = m_world_x1 + 1.0;
m_wy2 = m_world_y2 + 1.0;
m_dx1 = m_device_x1;
m_dy1 = m_device_y1;
m_kx = 1.0;
m_ky = 1.0;
m_is_valid = false;
return;
}
double world_x1 = m_world_x1;
double world_y1 = m_world_y1;
double world_x2 = m_world_x2;
double world_y2 = m_world_y2;
double device_x1 = m_device_x1;
double device_y1 = m_device_y1;
double device_x2 = m_device_x2;
double device_y2 = m_device_y2;
if (m_aspect != EAspectRatio.Stretch)
{
double d;
m_kx = (device_x2 - device_x1) / (world_x2 - world_x1);
m_ky = (device_y2 - device_y1) / (world_y2 - world_y1);
if ((m_aspect == EAspectRatio.Meet) == (m_kx < m_ky))
{
d = (world_y2 - world_y1) * m_ky / m_kx;
world_y1 += (world_y2 - world_y1 - d) * m_align_y;
world_y2 = world_y1 + d;
}
else
{
d = (world_x2 - world_x1) * m_kx / m_ky;
world_x1 += (world_x2 - world_x1 - d) * m_align_x;
world_x2 = world_x1 + d;
}
}
m_wx1 = world_x1;
m_wy1 = world_y1;
m_wx2 = world_x2;
m_wy2 = world_y2;
m_dx1 = device_x1;
m_dy1 = device_y1;
m_kx = (device_x2 - device_x1) / (world_x2 - world_x1);
m_ky = (device_y2 - device_y1) / (world_y2 - world_y1);
m_is_valid = true;
}
};
}
| |
#region license
// Copyright (c) 2003, 2004, 2005 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
namespace Boo.Lang.Compiler.TypeSystem
{
using System;
using System.Collections.Generic;
using Boo.Lang.Compiler.TypeSystem;
using Boo.Lang.Compiler.Ast;
using System.Text;
/// <summary>
/// A type constructed by supplying type parameters to a generic type, involving internal types.
/// </summary>
/// <remarks>
/// Constructed types constructed from an external generic type with external type arguments
/// are themselves external, and are represented as ExternalType instances. All other cases
/// are represented by this type.
/// </remarks>
public class GenericConstructedType : IType, IConstructedTypeInfo
{
protected TypeSystemServices _tss;
protected IType _definition;
IType[] _arguments;
GenericMapping _genericMapping;
bool _fullyConstructed;
string _fullName = null;
public GenericConstructedType(TypeSystemServices tss, IType definition, IType[] arguments)
{
_tss = tss;
_definition = definition;
_arguments = arguments;
_genericMapping = new GenericMapping(tss, this, arguments);
_fullyConstructed = IsFullyConstructed();
}
protected bool IsFullyConstructed()
{
return GenericsServices.GetTypeGenerity(this) == 0;
}
protected string BuildFullName()
{
string[] argumentNames = Array.ConvertAll<IType, string>(
GenericArguments,
delegate(IType t) { return t.FullName; });
return string.Format("{0}[{1}]", _definition.FullName, string.Join(", ", argumentNames));
}
public GenericMapping GenericMapping
{
get { return _genericMapping; }
}
public bool IsClass
{
get { return _definition.IsClass; }
}
public bool IsAbstract
{
get { return _definition.IsAbstract; }
}
public bool IsInterface
{
get { return _definition.IsInterface; }
}
public bool IsEnum
{
get { return _definition.IsEnum; }
}
public bool IsByRef
{
get { return _definition.IsByRef; }
}
public bool IsValueType
{
get { return _definition.IsValueType; }
}
public bool IsFinal
{
get { return _definition.IsFinal; }
}
public bool IsArray
{
get { return _definition.IsArray; }
}
public int GetTypeDepth()
{
return _definition.GetTypeDepth();
}
public IType GetElementType()
{
return GenericMapping.Map(_definition.GetElementType());
}
public IType BaseType
{
get { return GenericMapping.Map(_definition.BaseType); }
}
public IEntity GetDefaultMember()
{
return GenericMapping.Map(_definition.GetDefaultMember());
}
public IConstructor[] GetConstructors()
{
return Array.ConvertAll<IConstructor, IConstructor>(
_definition.GetConstructors(),
delegate(IConstructor c) { return GenericMapping.Map(c); });
}
public IType[] GetInterfaces()
{
return Array.ConvertAll<IType, IType>(
_definition.GetInterfaces(),
GenericMapping.Map);
}
public bool IsSubclassOf(IType other)
{
if (BaseType != null && (BaseType == other || BaseType.IsSubclassOf(other)))
{
return true;
}
if (other.IsInterface && Array.Exists(
GetInterfaces(),
delegate(IType i) { return other.IsAssignableFrom(i); }))
{
return true;
}
return false;
}
public virtual bool IsAssignableFrom(IType other)
{
if (other == null)
{
return false;
}
if (other == this || other.IsSubclassOf(this) || (other == Null.Default && !IsValueType))
{
return true;
}
return false;
}
public IGenericTypeInfo GenericInfo
{
get { return null; }
}
public IConstructedTypeInfo ConstructedInfo
{
get { return this; }
}
public IType Type
{
get { return this; }
}
public INamespace ParentNamespace
{
get
{
return GenericMapping.Map(_definition.ParentNamespace as IEntity) as INamespace;
}
}
public bool Resolve(List targetList, string name, EntityType filter)
{
// Resolve name using definition, and then map the matching members
List definitionMatches = new List();
if (_definition.Resolve(definitionMatches, name, filter))
{
foreach (IEntity match in definitionMatches)
{
if(GenericMapping.EntityNeedsMapping(match))
{
targetList.AddUnique(GenericMapping.Map(match));
}
else
{
targetList.AddUnique(match);
}
}
return true;
}
return false;
}
public IEntity[] GetMembers()
{
return Array.ConvertAll<IEntity, IEntity>(_definition.GetMembers(), GenericMapping.Map);
}
public string Name
{
get { return _definition.Name; }
}
public string FullName
{
get { return _fullName ?? (_fullName = BuildFullName()); }
}
public EntityType EntityType
{
get { return EntityType.Type; }
}
public IType[] GenericArguments
{
get { return _arguments; }
}
public IType GenericDefinition
{
get { return _definition; }
}
public bool FullyConstructed
{
get { return _fullyConstructed; }
}
public IMethod GetMethodTemplate(IMethod method)
{
return _genericMapping.UnMap(method);
}
public bool IsDefined(IType attributeType)
{
return _definition.IsDefined(attributeType);
}
public override string ToString()
{
return FullName;
}
}
public class GenericConstructedCallableType : GenericConstructedType, ICallableType
{
CallableSignature _signature;
public GenericConstructedCallableType(TypeSystemServices tss, ICallableType definition, IType[] arguments)
: base(tss, definition, arguments)
{
}
public CallableSignature GetSignature()
{
if (_signature == null)
{
CallableSignature definitionSignature = ((ICallableType)_definition).GetSignature();
IParameter[] parameters = GenericMapping.Map(definitionSignature.Parameters);
IType returnType = GenericMapping.Map(definitionSignature.ReturnType);
_signature = new CallableSignature(parameters, returnType);
}
return _signature;
}
override public bool IsAssignableFrom(IType other)
{
return _tss.IsCallableTypeAssignableFrom(this, other);
}
}
}
| |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for Additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
using System;
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.HSSF.Record.CF;
using System.Collections.Generic;
using NPOI.SS;
namespace NPOI.XSSF.UserModel
{
/**
* XSSF Conditional Formattings
*/
public class XSSFSheetConditionalFormatting : ISheetConditionalFormatting
{
/** Office 2010 Conditional Formatting extensions namespace */
protected static string CF_EXT_2009_NS_X14 = "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main";
private XSSFSheet _sheet;
/* namespace */
internal XSSFSheetConditionalFormatting(XSSFSheet sheet)
{
_sheet = sheet;
}
/**
* A factory method allowing to create a conditional formatting rule
* with a cell comparison operator<p/>
* TODO - formulas Containing cell references are currently not Parsed properly
*
* @param comparisonOperation - a constant value from
* <tt>{@link NPOI.hssf.record.CFRuleRecord.ComparisonOperator}</tt>: <p>
* <ul>
* <li>BETWEEN</li>
* <li>NOT_BETWEEN</li>
* <li>EQUAL</li>
* <li>NOT_EQUAL</li>
* <li>GT</li>
* <li>LT</li>
* <li>GE</li>
* <li>LE</li>
* </ul>
* </p>
* @param formula1 - formula for the valued, Compared with the cell
* @param formula2 - second formula (only used with
* {@link NPOI.ss.usermodel.ComparisonOperator#BETWEEN}) and
* {@link NPOI.ss.usermodel.ComparisonOperator#NOT_BETWEEN} operations)
*/
public IConditionalFormattingRule CreateConditionalFormattingRule(
ComparisonOperator comparisonOperation,
String formula1,
String formula2)
{
XSSFConditionalFormattingRule rule = new XSSFConditionalFormattingRule(_sheet);
CT_CfRule cfRule = rule.GetCTCfRule();
cfRule.AddFormula(formula1);
if (formula2 != null) cfRule.AddFormula(formula2);
cfRule.type = (ST_CfType.cellIs);
ST_ConditionalFormattingOperator operator1;
switch (comparisonOperation)
{
case ComparisonOperator.Between:
operator1 = ST_ConditionalFormattingOperator.between; break;
case ComparisonOperator.NotBetween:
operator1 = ST_ConditionalFormattingOperator.notBetween; break;
case ComparisonOperator.LessThan:
operator1 = ST_ConditionalFormattingOperator.lessThan; break;
case ComparisonOperator.LessThanOrEqual:
operator1 = ST_ConditionalFormattingOperator.lessThanOrEqual; break;
case ComparisonOperator.GreaterThan:
operator1 = ST_ConditionalFormattingOperator.greaterThan; break;
case ComparisonOperator.GreaterThanOrEqual:
operator1 = ST_ConditionalFormattingOperator.greaterThanOrEqual; break;
case ComparisonOperator.Equal:
operator1 = ST_ConditionalFormattingOperator.equal; break;
case ComparisonOperator.NotEqual:
operator1 = ST_ConditionalFormattingOperator.notEqual; break;
default:
throw new ArgumentException("Unknown comparison operator: " + comparisonOperation);
}
cfRule.@operator = (operator1);
return rule;
}
public IConditionalFormattingRule CreateConditionalFormattingRule(
ComparisonOperator comparisonOperation,
String formula)
{
return CreateConditionalFormattingRule(comparisonOperation, formula, null);
}
/**
* A factory method allowing to create a conditional formatting rule with a formula.<br>
*
* @param formula - formula for the valued, Compared with the cell
*/
public IConditionalFormattingRule CreateConditionalFormattingRule(String formula)
{
XSSFConditionalFormattingRule rule = new XSSFConditionalFormattingRule(_sheet);
CT_CfRule cfRule = rule.GetCTCfRule();
cfRule.AddFormula(formula);
cfRule.type = ST_CfType.expression;
return rule;
}
/**
* A factory method allowing the creation of conditional formatting
* rules using an Icon Set / Multi-State formatting.
* The thresholds for it will be created, but will be empty
* and require configuring with
* {@link XSSFConditionalFormattingRule#getMultiStateFormatting()}
* then
* {@link XSSFIconMultiStateFormatting#getThresholds()}
*/
public IConditionalFormattingRule CreateConditionalFormattingRule(IconSet iconSet)
{
XSSFConditionalFormattingRule rule = new XSSFConditionalFormattingRule(_sheet);
// Have it setup, with suitable defaults
rule.CreateMultiStateFormatting(iconSet);
// All done!
return rule;
}
/**
* Create a Databar conditional formatting rule.
* <p>The thresholds and colour for it will be created, but will be
* empty and require configuring with
* {@link XSSFConditionalFormattingRule#getDataBarFormatting()}
* then
* {@link XSSFDataBarFormatting#getMinThreshold()}
* and
* {@link XSSFDataBarFormatting#getMaxThreshold()}
*/
public XSSFConditionalFormattingRule CreateConditionalFormattingRule(XSSFColor color)
{
XSSFConditionalFormattingRule rule = new XSSFConditionalFormattingRule(_sheet);
// Have it setup, with suitable defaults
rule.CreateDataBarFormatting(color);
// All done!
return rule;
}
public IConditionalFormattingRule CreateConditionalFormattingRule(ExtendedColor color)
{
return CreateConditionalFormattingRule((XSSFColor)color);
}
/**
* Create a Color Scale / Color Gradient conditional formatting rule.
* <p>The thresholds and colours for it will be created, but will be
* empty and require configuring with
* {@link XSSFConditionalFormattingRule#getColorScaleFormatting()}
* then
* {@link XSSFColorScaleFormatting#getThresholds()}
* and
* {@link XSSFColorScaleFormatting#getColors()}
*/
public IConditionalFormattingRule CreateConditionalFormattingColorScaleRule()
{
XSSFConditionalFormattingRule rule = new XSSFConditionalFormattingRule(_sheet);
// Have it setup, with suitable defaults
rule.CreateColorScaleFormatting();
// All done!
return rule;
}
public int AddConditionalFormatting(CellRangeAddress[] regions, IConditionalFormattingRule[] cfRules)
{
if (regions == null)
{
throw new ArgumentException("regions must not be null");
}
foreach (CellRangeAddress range in regions) range.Validate(SpreadsheetVersion.EXCEL2007);
if (cfRules == null)
{
throw new ArgumentException("cfRules must not be null");
}
if (cfRules.Length == 0)
{
throw new ArgumentException("cfRules must not be empty");
}
if (cfRules.Length > 3)
{
throw new ArgumentException("Number of rules must not exceed 3");
}
CellRangeAddress[] mergeCellRanges = CellRangeUtil.MergeCellRanges(regions);
CT_ConditionalFormatting cf = _sheet.GetCTWorksheet().AddNewConditionalFormatting();
string refs = string.Empty;
foreach (CellRangeAddress a in mergeCellRanges)
{
if (refs.Length == 0)
refs = a.FormatAsString();
else
refs += " " +a.FormatAsString() ;
}
cf.sqref = refs;
int priority = 1;
foreach (CT_ConditionalFormatting c in _sheet.GetCTWorksheet().conditionalFormatting)
{
priority += c.sizeOfCfRuleArray();
}
foreach (IConditionalFormattingRule rule in cfRules)
{
XSSFConditionalFormattingRule xRule = (XSSFConditionalFormattingRule)rule;
xRule.GetCTCfRule().priority = (priority++);
cf.AddNewCfRule().Set(xRule.GetCTCfRule());
}
return _sheet.GetCTWorksheet().SizeOfConditionalFormattingArray() - 1;
}
public int AddConditionalFormatting(CellRangeAddress[] regions,
IConditionalFormattingRule rule1)
{
return AddConditionalFormatting(regions,
rule1 == null ? null : new XSSFConditionalFormattingRule[] {
(XSSFConditionalFormattingRule)rule1
});
}
public int AddConditionalFormatting(CellRangeAddress[] regions,
IConditionalFormattingRule rule1, IConditionalFormattingRule rule2)
{
return AddConditionalFormatting(regions,
rule1 == null ? null : new XSSFConditionalFormattingRule[] {
(XSSFConditionalFormattingRule)rule1,
(XSSFConditionalFormattingRule)rule2
});
}
/**
* Adds a copy of HSSFConditionalFormatting object to the sheet
* <p>This method could be used to copy HSSFConditionalFormatting object
* from one sheet to another. For example:
* <pre>
* HSSFConditionalFormatting cf = sheet.GetConditionalFormattingAt(index);
* newSheet.AddConditionalFormatting(cf);
* </pre>
*
* @param cf HSSFConditionalFormatting object
* @return index of the new Conditional Formatting object
*/
public int AddConditionalFormatting(IConditionalFormatting cf)
{
XSSFConditionalFormatting xcf = (XSSFConditionalFormatting)cf;
CT_Worksheet sh = _sheet.GetCTWorksheet();
sh.AddNewConditionalFormatting().Set(xcf.GetCTConditionalFormatting());//this is already copied in Set -> .Copy()); ommitted
return sh.SizeOfConditionalFormattingArray() - 1;
}
/**
* Gets Conditional Formatting object at a particular index
*
* @param index
* of the Conditional Formatting object to fetch
* @return Conditional Formatting object
*/
public IConditionalFormatting GetConditionalFormattingAt(int index)
{
CheckIndex(index);
CT_ConditionalFormatting cf = _sheet.GetCTWorksheet().GetConditionalFormattingArray(index);
return new XSSFConditionalFormatting(_sheet, cf);
}
/**
* @return number of Conditional Formatting objects of the sheet
*/
public int NumConditionalFormattings
{
get
{
return _sheet.GetCTWorksheet().SizeOfConditionalFormattingArray();
}
}
/**
* Removes a Conditional Formatting object by index
* @param index of a Conditional Formatting object to remove
*/
public void RemoveConditionalFormatting(int index)
{
CheckIndex(index);
_sheet.GetCTWorksheet().conditionalFormatting.RemoveAt(index);
}
private void CheckIndex(int index)
{
int cnt = NumConditionalFormattings;
if (index < 0 || index >= cnt)
{
throw new ArgumentException("Specified CF index " + index
+ " is outside the allowable range (0.." + (cnt - 1) + ")");
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: supply/rpc/pricing_override_svc.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 HOLMS.Types.Supply.RPC {
/// <summary>Holder for reflection information generated from supply/rpc/pricing_override_svc.proto</summary>
public static partial class PricingOverrideSvcReflection {
#region Descriptor
/// <summary>File descriptor for supply/rpc/pricing_override_svc.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static PricingOverrideSvcReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiVzdXBwbHkvcnBjL3ByaWNpbmdfb3ZlcnJpZGVfc3ZjLnByb3RvEhZob2xt",
"cy50eXBlcy5zdXBwbHkucnBjGipwcmltaXRpdmUvcGJfaW5jbHVzaXZlX29w",
"c2RhdGVfcmFuZ2UucHJvdG8aHXByaW1pdGl2ZS9wYl9sb2NhbF9kYXRlLnBy",
"b3RvGh9wcmltaXRpdmUvbW9uZXRhcnlfYW1vdW50LnByb3RvGitzdXBwbHkv",
"cm9vbV90eXBlcy9yb29tX3R5cGVfaW5kaWNhdG9yLnByb3RvIlsKFVByaWNp",
"bmdEZXRhaWxzUmVxdWVzdBJCCgpkYXRlX3JhbmdlGAEgASgLMi4uaG9sbXMu",
"dHlwZXMucHJpbWl0aXZlLlBiSW5jbHVzaXZlT3BzZGF0ZVJhbmdlIscBCg9P",
"dmVycmlkZVByaWNpbmcSQwoJcm9vbV90eXBlGAEgASgLMjAuaG9sbXMudHlw",
"ZXMuc3VwcGx5LnJvb21fdHlwZXMuUm9vbVR5cGVJbmRpY2F0b3ISMAoEZGF0",
"ZRgCIAEoCzIiLmhvbG1zLnR5cGVzLnByaW1pdGl2ZS5QYkxvY2FsRGF0ZRI9",
"Cg5vdmVycmlkZV9wcmljZRgDIAEoCzIlLmhvbG1zLnR5cGVzLnByaW1pdGl2",
"ZS5Nb25ldGFyeUFtb3VudCJHChNSZW1vdmVPdmVycmlkZURhdGVzEjAKBGRh",
"dGUYASABKAsyIi5ob2xtcy50eXBlcy5wcmltaXRpdmUuUGJMb2NhbERhdGUi",
"ngEKFFByaWNpbmdVcGRhdGVSZXF1ZXN0EkEKEG92ZXJyaWRlX3ByaWNpbmcY",
"ASADKAsyJy5ob2xtcy50eXBlcy5zdXBwbHkucnBjLk92ZXJyaWRlUHJpY2lu",
"ZxJDCg5yZW1vdmVfcHJpY2luZxgCIAMoCzIrLmhvbG1zLnR5cGVzLnN1cHBs",
"eS5ycGMuUmVtb3ZlT3ZlcnJpZGVEYXRlcyJrChVQcmljaW5nVXBkYXRlUmVz",
"cG9uc2USOwoGUmVzdWx0GAEgASgOMisuaG9sbXMudHlwZXMuc3VwcGx5LnJw",
"Yy5QcmljaW5nVXBkYXRlUmVzdWx0EhUKDUVycm9yTWVzc2FnZXMYAiADKAki",
"WwoWUHJpY2luZ0RldGFpbHNSZXNwb25zZRJBChBvdmVycmlkZV9wcmljaW5n",
"GAEgAygLMicuaG9sbXMudHlwZXMuc3VwcGx5LnJwYy5PdmVycmlkZVByaWNp",
"bmcqWAoTUHJpY2luZ1VwZGF0ZVJlc3VsdBIRCg1VUERBVEVfRkFJTEVEEAAS",
"FwoTREJfVVBEQVRFX0NSX0ZBSUxFRBABEhUKEVVQREFURV9TVUNDRVNTRlVM",
"EAIy9wEKElByaWNpbmdPdmVycmlkZVN2YxJsCgtBbGxGb3JEYXRlcxItLmhv",
"bG1zLnR5cGVzLnN1cHBseS5ycGMuUHJpY2luZ0RldGFpbHNSZXF1ZXN0Gi4u",
"aG9sbXMudHlwZXMuc3VwcGx5LnJwYy5QcmljaW5nRGV0YWlsc1Jlc3BvbnNl",
"EnMKFEluc2VydE9yVXBkYXRlUHJpY2VzEiwuaG9sbXMudHlwZXMuc3VwcGx5",
"LnJwYy5QcmljaW5nVXBkYXRlUmVxdWVzdBotLmhvbG1zLnR5cGVzLnN1cHBs",
"eS5ycGMuUHJpY2luZ1VwZGF0ZVJlc3BvbnNlQiVaCnN1cHBseS9ycGOqAhZI",
"T0xNUy5UeXBlcy5TdXBwbHkuUlBDYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.PbInclusiveOpsdateRangeReflection.Descriptor, global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor, global::HOLMS.Types.Primitive.MonetaryAmountReflection.Descriptor, global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicatorReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::HOLMS.Types.Supply.RPC.PricingUpdateResult), }, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.RPC.PricingDetailsRequest), global::HOLMS.Types.Supply.RPC.PricingDetailsRequest.Parser, new[]{ "DateRange" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.RPC.OverridePricing), global::HOLMS.Types.Supply.RPC.OverridePricing.Parser, new[]{ "RoomType", "Date", "OverridePrice" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.RPC.RemoveOverrideDates), global::HOLMS.Types.Supply.RPC.RemoveOverrideDates.Parser, new[]{ "Date" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.RPC.PricingUpdateRequest), global::HOLMS.Types.Supply.RPC.PricingUpdateRequest.Parser, new[]{ "OverridePricing", "RemovePricing" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.RPC.PricingUpdateResponse), global::HOLMS.Types.Supply.RPC.PricingUpdateResponse.Parser, new[]{ "Result", "ErrorMessages" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.RPC.PricingDetailsResponse), global::HOLMS.Types.Supply.RPC.PricingDetailsResponse.Parser, new[]{ "OverridePricing" }, null, null, null)
}));
}
#endregion
}
#region Enums
public enum PricingUpdateResult {
[pbr::OriginalName("UPDATE_FAILED")] UpdateFailed = 0,
[pbr::OriginalName("DB_UPDATE_CR_FAILED")] DbUpdateCrFailed = 1,
[pbr::OriginalName("UPDATE_SUCCESSFUL")] UpdateSuccessful = 2,
}
#endregion
#region Messages
public sealed partial class PricingDetailsRequest : pb::IMessage<PricingDetailsRequest> {
private static readonly pb::MessageParser<PricingDetailsRequest> _parser = new pb::MessageParser<PricingDetailsRequest>(() => new PricingDetailsRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PricingDetailsRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Supply.RPC.PricingOverrideSvcReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PricingDetailsRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PricingDetailsRequest(PricingDetailsRequest other) : this() {
DateRange = other.dateRange_ != null ? other.DateRange.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PricingDetailsRequest Clone() {
return new PricingDetailsRequest(this);
}
/// <summary>Field number for the "date_range" field.</summary>
public const int DateRangeFieldNumber = 1;
private global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange dateRange_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange DateRange {
get { return dateRange_; }
set {
dateRange_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PricingDetailsRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PricingDetailsRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(DateRange, other.DateRange)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (dateRange_ != null) hash ^= DateRange.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 (dateRange_ != null) {
output.WriteRawTag(10);
output.WriteMessage(DateRange);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (dateRange_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(DateRange);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PricingDetailsRequest other) {
if (other == null) {
return;
}
if (other.dateRange_ != null) {
if (dateRange_ == null) {
dateRange_ = new global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange();
}
DateRange.MergeFrom(other.DateRange);
}
}
[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: {
if (dateRange_ == null) {
dateRange_ = new global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange();
}
input.ReadMessage(dateRange_);
break;
}
}
}
}
}
public sealed partial class OverridePricing : pb::IMessage<OverridePricing> {
private static readonly pb::MessageParser<OverridePricing> _parser = new pb::MessageParser<OverridePricing>(() => new OverridePricing());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<OverridePricing> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Supply.RPC.PricingOverrideSvcReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public OverridePricing() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public OverridePricing(OverridePricing other) : this() {
RoomType = other.roomType_ != null ? other.RoomType.Clone() : null;
Date = other.date_ != null ? other.Date.Clone() : null;
OverridePrice = other.overridePrice_ != null ? other.OverridePrice.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public OverridePricing Clone() {
return new OverridePricing(this);
}
/// <summary>Field number for the "room_type" field.</summary>
public const int RoomTypeFieldNumber = 1;
private global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator roomType_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator RoomType {
get { return roomType_; }
set {
roomType_ = value;
}
}
/// <summary>Field number for the "date" field.</summary>
public const int DateFieldNumber = 2;
private global::HOLMS.Types.Primitive.PbLocalDate date_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.PbLocalDate Date {
get { return date_; }
set {
date_ = value;
}
}
/// <summary>Field number for the "override_price" field.</summary>
public const int OverridePriceFieldNumber = 3;
private global::HOLMS.Types.Primitive.MonetaryAmount overridePrice_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.MonetaryAmount OverridePrice {
get { return overridePrice_; }
set {
overridePrice_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as OverridePricing);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(OverridePricing other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(RoomType, other.RoomType)) return false;
if (!object.Equals(Date, other.Date)) return false;
if (!object.Equals(OverridePrice, other.OverridePrice)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (roomType_ != null) hash ^= RoomType.GetHashCode();
if (date_ != null) hash ^= Date.GetHashCode();
if (overridePrice_ != null) hash ^= OverridePrice.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 (roomType_ != null) {
output.WriteRawTag(10);
output.WriteMessage(RoomType);
}
if (date_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Date);
}
if (overridePrice_ != null) {
output.WriteRawTag(26);
output.WriteMessage(OverridePrice);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (roomType_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(RoomType);
}
if (date_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Date);
}
if (overridePrice_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(OverridePrice);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(OverridePricing other) {
if (other == null) {
return;
}
if (other.roomType_ != null) {
if (roomType_ == null) {
roomType_ = new global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator();
}
RoomType.MergeFrom(other.RoomType);
}
if (other.date_ != null) {
if (date_ == null) {
date_ = new global::HOLMS.Types.Primitive.PbLocalDate();
}
Date.MergeFrom(other.Date);
}
if (other.overridePrice_ != null) {
if (overridePrice_ == null) {
overridePrice_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
OverridePrice.MergeFrom(other.OverridePrice);
}
}
[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: {
if (roomType_ == null) {
roomType_ = new global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator();
}
input.ReadMessage(roomType_);
break;
}
case 18: {
if (date_ == null) {
date_ = new global::HOLMS.Types.Primitive.PbLocalDate();
}
input.ReadMessage(date_);
break;
}
case 26: {
if (overridePrice_ == null) {
overridePrice_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
input.ReadMessage(overridePrice_);
break;
}
}
}
}
}
public sealed partial class RemoveOverrideDates : pb::IMessage<RemoveOverrideDates> {
private static readonly pb::MessageParser<RemoveOverrideDates> _parser = new pb::MessageParser<RemoveOverrideDates>(() => new RemoveOverrideDates());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<RemoveOverrideDates> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Supply.RPC.PricingOverrideSvcReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RemoveOverrideDates() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RemoveOverrideDates(RemoveOverrideDates other) : this() {
Date = other.date_ != null ? other.Date.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RemoveOverrideDates Clone() {
return new RemoveOverrideDates(this);
}
/// <summary>Field number for the "date" field.</summary>
public const int DateFieldNumber = 1;
private global::HOLMS.Types.Primitive.PbLocalDate date_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.PbLocalDate Date {
get { return date_; }
set {
date_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as RemoveOverrideDates);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(RemoveOverrideDates other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Date, other.Date)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (date_ != null) hash ^= Date.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 (date_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Date);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (date_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Date);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(RemoveOverrideDates other) {
if (other == null) {
return;
}
if (other.date_ != null) {
if (date_ == null) {
date_ = new global::HOLMS.Types.Primitive.PbLocalDate();
}
Date.MergeFrom(other.Date);
}
}
[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: {
if (date_ == null) {
date_ = new global::HOLMS.Types.Primitive.PbLocalDate();
}
input.ReadMessage(date_);
break;
}
}
}
}
}
public sealed partial class PricingUpdateRequest : pb::IMessage<PricingUpdateRequest> {
private static readonly pb::MessageParser<PricingUpdateRequest> _parser = new pb::MessageParser<PricingUpdateRequest>(() => new PricingUpdateRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PricingUpdateRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Supply.RPC.PricingOverrideSvcReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PricingUpdateRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PricingUpdateRequest(PricingUpdateRequest other) : this() {
overridePricing_ = other.overridePricing_.Clone();
removePricing_ = other.removePricing_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PricingUpdateRequest Clone() {
return new PricingUpdateRequest(this);
}
/// <summary>Field number for the "override_pricing" field.</summary>
public const int OverridePricingFieldNumber = 1;
private static readonly pb::FieldCodec<global::HOLMS.Types.Supply.RPC.OverridePricing> _repeated_overridePricing_codec
= pb::FieldCodec.ForMessage(10, global::HOLMS.Types.Supply.RPC.OverridePricing.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Supply.RPC.OverridePricing> overridePricing_ = new pbc::RepeatedField<global::HOLMS.Types.Supply.RPC.OverridePricing>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Supply.RPC.OverridePricing> OverridePricing {
get { return overridePricing_; }
}
/// <summary>Field number for the "remove_pricing" field.</summary>
public const int RemovePricingFieldNumber = 2;
private static readonly pb::FieldCodec<global::HOLMS.Types.Supply.RPC.RemoveOverrideDates> _repeated_removePricing_codec
= pb::FieldCodec.ForMessage(18, global::HOLMS.Types.Supply.RPC.RemoveOverrideDates.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Supply.RPC.RemoveOverrideDates> removePricing_ = new pbc::RepeatedField<global::HOLMS.Types.Supply.RPC.RemoveOverrideDates>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Supply.RPC.RemoveOverrideDates> RemovePricing {
get { return removePricing_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PricingUpdateRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PricingUpdateRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!overridePricing_.Equals(other.overridePricing_)) return false;
if(!removePricing_.Equals(other.removePricing_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= overridePricing_.GetHashCode();
hash ^= removePricing_.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) {
overridePricing_.WriteTo(output, _repeated_overridePricing_codec);
removePricing_.WriteTo(output, _repeated_removePricing_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += overridePricing_.CalculateSize(_repeated_overridePricing_codec);
size += removePricing_.CalculateSize(_repeated_removePricing_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PricingUpdateRequest other) {
if (other == null) {
return;
}
overridePricing_.Add(other.overridePricing_);
removePricing_.Add(other.removePricing_);
}
[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: {
overridePricing_.AddEntriesFrom(input, _repeated_overridePricing_codec);
break;
}
case 18: {
removePricing_.AddEntriesFrom(input, _repeated_removePricing_codec);
break;
}
}
}
}
}
public sealed partial class PricingUpdateResponse : pb::IMessage<PricingUpdateResponse> {
private static readonly pb::MessageParser<PricingUpdateResponse> _parser = new pb::MessageParser<PricingUpdateResponse>(() => new PricingUpdateResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PricingUpdateResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Supply.RPC.PricingOverrideSvcReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PricingUpdateResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PricingUpdateResponse(PricingUpdateResponse other) : this() {
result_ = other.result_;
errorMessages_ = other.errorMessages_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PricingUpdateResponse Clone() {
return new PricingUpdateResponse(this);
}
/// <summary>Field number for the "Result" field.</summary>
public const int ResultFieldNumber = 1;
private global::HOLMS.Types.Supply.RPC.PricingUpdateResult result_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Supply.RPC.PricingUpdateResult Result {
get { return result_; }
set {
result_ = value;
}
}
/// <summary>Field number for the "ErrorMessages" field.</summary>
public const int ErrorMessagesFieldNumber = 2;
private static readonly pb::FieldCodec<string> _repeated_errorMessages_codec
= pb::FieldCodec.ForString(18);
private readonly pbc::RepeatedField<string> errorMessages_ = new pbc::RepeatedField<string>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<string> ErrorMessages {
get { return errorMessages_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PricingUpdateResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PricingUpdateResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Result != other.Result) return false;
if(!errorMessages_.Equals(other.errorMessages_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Result != 0) hash ^= Result.GetHashCode();
hash ^= errorMessages_.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 (Result != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) Result);
}
errorMessages_.WriteTo(output, _repeated_errorMessages_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Result != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result);
}
size += errorMessages_.CalculateSize(_repeated_errorMessages_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PricingUpdateResponse other) {
if (other == null) {
return;
}
if (other.Result != 0) {
Result = other.Result;
}
errorMessages_.Add(other.errorMessages_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
result_ = (global::HOLMS.Types.Supply.RPC.PricingUpdateResult) input.ReadEnum();
break;
}
case 18: {
errorMessages_.AddEntriesFrom(input, _repeated_errorMessages_codec);
break;
}
}
}
}
}
public sealed partial class PricingDetailsResponse : pb::IMessage<PricingDetailsResponse> {
private static readonly pb::MessageParser<PricingDetailsResponse> _parser = new pb::MessageParser<PricingDetailsResponse>(() => new PricingDetailsResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PricingDetailsResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Supply.RPC.PricingOverrideSvcReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PricingDetailsResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PricingDetailsResponse(PricingDetailsResponse other) : this() {
overridePricing_ = other.overridePricing_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PricingDetailsResponse Clone() {
return new PricingDetailsResponse(this);
}
/// <summary>Field number for the "override_pricing" field.</summary>
public const int OverridePricingFieldNumber = 1;
private static readonly pb::FieldCodec<global::HOLMS.Types.Supply.RPC.OverridePricing> _repeated_overridePricing_codec
= pb::FieldCodec.ForMessage(10, global::HOLMS.Types.Supply.RPC.OverridePricing.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Supply.RPC.OverridePricing> overridePricing_ = new pbc::RepeatedField<global::HOLMS.Types.Supply.RPC.OverridePricing>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Supply.RPC.OverridePricing> OverridePricing {
get { return overridePricing_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PricingDetailsResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PricingDetailsResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!overridePricing_.Equals(other.overridePricing_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= overridePricing_.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) {
overridePricing_.WriteTo(output, _repeated_overridePricing_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += overridePricing_.CalculateSize(_repeated_overridePricing_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PricingDetailsResponse other) {
if (other == null) {
return;
}
overridePricing_.Add(other.overridePricing_);
}
[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: {
overridePricing_.AddEntriesFrom(input, _repeated_overridePricing_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// 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.
//Test is checking the ReserveSlot function
// If someone screws up the function we will end up
// setting values in the wrong slots and the totals will be wrong
using System;
using System.Threading;
public class Value0
{
[ThreadStatic]
private static object One= 1;
[ThreadStatic]
private static object Two= 2;
[ThreadStatic]
private static object Three= 3;
[ThreadStatic]
private static object Four= 4;
[ThreadStatic]
private static object Five= 5;
[ThreadStatic]
private static object Six= 6;
[ThreadStatic]
private static object Seven= 7;
[ThreadStatic]
private static object Eight= 8;
[ThreadStatic]
private static object Nine= 9;
[ThreadStatic]
private static object Ten= 10;
[ThreadStatic]
private static object Eleven= 11;
[ThreadStatic]
private static object Twelve= 12;
[ThreadStatic]
private static object Thirteen= 13;
[ThreadStatic]
private static object Fourteen= 14;
[ThreadStatic]
private static object Fifteen= 15;
[ThreadStatic]
private static object Sixteen= 16;
[ThreadStatic]
private static object Seventeen= 17;
[ThreadStatic]
private static object Eightteen= 18;
[ThreadStatic]
private static object Nineteen= 19;
[ThreadStatic]
private static object Twenty= 20;
[ThreadStatic]
private static object TwentyOne= 21;
[ThreadStatic]
private static object TwentyTwo= 22;
[ThreadStatic]
private static object TwentyThree= 23;
[ThreadStatic]
private static object TwentyFour= 24;
[ThreadStatic]
private static object TwentyFive= 25;
[ThreadStatic]
private static object TwentySix= 26;
[ThreadStatic]
private static object TwentySeven= 27;
[ThreadStatic]
private static object TwentyEight= 28;
[ThreadStatic]
private static object TwentyNine= 29;
[ThreadStatic]
private static object Thirty= 30;
[ThreadStatic]
private static object ThirtyOne= 31;
[ThreadStatic]
private static object ThirtyTwo= 32;
public bool CheckValues()
{
if((int)ThirtyTwo != 32)
{
Console.WriteLine("ThirtySecond spot was incorrect!!!");
return false;
}
int value = 0;
value = (int)One
+ (int)Two
+ (int)Three
+ (int)Four
+ (int)Five
+ (int)Six
+ (int)Seven
+ (int)Eight
+ (int)Nine
+ (int)Ten
+ (int)Eleven
+ (int)Twelve
+ (int)Thirteen
+ (int)Fourteen
+ (int)Fifteen
+ (int)Sixteen
+ (int)Seventeen
+ (int)Eightteen
+ (int)Nineteen
+ (int)Twenty
+ (int)TwentyOne
+ (int)TwentyTwo
+ (int)TwentyThree
+ (int)TwentyFour
+ (int)TwentyFive
+ (int)TwentySix
+ (int)TwentySeven
+ (int)TwentyEight
+ (int)TwentyNine
+ (int)Thirty
+ (int)ThirtyOne
+ (int)ThirtyTwo;
if(value != 528)
{
Console.WriteLine("Value0 - Wrong values in ThreadStatics!!! {0}",value);
return false;
}
return true;
}
}
public class Value1
{
[ThreadStatic]
private static object One= 1;
[ThreadStatic]
private static object Two= 2;
[ThreadStatic]
private static object Three= 3;
[ThreadStatic]
private static object Four= 4;
[ThreadStatic]
private static object Five= 5;
[ThreadStatic]
private static object Six= 6;
[ThreadStatic]
private static object Seven= 7;
[ThreadStatic]
private static object Eight= 8;
[ThreadStatic]
private static object Nine= 9;
[ThreadStatic]
private static object Ten= 10;
[ThreadStatic]
private static object Eleven= 11;
[ThreadStatic]
private static object Twelve= 12;
[ThreadStatic]
private static object Thirteen= 13;
[ThreadStatic]
private static object Fourteen= 14;
[ThreadStatic]
private static object Fifteen= 15;
[ThreadStatic]
private static object Sixteen= 16;
[ThreadStatic]
private static object Seventeen= 17;
[ThreadStatic]
private static object Eightteen= 18;
[ThreadStatic]
private static object Nineteen= 19;
[ThreadStatic]
private static object Twenty= 20;
[ThreadStatic]
private static object TwentyOne= 21;
[ThreadStatic]
private static object TwentyTwo= 22;
[ThreadStatic]
private static object TwentyThree= 23;
[ThreadStatic]
private static object TwentyFour= 24;
[ThreadStatic]
private static object TwentyFive= 25;
[ThreadStatic]
private static object TwentySix= 26;
[ThreadStatic]
private static object TwentySeven= 27;
[ThreadStatic]
private static object TwentyEight= 28;
[ThreadStatic]
private static object TwentyNine= 29;
[ThreadStatic]
private static object Thirty= 30;
[ThreadStatic]
private static object ThirtyOne= 31;
[ThreadStatic]
private static object ThirtyTwo= 32;
public bool CheckValues()
{
if((int)ThirtyTwo != 32)
{
Console.WriteLine("ThirtySecond spot was incorrect!!!");
return false;
}
int value = 0;
value = (int)One
+ (int)Two
+ (int)Three
+ (int)Four
+ (int)Five
+ (int)Six
+ (int)Seven
+ (int)Eight
+ (int)Nine
+ (int)Ten
+ (int)Eleven
+ (int)Twelve
+ (int)Thirteen
+ (int)Fourteen
+ (int)Fifteen
+ (int)Sixteen
+ (int)Seventeen
+ (int)Eightteen
+ (int)Nineteen
+ (int)Twenty
+ (int)TwentyOne
+ (int)TwentyTwo
+ (int)TwentyThree
+ (int)TwentyFour
+ (int)TwentyFive
+ (int)TwentySix
+ (int)TwentySeven
+ (int)TwentyEight
+ (int)TwentyNine
+ (int)Thirty
+ (int)ThirtyOne
+ (int)ThirtyTwo;
if(value != 528)
{
Console.WriteLine("Value1 - Wrong values in ThreadStatics!!! {0}",value);
return false;
}
return true;
}
}
public class Value2
{
[ThreadStatic]
private static object One= 1;
[ThreadStatic]
private static object Two= 2;
[ThreadStatic]
private static object Three= 3;
[ThreadStatic]
private static object Four= 4;
[ThreadStatic]
private static object Five= 5;
[ThreadStatic]
private static object Six= 6;
[ThreadStatic]
private static object Seven= 7;
[ThreadStatic]
private static object Eight= 8;
[ThreadStatic]
private static object Nine= 9;
[ThreadStatic]
private static object Ten= 10;
[ThreadStatic]
private static object Eleven= 11;
[ThreadStatic]
private static object Twelve= 12;
[ThreadStatic]
private static object Thirteen= 13;
[ThreadStatic]
private static object Fourteen= 14;
[ThreadStatic]
private static object Fifteen= 15;
[ThreadStatic]
private static object Sixteen= 16;
[ThreadStatic]
private static object Seventeen= 17;
[ThreadStatic]
private static object Eightteen= 18;
[ThreadStatic]
private static object Nineteen= 19;
[ThreadStatic]
private static object Twenty= 20;
[ThreadStatic]
private static object TwentyOne= 21;
[ThreadStatic]
private static object TwentyTwo= 22;
[ThreadStatic]
private static object TwentyThree= 23;
[ThreadStatic]
private static object TwentyFour= 24;
[ThreadStatic]
private static object TwentyFive= 25;
[ThreadStatic]
private static object TwentySix= 26;
[ThreadStatic]
private static object TwentySeven= 27;
[ThreadStatic]
private static object TwentyEight= 28;
[ThreadStatic]
private static object TwentyNine= 29;
[ThreadStatic]
private static object Thirty= 30;
[ThreadStatic]
private static object ThirtyOne= 31;
[ThreadStatic]
private static object ThirtyTwo= 32;
public bool CheckValues()
{
if((int)ThirtyTwo != 32)
{
Console.WriteLine("Value2 - ThirtySecond spot was incorrect!!!");
return false;
}
int value = 0;
value = (int)One
+ (int)Two
+ (int)Three
+ (int)Four
+ (int)Five
+ (int)Six
+ (int)Seven
+ (int)Eight
+ (int)Nine
+ (int)Ten
+ (int)Eleven
+ (int)Twelve
+ (int)Thirteen
+ (int)Fourteen
+ (int)Fifteen
+ (int)Sixteen
+ (int)Seventeen
+ (int)Eightteen
+ (int)Nineteen
+ (int)Twenty
+ (int)TwentyOne
+ (int)TwentyTwo
+ (int)TwentyThree
+ (int)TwentyFour
+ (int)TwentyFive
+ (int)TwentySix
+ (int)TwentySeven
+ (int)TwentyEight
+ (int)TwentyNine
+ (int)Thirty
+ (int)ThirtyOne
+ (int)ThirtyTwo;
if(value != 528)
{
Console.WriteLine("Wrong values in ThreadStatics!!! {0}",value);
return false;
}
return true;
}
}
public class Value3
{
[ThreadStatic]
private static object One= 1;
[ThreadStatic]
private static object Two= 2;
[ThreadStatic]
private static object Three= 3;
[ThreadStatic]
private static object Four= 4;
[ThreadStatic]
private static object Five= 5;
[ThreadStatic]
private static object Six= 6;
[ThreadStatic]
private static object Seven= 7;
[ThreadStatic]
private static object Eight= 8;
[ThreadStatic]
private static object Nine= 9;
[ThreadStatic]
private static object Ten= 10;
[ThreadStatic]
private static object Eleven= 11;
[ThreadStatic]
private static object Twelve= 12;
[ThreadStatic]
private static object Thirteen= 13;
[ThreadStatic]
private static object Fourteen= 14;
[ThreadStatic]
private static object Fifteen= 15;
[ThreadStatic]
private static object Sixteen= 16;
[ThreadStatic]
private static object Seventeen= 17;
[ThreadStatic]
private static object Eightteen= 18;
[ThreadStatic]
private static object Nineteen= 19;
[ThreadStatic]
private static object Twenty= 20;
[ThreadStatic]
private static object TwentyOne= 21;
[ThreadStatic]
private static object TwentyTwo= 22;
[ThreadStatic]
private static object TwentyThree= 23;
[ThreadStatic]
private static object TwentyFour= 24;
[ThreadStatic]
private static object TwentyFive= 25;
[ThreadStatic]
private static object TwentySix= 26;
[ThreadStatic]
private static object TwentySeven= 27;
[ThreadStatic]
private static object TwentyEight= 28;
[ThreadStatic]
private static object TwentyNine= 29;
[ThreadStatic]
private static object Thirty= 30;
[ThreadStatic]
private static object ThirtyOne= 31;
[ThreadStatic]
private static object ThirtyTwo= 32;
public bool CheckValues()
{
if((int)ThirtyTwo != 32)
{
Console.WriteLine("Value2 - ThirtySecond spot was incorrect!!!");
return false;
}
int value = 0;
value = (int)One
+ (int)Two
+ (int)Three
+ (int)Four
+ (int)Five
+ (int)Six
+ (int)Seven
+ (int)Eight
+ (int)Nine
+ (int)Ten
+ (int)Eleven
+ (int)Twelve
+ (int)Thirteen
+ (int)Fourteen
+ (int)Fifteen
+ (int)Sixteen
+ (int)Seventeen
+ (int)Eightteen
+ (int)Nineteen
+ (int)Twenty
+ (int)TwentyOne
+ (int)TwentyTwo
+ (int)TwentyThree
+ (int)TwentyFour
+ (int)TwentyFive
+ (int)TwentySix
+ (int)TwentySeven
+ (int)TwentyEight
+ (int)TwentyNine
+ (int)Thirty
+ (int)ThirtyOne
+ (int)ThirtyTwo;
if(value != 528)
{
Console.WriteLine("Wrong values in ThreadStatics!!! {0}",value);
return false;
}
return true;
}
}
public class Value4
{
[ThreadStatic]
private static object One= 1;
[ThreadStatic]
private static object Two= 2;
[ThreadStatic]
private static object Three= 3;
[ThreadStatic]
private static object Four= 4;
[ThreadStatic]
private static object Five= 5;
[ThreadStatic]
private static object Six= 6;
[ThreadStatic]
private static object Seven= 7;
[ThreadStatic]
private static object Eight= 8;
[ThreadStatic]
private static object Nine= 9;
[ThreadStatic]
private static object Ten= 10;
[ThreadStatic]
private static object Eleven= 11;
[ThreadStatic]
private static object Twelve= 12;
[ThreadStatic]
private static object Thirteen= 13;
[ThreadStatic]
private static object Fourteen= 14;
[ThreadStatic]
private static object Fifteen= 15;
[ThreadStatic]
private static object Sixteen= 16;
[ThreadStatic]
private static object Seventeen= 17;
[ThreadStatic]
private static object Eightteen= 18;
[ThreadStatic]
private static object Nineteen= 19;
[ThreadStatic]
private static object Twenty= 20;
[ThreadStatic]
private static object TwentyOne= 21;
[ThreadStatic]
private static object TwentyTwo= 22;
[ThreadStatic]
private static object TwentyThree= 23;
[ThreadStatic]
private static object TwentyFour= 24;
[ThreadStatic]
private static object TwentyFive= 25;
[ThreadStatic]
private static object TwentySix= 26;
[ThreadStatic]
private static object TwentySeven= 27;
[ThreadStatic]
private static object TwentyEight= 28;
[ThreadStatic]
private static object TwentyNine= 29;
[ThreadStatic]
private static object Thirty= 30;
[ThreadStatic]
private static object ThirtyOne= 31;
[ThreadStatic]
private static object ThirtyTwo= 32;
public bool CheckValues()
{
if((int)ThirtyTwo != 32)
{
Console.WriteLine("Value2 - ThirtySecond spot was incorrect!!!");
return false;
}
int value = 0;
value = (int)One
+ (int)Two
+ (int)Three
+ (int)Four
+ (int)Five
+ (int)Six
+ (int)Seven
+ (int)Eight
+ (int)Nine
+ (int)Ten
+ (int)Eleven
+ (int)Twelve
+ (int)Thirteen
+ (int)Fourteen
+ (int)Fifteen
+ (int)Sixteen
+ (int)Seventeen
+ (int)Eightteen
+ (int)Nineteen
+ (int)Twenty
+ (int)TwentyOne
+ (int)TwentyTwo
+ (int)TwentyThree
+ (int)TwentyFour
+ (int)TwentyFive
+ (int)TwentySix
+ (int)TwentySeven
+ (int)TwentyEight
+ (int)TwentyNine
+ (int)Thirty
+ (int)ThirtyOne
+ (int)ThirtyTwo;
if(value != 528)
{
Console.WriteLine("Wrong values in ThreadStatics!!! {0}",value);
return false;
}
return true;
}
}
public class Value5
{
[ThreadStatic]
private static object One= 1;
[ThreadStatic]
private static object Two= 2;
[ThreadStatic]
private static object Three= 3;
[ThreadStatic]
private static object Four= 4;
[ThreadStatic]
private static object Five= 5;
[ThreadStatic]
private static object Six= 6;
[ThreadStatic]
private static object Seven= 7;
[ThreadStatic]
private static object Eight= 8;
[ThreadStatic]
private static object Nine= 9;
[ThreadStatic]
private static object Ten= 10;
[ThreadStatic]
private static object Eleven= 11;
[ThreadStatic]
private static object Twelve= 12;
[ThreadStatic]
private static object Thirteen= 13;
[ThreadStatic]
private static object Fourteen= 14;
[ThreadStatic]
private static object Fifteen= 15;
[ThreadStatic]
private static object Sixteen= 16;
[ThreadStatic]
private static object Seventeen= 17;
[ThreadStatic]
private static object Eightteen= 18;
[ThreadStatic]
private static object Nineteen= 19;
[ThreadStatic]
private static object Twenty= 20;
[ThreadStatic]
private static object TwentyOne= 21;
[ThreadStatic]
private static object TwentyTwo= 22;
[ThreadStatic]
private static object TwentyThree= 23;
[ThreadStatic]
private static object TwentyFour= 24;
[ThreadStatic]
private static object TwentyFive= 25;
[ThreadStatic]
private static object TwentySix= 26;
[ThreadStatic]
private static object TwentySeven= 27;
[ThreadStatic]
private static object TwentyEight= 28;
[ThreadStatic]
private static object TwentyNine= 29;
[ThreadStatic]
private static object Thirty= 30;
[ThreadStatic]
private static object ThirtyOne= 31;
[ThreadStatic]
private static object ThirtyTwo= 32;
public bool CheckValues()
{
if((int)ThirtyTwo != 32)
{
Console.WriteLine("Value2 - ThirtySecond spot was incorrect!!!");
return false;
}
int value = 0;
value = (int)One
+ (int)Two
+ (int)Three
+ (int)Four
+ (int)Five
+ (int)Six
+ (int)Seven
+ (int)Eight
+ (int)Nine
+ (int)Ten
+ (int)Eleven
+ (int)Twelve
+ (int)Thirteen
+ (int)Fourteen
+ (int)Fifteen
+ (int)Sixteen
+ (int)Seventeen
+ (int)Eightteen
+ (int)Nineteen
+ (int)Twenty
+ (int)TwentyOne
+ (int)TwentyTwo
+ (int)TwentyThree
+ (int)TwentyFour
+ (int)TwentyFive
+ (int)TwentySix
+ (int)TwentySeven
+ (int)TwentyEight
+ (int)TwentyNine
+ (int)Thirty
+ (int)ThirtyOne
+ (int)ThirtyTwo;
if(value != 528)
{
Console.WriteLine("Wrong values in ThreadStatics!!! {0}",value);
return false;
}
return true;
}
}
public class MyData
{
public AutoResetEvent autoEvent;
[ThreadStatic]
private static Value0 v0;
[ThreadStatic]
private static Value1 v1;
[ThreadStatic]
private static Value2 v2;
[ThreadStatic]
private static Value3 v3;
[ThreadStatic]
private static Value4 v4;
[ThreadStatic]
private static Value5 v5;
public bool pass = false;
public void ThreadTarget()
{
autoEvent.WaitOne();
v0 = new Value0();
v1 = new Value1();
v2 = new Value2();
v3 = new Value3();
v4 = new Value4();
v5 = new Value5();
pass = v0.CheckValues()
&& v1.CheckValues()
&& v2.CheckValues()
&& v3.CheckValues()
&& v4.CheckValues()
&& v5.CheckValues();
}
}
public class Test
{
private int retVal = 0;
public static int Main()
{
Test staticsTest = new Test();
staticsTest.RunTest();
Console.WriteLine(100 == staticsTest.retVal ? "Test Passed":"Test Failed");
return staticsTest.retVal;
}
public void RunTest()
{
MyData data = new MyData();
data.autoEvent = new AutoResetEvent(false);
Thread t = new Thread(data.ThreadTarget);
t.Start();
if(!t.IsAlive)
{
Console.WriteLine("Thread was not set to Alive after starting");
retVal = 50;
return;
}
data.autoEvent.Set();
t.Join();
if(data.pass)
retVal = 100;
}
}
| |
// 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 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// SecurityRulesOperations operations.
/// </summary>
internal partial class SecurityRulesOperations : IServiceOperations<NetworkManagementClient>, ISecurityRulesOperations
{
/// <summary>
/// Initializes a new instance of the SecurityRulesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal SecurityRulesOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Deletes the specified network security rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get the specified network security rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<SecurityRule>> GetWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkSecurityGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName");
}
if (securityRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "securityRuleName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-09-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.Add("securityRuleName", securityRuleName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName));
_url = _url.Replace("{securityRuleName}", System.Uri.EscapeDataString(securityRuleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<SecurityRule>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SecurityRule>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a security rule in the specified network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create or update network security rule
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<SecurityRule>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<SecurityRule> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all security rules in a network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<SecurityRule>>> ListWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkSecurityGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-09-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<SecurityRule>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SecurityRule>>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified network security rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkSecurityGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName");
}
if (securityRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "securityRuleName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-09-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.Add("securityRuleName", securityRuleName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName));
_url = _url.Replace("{securityRuleName}", System.Uri.EscapeDataString(securityRuleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204 && (int)_statusCode != 202 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a security rule in the specified network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create or update network security rule
/// operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<SecurityRule>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkSecurityGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName");
}
if (securityRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "securityRuleName");
}
if (securityRuleParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "securityRuleParameters");
}
if (securityRuleParameters != null)
{
securityRuleParameters.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-09-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.Add("securityRuleName", securityRuleName);
tracingParameters.Add("securityRuleParameters", securityRuleParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName));
_url = _url.Replace("{securityRuleName}", System.Uri.EscapeDataString(securityRuleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(securityRuleParameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(securityRuleParameters, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<SecurityRule>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SecurityRule>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SecurityRule>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all security rules in a network security group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<SecurityRule>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<SecurityRule>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SecurityRule>>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
* Muhimbi PDF
*
* Convert, Merge, Watermark, Secure and OCR files.
*
* OpenAPI spec version: 9.15
*
* 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 Muhimbi.PDF.Online.Client.Client;
using Muhimbi.PDF.Online.Client.Model;
namespace Muhimbi.PDF.Online.Client.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface ISplitApi : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// Split PDF
/// </summary>
/// <remarks>
/// Split a PDF file into multiple PDFs.
/// </remarks>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>SplitOperationResponse</returns>
SplitOperationResponse SplitPdf (SplitPdfData inputData);
/// <summary>
/// Split PDF
/// </summary>
/// <remarks>
/// Split a PDF file into multiple PDFs.
/// </remarks>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>ApiResponse of SplitOperationResponse</returns>
ApiResponse<SplitOperationResponse> SplitPdfWithHttpInfo (SplitPdfData inputData);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Split PDF
/// </summary>
/// <remarks>
/// Split a PDF file into multiple PDFs.
/// </remarks>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>Task of SplitOperationResponse</returns>
System.Threading.Tasks.Task<SplitOperationResponse> SplitPdfAsync (SplitPdfData inputData);
/// <summary>
/// Split PDF
/// </summary>
/// <remarks>
/// Split a PDF file into multiple PDFs.
/// </remarks>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>Task of ApiResponse (SplitOperationResponse)</returns>
System.Threading.Tasks.Task<ApiResponse<SplitOperationResponse>> SplitPdfAsyncWithHttpInfo (SplitPdfData inputData);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class SplitApi : ISplitApi
{
private Muhimbi.PDF.Online.Client.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="SplitApi"/> class.
/// </summary>
/// <returns></returns>
public SplitApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
ExceptionFactory = Muhimbi.PDF.Online.Client.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="SplitApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public SplitApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
ExceptionFactory = Muhimbi.PDF.Online.Client.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
[Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")]
public void SetBasePath(String basePath)
{
// do nothing
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Configuration Configuration {get; set;}
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public Muhimbi.PDF.Online.Client.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>
/// Gets the default header.
/// </summary>
/// <returns>Dictionary of HTTP header</returns>
[Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")]
public Dictionary<String, String> DefaultHeader()
{
return this.Configuration.DefaultHeader;
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
[Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")]
public void AddDefaultHeader(string key, string value)
{
this.Configuration.AddDefaultHeader(key, value);
}
/// <summary>
/// Split PDF Split a PDF file into multiple PDFs.
/// </summary>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>SplitOperationResponse</returns>
public SplitOperationResponse SplitPdf (SplitPdfData inputData)
{
ApiResponse<SplitOperationResponse> localVarResponse = SplitPdfWithHttpInfo(inputData);
return localVarResponse.Data;
}
/// <summary>
/// Split PDF Split a PDF file into multiple PDFs.
/// </summary>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>ApiResponse of SplitOperationResponse</returns>
public ApiResponse< SplitOperationResponse > SplitPdfWithHttpInfo (SplitPdfData inputData)
{
// verify the required parameter 'inputData' is set
if (inputData == null)
throw new ApiException(400, "Missing required parameter 'inputData' when calling SplitApi->SplitPdf");
var localVarPath = "/v1/operations/split_pdf";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (inputData != null && inputData.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(inputData); // http body (model) parameter
}
else
{
localVarPostBody = inputData; // byte array
}
// authentication (oauth2_auth) required
// oauth required
if (!String.IsNullOrEmpty(Configuration.AccessToken))
{
localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken;
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("api_key")))
{
localVarHeaderParams["api_key"] = Configuration.GetApiKeyWithPrefix("api_key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("SplitPdf", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<SplitOperationResponse>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(SplitOperationResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(SplitOperationResponse)));
}
/// <summary>
/// Split PDF Split a PDF file into multiple PDFs.
/// </summary>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>Task of SplitOperationResponse</returns>
public async System.Threading.Tasks.Task<SplitOperationResponse> SplitPdfAsync (SplitPdfData inputData)
{
ApiResponse<SplitOperationResponse> localVarResponse = await SplitPdfAsyncWithHttpInfo(inputData);
return localVarResponse.Data;
}
/// <summary>
/// Split PDF Split a PDF file into multiple PDFs.
/// </summary>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>Task of ApiResponse (SplitOperationResponse)</returns>
public async System.Threading.Tasks.Task<ApiResponse<SplitOperationResponse>> SplitPdfAsyncWithHttpInfo (SplitPdfData inputData)
{
// verify the required parameter 'inputData' is set
if (inputData == null)
throw new ApiException(400, "Missing required parameter 'inputData' when calling SplitApi->SplitPdf");
var localVarPath = "/v1/operations/split_pdf";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (inputData != null && inputData.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(inputData); // http body (model) parameter
}
else
{
localVarPostBody = inputData; // byte array
}
// authentication (oauth2_auth) required
// oauth required
if (!String.IsNullOrEmpty(Configuration.AccessToken))
{
localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken;
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("api_key")))
{
localVarHeaderParams["api_key"] = Configuration.GetApiKeyWithPrefix("api_key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("SplitPdf", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<SplitOperationResponse>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(SplitOperationResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(SplitOperationResponse)));
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
/// <summary>
/// Task to help with resume able large file uploads.
/// </summary>
public class LargeFileUploadTask<T>
{
private const int DefaultMaxSliceSize = 4 * 1024 * 1024;
private const int RequiredSliceSizeIncrement = 320 * 1024;
private IUploadSession Session { get; set; }
private readonly IBaseClient _client;
private readonly Stream _uploadStream;
private readonly int _maxSliceSize;
private List<Tuple<long, long>> _rangesRemaining;
private long TotalUploadLength => _uploadStream.Length;
/// <summary>
/// Task to help with resume able large file uploads. Generates slices based on <paramref name="uploadSession"/>
/// information, and can control uploading of requests/>
/// </summary>
/// <param name="uploadSession">Session information of type <see cref="IUploadSession"/>></param>
/// <param name="uploadStream">Readable, seekable stream to be uploaded. Length of session is determined via uploadStream.Length</param>
/// <param name="maxSliceSize">Max size of each slice to be uploaded. Multiple of 320 KiB (320 * 1024) is required.</param>
/// <param name="baseClient"><see cref="IBaseClient"/> to use for making upload requests. The client should not set Auth headers as upload urls do not need them.
/// If less than 0, default value of 5 MiB is used. .</param>
public LargeFileUploadTask(IUploadSession uploadSession, Stream uploadStream, int maxSliceSize = -1, IBaseClient baseClient = null)
{
if (!uploadStream.CanRead || !uploadStream.CanSeek)
{
throw new ArgumentException("Must provide stream that can read and seek");
}
this.Session = uploadSession;
this._client = baseClient ?? this.InitializeClient(uploadSession.UploadUrl);
this._uploadStream = uploadStream;
this._rangesRemaining = this.GetRangesRemaining(uploadSession);
this._maxSliceSize = maxSliceSize < 0 ? DefaultMaxSliceSize : maxSliceSize;
if (this._maxSliceSize % RequiredSliceSizeIncrement != 0)
{
throw new ArgumentException("Max slice size must be a multiple of 320 KiB", nameof(maxSliceSize));
}
}
/// <summary>
/// Initialize a baseClient to use for the upload that does not have Auth enabled as the upload URLs explicitly do not need authentication.
/// </summary>
/// <param name="uploadUrl">Url to perform the upload to from the session</param>
/// <returns></returns>
private IBaseClient InitializeClient(string uploadUrl)
{
HttpClient httpClient = GraphClientFactory.Create(authenticationProvider: null); //no auth
httpClient.SetFeatureFlag(FeatureFlag.FileUploadTask);
return new BaseClient(uploadUrl, httpClient);
}
/// <summary>
/// Write a slice of data using the UploadSliceRequest.
/// </summary>
/// <param name="uploadSliceRequest">The UploadSliceRequest to make the request with.</param>
/// <param name="exceptionTrackingList">A list of exceptions to use to track progress. SlicedUpload may retry.</param>
private async Task<UploadResult<T>> UploadSliceAsync(UploadSliceRequest<T> uploadSliceRequest, ICollection<Exception> exceptionTrackingList)
{
var firstAttempt = true;
this._uploadStream.Seek(uploadSliceRequest.RangeBegin, SeekOrigin.Begin);
while (true)
{
using (var requestBodyStream = new ReadOnlySubStream(this._uploadStream, uploadSliceRequest.RangeBegin, uploadSliceRequest.RangeLength))
{
try
{
return await uploadSliceRequest.PutAsync(requestBodyStream).ConfigureAwait(false);
}
catch (ServiceException exception)
{
if (exception.IsMatch("generalException") || exception.IsMatch("timeout"))
{
if (firstAttempt)
{
firstAttempt = false;
exceptionTrackingList.Add(exception);
}
else
{
throw;
}
}
else if (exception.IsMatch("invalidRange"))
{
// Succeeded previously, but nothing to return right now
return new UploadResult<T>();
}
else
{
throw;
}
}
}
}
}
/// <summary>
/// Get the series of requests needed to complete the upload session. Call <see cref="UpdateSessionStatusAsync"/>
/// first to update the internal session information.
/// </summary>
/// <returns>All requests currently needed to complete the upload session.</returns>
internal IEnumerable<UploadSliceRequest<T>> GetUploadSliceRequests()
{
foreach (var (item1, item2) in this._rangesRemaining)
{
var currentRangeBegins = item1;
while (currentRangeBegins <= item2)
{
var nextSliceSize = NextSliceSize(currentRangeBegins, item2);
var uploadRequest = new UploadSliceRequest<T>(
this.Session.UploadUrl,
this._client,
currentRangeBegins,
currentRangeBegins + nextSliceSize - 1,
this.TotalUploadLength);
yield return uploadRequest;
currentRangeBegins += nextSliceSize;
}
}
}
/// <summary>
/// Upload the whole session.
/// </summary>
/// <param name="maxTries">Number of times to retry entire session before giving up.</param>
/// <param name="progress">IProgress object to monitor the progress of the upload.</param>
/// <returns>Item information returned by server.</returns>
public async Task<UploadResult<T>> UploadAsync(IProgress<long> progress = null, int maxTries = 3)
{
var uploadTries = 0;
var trackedExceptions = new List<Exception>();
while (uploadTries < maxTries)
{
var sliceRequests = this.GetUploadSliceRequests();
foreach (var request in sliceRequests)
{
var uploadResult = await this.UploadSliceAsync(request, trackedExceptions).ConfigureAwait(false);
progress?.Report(request.RangeBegin);//report the progress of upload
if (uploadResult.UploadSucceeded)
{
return uploadResult;
}
}
await this.UpdateSessionStatusAsync().ConfigureAwait(false);
uploadTries += 1;
if (uploadTries < maxTries)
{
// Exponential back off in case of failures.
await Task.Delay(2000 * uploadTries * uploadTries).ConfigureAwait(false);
}
}
throw new TaskCanceledException("Upload failed too many times. See InnerException for list of exceptions that occured.", new AggregateException(trackedExceptions.ToArray()));
}
/// <summary>
/// Get info about the upload session and resume from where it left off.
/// </summary>
/// <param name="maxTries">Number of times to retry entire session before giving up.</param>
/// <param name="progress">IProgress object to monitor the progress of the upload.</param>
/// <returns>Item information returned by server.</returns>
public async Task<UploadResult<T>> ResumeAsync(IProgress<long> progress = null, int maxTries = 3)
{
var uploadSession = await this.UpdateSessionStatusAsync().ConfigureAwait(false);
var uploadExpirationTime = uploadSession.ExpirationDateTime ?? DateTimeOffset.Now;
// validate that the upload can still be resumed.
if (DateTimeOffset.Compare(uploadExpirationTime, DateTimeOffset.Now) <= 0)
{
throw new ClientException(
new Error
{
Code = ErrorConstants.Codes.Timeout,
Message = ErrorConstants.Messages.ExpiredUploadSession
});
}
return await this.UploadAsync(progress, maxTries).ConfigureAwait(false);
}
/// <summary>
/// Get the status of the session. Stores returned session internally.
/// Updates internal list of ranges remaining to be uploaded (according to the server).
/// </summary>
/// <returns><see cref="IUploadSession"/>> returned by the server.</returns>
public async Task<IUploadSession> UpdateSessionStatusAsync()
{
var request = new UploadSessionRequest(this.Session, this._client);
var newSession = await request.GetAsync().ConfigureAwait(false);
var newRangesRemaining = this.GetRangesRemaining(newSession);
this._rangesRemaining = newRangesRemaining;
newSession.UploadUrl = this.Session.UploadUrl; // Sometimes the UploadUrl is not returned
this.Session = newSession;
return newSession;
}
/// <summary>
/// Delete the session.
/// </summary>
/// <returns>Once returned task is complete, the session has been deleted.</returns>
public async Task DeleteSessionAsync()
{
// validate that the upload can still be deleted.
var uploadExpirationTime = this.Session.ExpirationDateTime ?? DateTimeOffset.Now;
if (DateTimeOffset.Compare(uploadExpirationTime, DateTimeOffset.Now) <= 0)
{
throw new ClientException(
new Error
{
Code = ErrorConstants.Codes.Timeout,
Message = ErrorConstants.Messages.ExpiredUploadSession
});
}
var request = new UploadSessionRequest(this.Session, this._client);
await request.DeleteAsync().ConfigureAwait(false);
}
private List<Tuple<long, long>> GetRangesRemaining(IUploadSession session)
{
// nextExpectedRanges: https://dev.onedrive.com/items/upload_large_files.htm
// Sample: ["12345-55232","77829-99375"]
// Also, second number in range can be blank, which means 'until the end'
var newRangesRemaining = new List<Tuple<long, long>>();
foreach (var range in session.NextExpectedRanges)
{
var rangeSpecifiers = range.Split('-');
newRangesRemaining.Add(new Tuple<long, long>(long.Parse(rangeSpecifiers[0]),
string.IsNullOrEmpty(rangeSpecifiers[1]) ? this.TotalUploadLength - 1 : long.Parse(rangeSpecifiers[1])));
}
return newRangesRemaining;
}
private long NextSliceSize(long rangeBegin, long rangeEnd)
{
var sizeBasedOnRange = rangeEnd - rangeBegin + 1;
return sizeBasedOnRange > this._maxSliceSize
? this._maxSliceSize
: sizeBasedOnRange;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.