context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.Collections.Generic;
using UnityEngine;
public class BluetoothDeviceScript : MonoBehaviour
{
public List<string> DiscoveredDeviceList;
public Action InitializedAction;
public Action DeinitializedAction;
public Action<string> ErrorAction;
public Action<string> ServiceAddedAction;
public Action StartedAdvertisingAction;
public Action StoppedAdvertisingAction;
public Action<string, string> DiscoveredPeripheralAction;
public Action<string, string, int, byte[]> DiscoveredPeripheralWithAdvertisingInfoAction;
public Action<string, string> RetrievedConnectedPeripheralAction;
public Action<string, byte[]> PeripheralReceivedWriteDataAction;
public Action<string> ConnectedPeripheralAction;
public Action<string> ConnectedDisconnectPeripheralAction;
public Action<string> DisconnectedPeripheralAction;
public Action<string, string> DiscoveredServiceAction;
public Action<string, string, string> DiscoveredCharacteristicAction;
public Action<string> DidWriteCharacteristicAction;
public Dictionary<string, Dictionary<string, Action<string>>> DidUpdateNotificationStateForCharacteristicAction;
public Dictionary<string, Dictionary<string, Action<string, string>>> DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction;
public Dictionary<string, Dictionary<string, Action<string, byte[]>>> DidUpdateCharacteristicValueAction;
public Dictionary<string, Dictionary<string, Action<string, string, byte[]>>> DidUpdateCharacteristicValueWithDeviceAddressAction;
// Use this for initialization
void Start ()
{
DiscoveredDeviceList = new List<string>();
DidUpdateNotificationStateForCharacteristicAction = new Dictionary<string, Dictionary<string, Action<string>>>();
DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction = new Dictionary<string, Dictionary<string, Action<string, string>>>();
DidUpdateCharacteristicValueAction = new Dictionary<string, Dictionary<string, Action<string, byte[]>>>();
DidUpdateCharacteristicValueWithDeviceAddressAction = new Dictionary<string, Dictionary<string, Action<string, string, byte[]>>>();
}
// Update is called once per frame
void Update ()
{
}
const string deviceInitializedString = "Initialized";
const string deviceDeInitializedString = "DeInitialized";
const string deviceErrorString = "Error";
const string deviceServiceAdded = "ServiceAdded";
const string deviceStartedAdvertising = "StartedAdvertising";
const string deviceStoppedAdvertising = "StoppedAdvertising";
const string deviceDiscoveredPeripheral = "DiscoveredPeripheral";
const string deviceRetrievedConnectedPeripheral = "RetrievedConnectedPeripheral";
const string devicePeripheralReceivedWriteData = "PeripheralReceivedWriteData";
const string deviceConnectedPeripheral = "ConnectedPeripheral";
const string deviceDisconnectedPeripheral = "DisconnectedPeripheral";
const string deviceDiscoveredService = "DiscoveredService";
const string deviceDiscoveredCharacteristic = "DiscoveredCharacteristic";
const string deviceDidWriteCharacteristic = "DidWriteCharacteristic";
const string deviceDidUpdateNotificationStateForCharacteristic = "DidUpdateNotificationStateForCharacteristic";
const string deviceDidUpdateValueForCharacteristic = "DidUpdateValueForCharacteristic";
public void OnBluetoothMessage (string message)
{
if (message != null)
{
char[] delim = new char[] { '~' };
string[] parts = message.Split (delim);
for (int i = 0; i < parts.Length; ++i)
BluetoothLEHardwareInterface.Log(string.Format ("Part: {0} - {1}", i, parts[i]));
if (message.Length >= deviceInitializedString.Length && message.Substring (0, deviceInitializedString.Length) == deviceInitializedString)
{
if (InitializedAction != null)
InitializedAction ();
}
else if (message.Length >= deviceDeInitializedString.Length && message.Substring (0, deviceDeInitializedString.Length) == deviceDeInitializedString)
{
BluetoothLEHardwareInterface.FinishDeInitialize ();
if (DeinitializedAction != null)
DeinitializedAction ();
}
else if (message.Length >= deviceErrorString.Length && message.Substring (0, deviceErrorString.Length) == deviceErrorString)
{
string error = "";
if (parts.Length >= 2)
error = parts[1];
if (ErrorAction != null)
ErrorAction (error);
}
else if (message.Length >= deviceServiceAdded.Length && message.Substring (0, deviceServiceAdded.Length) == deviceServiceAdded)
{
if (parts.Length >= 2)
{
if (ServiceAddedAction != null)
ServiceAddedAction (parts[1]);
}
}
else if (message.Length >= deviceStartedAdvertising.Length && message.Substring (0, deviceStartedAdvertising.Length) == deviceStartedAdvertising)
{
BluetoothLEHardwareInterface.Log("Started Advertising");
if (StartedAdvertisingAction != null)
StartedAdvertisingAction ();
}
else if (message.Length >= deviceStoppedAdvertising.Length && message.Substring (0, deviceStoppedAdvertising.Length) == deviceStoppedAdvertising)
{
BluetoothLEHardwareInterface.Log("Stopped Advertising");
if (StoppedAdvertisingAction != null)
StoppedAdvertisingAction ();
}
else if (message.Length >= deviceDiscoveredPeripheral.Length && message.Substring (0, deviceDiscoveredPeripheral.Length) == deviceDiscoveredPeripheral)
{
if (parts.Length >= 3)
{
// the first callback will only get called the first time this device is seen
// this is because it gets added to the a list in the DiscoveredDeviceList
// after that only the second callback will get called and only if there is
// advertising data available
if (!DiscoveredDeviceList.Contains (parts[1]))
{
DiscoveredDeviceList.Add (parts[1]);
if (DiscoveredPeripheralAction != null)
DiscoveredPeripheralAction (parts[1], parts[2]);
}
if (parts.Length >= 5 && DiscoveredPeripheralWithAdvertisingInfoAction != null)
{
// get the rssi from the 4th value
int rssi = 0;
if (!int.TryParse (parts[3], out rssi))
rssi = 0;
// parse the base 64 encoded data that is the 5th value
byte[] bytes = System.Convert.FromBase64String(parts[4]);
DiscoveredPeripheralWithAdvertisingInfoAction(parts[1], parts[2], rssi, bytes);
}
}
}
else if (message.Length >= deviceRetrievedConnectedPeripheral.Length && message.Substring (0, deviceRetrievedConnectedPeripheral.Length) == deviceRetrievedConnectedPeripheral)
{
if (parts.Length >= 3)
{
DiscoveredDeviceList.Add (parts[1]);
if (RetrievedConnectedPeripheralAction != null)
RetrievedConnectedPeripheralAction (parts[1], parts[2]);
}
}
else if (message.Length >= devicePeripheralReceivedWriteData.Length && message.Substring (0, devicePeripheralReceivedWriteData.Length) == devicePeripheralReceivedWriteData)
{
if (parts.Length >= 3)
OnPeripheralData (parts[1], parts[2]);
}
else if (message.Length >= deviceConnectedPeripheral.Length && message.Substring (0, deviceConnectedPeripheral.Length) == deviceConnectedPeripheral)
{
if (parts.Length >= 2 && ConnectedPeripheralAction != null)
ConnectedPeripheralAction (parts[1]);
}
else if (message.Length >= deviceDisconnectedPeripheral.Length && message.Substring (0, deviceDisconnectedPeripheral.Length) == deviceDisconnectedPeripheral)
{
if (parts.Length >= 2)
{
if (ConnectedDisconnectPeripheralAction != null)
ConnectedDisconnectPeripheralAction (parts[1]);
if (DisconnectedPeripheralAction != null)
DisconnectedPeripheralAction (parts[1]);
}
}
else if (message.Length >= deviceDiscoveredService.Length && message.Substring (0, deviceDiscoveredService.Length) == deviceDiscoveredService)
{
if (parts.Length >= 3 && DiscoveredServiceAction != null)
DiscoveredServiceAction (parts[1], parts[2]);
}
else if (message.Length >= deviceDiscoveredCharacteristic.Length && message.Substring (0, deviceDiscoveredCharacteristic.Length) == deviceDiscoveredCharacteristic)
{
if (parts.Length >= 4 && DiscoveredCharacteristicAction != null)
DiscoveredCharacteristicAction (parts[1], parts[2], parts[3]);
}
else if (message.Length >= deviceDidWriteCharacteristic.Length && message.Substring (0, deviceDidWriteCharacteristic.Length) == deviceDidWriteCharacteristic)
{
if (parts.Length >= 2 && DidWriteCharacteristicAction != null)
DidWriteCharacteristicAction (parts[1]);
}
else if (message.Length >= deviceDidUpdateNotificationStateForCharacteristic.Length && message.Substring (0, deviceDidUpdateNotificationStateForCharacteristic.Length) == deviceDidUpdateNotificationStateForCharacteristic)
{
if (parts.Length >= 3)
{
if (DidUpdateNotificationStateForCharacteristicAction != null && DidUpdateNotificationStateForCharacteristicAction.ContainsKey (parts[1]))
{
var characteristicAction = DidUpdateNotificationStateForCharacteristicAction[parts[1]];
if (characteristicAction != null && characteristicAction.ContainsKey (parts[2]))
{
var action = characteristicAction[parts[2]];
if (action != null)
action (parts[2]);
}
}
if (DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction != null && DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction.ContainsKey (parts[1]))
{
var characteristicAction = DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction[parts[1]];
if (characteristicAction != null && characteristicAction.ContainsKey (parts[2]))
{
var action = characteristicAction[parts[2]];
if (action != null)
action (parts[1], parts[2]);
}
}
}
}
else if (message.Length >= deviceDidUpdateValueForCharacteristic.Length && message.Substring (0, deviceDidUpdateValueForCharacteristic.Length) == deviceDidUpdateValueForCharacteristic)
{
if (parts.Length >= 4)
OnBluetoothData (parts[1], parts[2], parts[3]);
}
}
}
public void OnBluetoothData (string base64Data)
{
OnBluetoothData ("", "", base64Data);
}
public void OnBluetoothData (string deviceAddress, string characteristic, string base64Data)
{
if (base64Data != null)
{
byte[] bytes = System.Convert.FromBase64String(base64Data);
if (bytes.Length > 0)
{
deviceAddress = deviceAddress.ToUpper ();
characteristic = characteristic.ToUpper ();
BluetoothLEHardwareInterface.Log("Device: " + deviceAddress + " Characteristic Received: " + characteristic);
string byteString = "";
foreach (byte b in bytes)
byteString += string.Format("{0:X2}", b);
BluetoothLEHardwareInterface.Log(byteString);
if (DidUpdateCharacteristicValueAction != null && DidUpdateCharacteristicValueAction.ContainsKey (deviceAddress))
{
var characteristicAction = DidUpdateCharacteristicValueAction[deviceAddress];
#if UNITY_ANDROID
characteristic = characteristic.ToLower ();
#endif
if (characteristicAction != null && characteristicAction.ContainsKey (characteristic))
{
var action = characteristicAction[characteristic];
if (action != null)
action (characteristic, bytes);
}
}
if (DidUpdateCharacteristicValueWithDeviceAddressAction != null && DidUpdateCharacteristicValueWithDeviceAddressAction.ContainsKey (deviceAddress))
{
var characteristicAction = DidUpdateCharacteristicValueWithDeviceAddressAction[deviceAddress];
#if UNITY_ANDROID
characteristic = characteristic.ToLower ();
#endif
if (characteristicAction != null && characteristicAction.ContainsKey (characteristic))
{
var action = characteristicAction[characteristic];
if (action != null)
action (deviceAddress, characteristic, bytes);
}
}
}
}
}
public void OnPeripheralData (string characteristic, string base64Data)
{
if (base64Data != null)
{
byte[] bytes = System.Convert.FromBase64String(base64Data);
if (bytes.Length > 0)
{
BluetoothLEHardwareInterface.Log("Peripheral Received: " + characteristic);
string byteString = "";
foreach (byte b in bytes)
byteString += string.Format("{0:X2}", b);
BluetoothLEHardwareInterface.Log(byteString);
if (PeripheralReceivedWriteDataAction != null)
PeripheralReceivedWriteDataAction (characteristic, bytes);
}
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you
/// currently do not have developer preview access, please contact [email protected].
///
/// WebhookResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
namespace Twilio.Rest.Autopilot.V1.Assistant
{
public class WebhookResource : Resource
{
private static Request BuildFetchRequest(FetchWebhookOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Autopilot,
"/v1/Assistants/" + options.PathAssistantSid + "/Webhooks/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Webhook parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Webhook </returns>
public static WebhookResource Fetch(FetchWebhookOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Webhook parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Webhook </returns>
public static async System.Threading.Tasks.Task<WebhookResource> FetchAsync(FetchWebhookOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// fetch
/// </summary>
/// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the resource to fetch </param>
/// <param name="pathSid"> The unique string that identifies the resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Webhook </returns>
public static WebhookResource Fetch(string pathAssistantSid, string pathSid, ITwilioRestClient client = null)
{
var options = new FetchWebhookOptions(pathAssistantSid, pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the resource to fetch </param>
/// <param name="pathSid"> The unique string that identifies the resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Webhook </returns>
public static async System.Threading.Tasks.Task<WebhookResource> FetchAsync(string pathAssistantSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchWebhookOptions(pathAssistantSid, pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadWebhookOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Autopilot,
"/v1/Assistants/" + options.PathAssistantSid + "/Webhooks",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Webhook parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Webhook </returns>
public static ResourceSet<WebhookResource> Read(ReadWebhookOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<WebhookResource>.FromJson("webhooks", response.Content);
return new ResourceSet<WebhookResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Webhook parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Webhook </returns>
public static async System.Threading.Tasks.Task<ResourceSet<WebhookResource>> ReadAsync(ReadWebhookOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<WebhookResource>.FromJson("webhooks", response.Content);
return new ResourceSet<WebhookResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the resources to read </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Webhook </returns>
public static ResourceSet<WebhookResource> Read(string pathAssistantSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadWebhookOptions(pathAssistantSid){PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the resources to read </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Webhook </returns>
public static async System.Threading.Tasks.Task<ResourceSet<WebhookResource>> ReadAsync(string pathAssistantSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadWebhookOptions(pathAssistantSid){PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<WebhookResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<WebhookResource>.FromJson("webhooks", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<WebhookResource> NextPage(Page<WebhookResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Autopilot)
);
var response = client.Request(request);
return Page<WebhookResource>.FromJson("webhooks", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<WebhookResource> PreviousPage(Page<WebhookResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Autopilot)
);
var response = client.Request(request);
return Page<WebhookResource>.FromJson("webhooks", response.Content);
}
private static Request BuildCreateRequest(CreateWebhookOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Autopilot,
"/v1/Assistants/" + options.PathAssistantSid + "/Webhooks",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Webhook parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Webhook </returns>
public static WebhookResource Create(CreateWebhookOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Webhook parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Webhook </returns>
public static async System.Threading.Tasks.Task<WebhookResource> CreateAsync(CreateWebhookOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// create
/// </summary>
/// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the new resource </param>
/// <param name="uniqueName"> An application-defined string that uniquely identifies the resource </param>
/// <param name="events"> The list of space-separated events that this Webhook will subscribe to. </param>
/// <param name="webhookUrl"> The URL associated with this Webhook. </param>
/// <param name="webhookMethod"> The method to be used when calling the webhook's URL. </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Webhook </returns>
public static WebhookResource Create(string pathAssistantSid,
string uniqueName,
string events,
Uri webhookUrl,
string webhookMethod = null,
ITwilioRestClient client = null)
{
var options = new CreateWebhookOptions(pathAssistantSid, uniqueName, events, webhookUrl){WebhookMethod = webhookMethod};
return Create(options, client);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the new resource </param>
/// <param name="uniqueName"> An application-defined string that uniquely identifies the resource </param>
/// <param name="events"> The list of space-separated events that this Webhook will subscribe to. </param>
/// <param name="webhookUrl"> The URL associated with this Webhook. </param>
/// <param name="webhookMethod"> The method to be used when calling the webhook's URL. </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Webhook </returns>
public static async System.Threading.Tasks.Task<WebhookResource> CreateAsync(string pathAssistantSid,
string uniqueName,
string events,
Uri webhookUrl,
string webhookMethod = null,
ITwilioRestClient client = null)
{
var options = new CreateWebhookOptions(pathAssistantSid, uniqueName, events, webhookUrl){WebhookMethod = webhookMethod};
return await CreateAsync(options, client);
}
#endif
private static Request BuildUpdateRequest(UpdateWebhookOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Autopilot,
"/v1/Assistants/" + options.PathAssistantSid + "/Webhooks/" + options.PathSid + "",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Webhook parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Webhook </returns>
public static WebhookResource Update(UpdateWebhookOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Webhook parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Webhook </returns>
public static async System.Threading.Tasks.Task<WebhookResource> UpdateAsync(UpdateWebhookOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// update
/// </summary>
/// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the resource to update </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="uniqueName"> An application-defined string that uniquely identifies the resource </param>
/// <param name="events"> The list of space-separated events that this Webhook will subscribe to. </param>
/// <param name="webhookUrl"> The URL associated with this Webhook. </param>
/// <param name="webhookMethod"> The method to be used when calling the webhook's URL. </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Webhook </returns>
public static WebhookResource Update(string pathAssistantSid,
string pathSid,
string uniqueName = null,
string events = null,
Uri webhookUrl = null,
string webhookMethod = null,
ITwilioRestClient client = null)
{
var options = new UpdateWebhookOptions(pathAssistantSid, pathSid){UniqueName = uniqueName, Events = events, WebhookUrl = webhookUrl, WebhookMethod = webhookMethod};
return Update(options, client);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the resource to update </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="uniqueName"> An application-defined string that uniquely identifies the resource </param>
/// <param name="events"> The list of space-separated events that this Webhook will subscribe to. </param>
/// <param name="webhookUrl"> The URL associated with this Webhook. </param>
/// <param name="webhookMethod"> The method to be used when calling the webhook's URL. </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Webhook </returns>
public static async System.Threading.Tasks.Task<WebhookResource> UpdateAsync(string pathAssistantSid,
string pathSid,
string uniqueName = null,
string events = null,
Uri webhookUrl = null,
string webhookMethod = null,
ITwilioRestClient client = null)
{
var options = new UpdateWebhookOptions(pathAssistantSid, pathSid){UniqueName = uniqueName, Events = events, WebhookUrl = webhookUrl, WebhookMethod = webhookMethod};
return await UpdateAsync(options, client);
}
#endif
private static Request BuildDeleteRequest(DeleteWebhookOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.Autopilot,
"/v1/Assistants/" + options.PathAssistantSid + "/Webhooks/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Webhook parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Webhook </returns>
public static bool Delete(DeleteWebhookOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Webhook parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Webhook </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteWebhookOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// delete
/// </summary>
/// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the resources to delete </param>
/// <param name="pathSid"> The unique string that identifies the resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Webhook </returns>
public static bool Delete(string pathAssistantSid, string pathSid, ITwilioRestClient client = null)
{
var options = new DeleteWebhookOptions(pathAssistantSid, pathSid);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the resources to delete </param>
/// <param name="pathSid"> The unique string that identifies the resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Webhook </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathAssistantSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new DeleteWebhookOptions(pathAssistantSid, pathSid);
return await DeleteAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a WebhookResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> WebhookResource object represented by the provided JSON </returns>
public static WebhookResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<WebhookResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The absolute URL of the Webhook resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The RFC 2822 date and time in GMT when the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The RFC 2822 date and time in GMT when the resource was last updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The SID of the Assistant that is the parent of the resource
/// </summary>
[JsonProperty("assistant_sid")]
public string AssistantSid { get; private set; }
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// An application-defined string that uniquely identifies the resource
/// </summary>
[JsonProperty("unique_name")]
public string UniqueName { get; private set; }
/// <summary>
/// The list of space-separated events that this Webhook is subscribed to.
/// </summary>
[JsonProperty("events")]
public string Events { get; private set; }
/// <summary>
/// The URL associated with this Webhook.
/// </summary>
[JsonProperty("webhook_url")]
public Uri WebhookUrl { get; private set; }
/// <summary>
/// The method used when calling the webhook's URL.
/// </summary>
[JsonProperty("webhook_method")]
public string WebhookMethod { get; private set; }
private WebhookResource()
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.ComponentModel;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using MahApps.Metro;
using MetroDemo.Models;
using System.Windows.Input;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using MetroDemo.ExampleViews;
using NHotkey;
using NHotkey.Wpf;
namespace MetroDemo
{
public class AccentColorMenuData
{
public string Name { get; set; }
public Brush BorderColorBrush { get; set; }
public Brush ColorBrush { get; set; }
private ICommand changeAccentCommand;
public ICommand ChangeAccentCommand
{
get { return this.changeAccentCommand ?? (changeAccentCommand = new SimpleCommand { CanExecuteDelegate = x => true, ExecuteDelegate = x => this.DoChangeTheme(x) }); }
}
protected virtual void DoChangeTheme(object sender)
{
ThemeManager.ChangeThemeColorScheme(Application.Current, this.Name);
}
}
public class AppThemeMenuData : AccentColorMenuData
{
protected override void DoChangeTheme(object sender)
{
ThemeManager.ChangeThemeBaseColor(Application.Current, this.Name);
}
}
public class MainWindowViewModel : INotifyPropertyChanged, IDataErrorInfo, IDisposable
{
private readonly IDialogCoordinator _dialogCoordinator;
int? _integerGreater10Property;
private bool _animateOnPositionChange = true;
public MainWindowViewModel(IDialogCoordinator dialogCoordinator)
{
this.Title = "Flyout Binding Test";
_dialogCoordinator = dialogCoordinator;
SampleData.Seed();
// create accent color menu items for the demo
this.AccentColors = ThemeManager.ColorSchemes
.Select(a => new AccentColorMenuData { Name = a.Name, ColorBrush = a.ShowcaseBrush })
.ToList();
// create metro theme color menu items for the demo
this.AppThemes = ThemeManager.Themes
.GroupBy(x => x.BaseColorScheme)
.Select(x => x.First())
.Select(a => new AppThemeMenuData() { Name = a.BaseColorScheme, BorderColorBrush = a.Resources["BlackColorBrush"] as Brush, ColorBrush = a.Resources["WhiteColorBrush"] as Brush })
.ToList();
Albums = SampleData.Albums;
Artists = SampleData.Artists;
FlipViewImages = new Uri[]
{
new Uri("pack://application:,,,/MahApps.Metro.Demo;component/Assets/Photos/Home.jpg", UriKind.RelativeOrAbsolute),
new Uri("pack://application:,,,/MahApps.Metro.Demo;component/Assets/Photos/Privat.jpg", UriKind.RelativeOrAbsolute),
new Uri("pack://application:,,,/MahApps.Metro.Demo;component/Assets/Photos/Settings.jpg", UriKind.RelativeOrAbsolute)
};
BrushResources = FindBrushResources();
CultureInfos = CultureInfo.GetCultures(CultureTypes.InstalledWin32Cultures).OrderBy(c => c.DisplayName).ToList();
try
{
HotkeyManager.Current.AddOrReplace("demo", HotKey.Key, HotKey.ModifierKeys, (sender, e) => OnHotKey(sender, e));
}
catch (HotkeyAlreadyRegisteredException exception)
{
System.Diagnostics.Trace.TraceWarning("Uups, the hotkey {0} is already registered!", exception.Name);
}
}
public void Dispose()
{
HotkeyManager.Current.Remove("demo");
}
public string Title { get; set; }
public int SelectedIndex { get; set; }
public List<Album> Albums { get; set; }
public List<Artist> Artists { get; set; }
public List<AccentColorMenuData> AccentColors { get; set; }
public List<AppThemeMenuData> AppThemes { get; set; }
public List<CultureInfo> CultureInfos { get; set; }
private ICommand endOfScrollReachedCmdWithParameter;
public ICommand EndOfScrollReachedCmdWithParameter
{
get
{
return this.endOfScrollReachedCmdWithParameter ?? (this.endOfScrollReachedCmdWithParameter = new SimpleCommand
{
CanExecuteDelegate = x => true,
ExecuteDelegate = async x =>
{
await ((MetroWindow)Application.Current.MainWindow).ShowMessageAsync("End of scroll reached!", $"Parameter: {x}");
}
});
}
}
public int? IntegerGreater10Property
{
get { return this._integerGreater10Property; }
set
{
if (Equals(value, _integerGreater10Property))
{
return;
}
_integerGreater10Property = value;
RaisePropertyChanged("IntegerGreater10Property");
}
}
DateTime? _datePickerDate;
[Display(Prompt = "Auto resolved Watermark")]
public DateTime? DatePickerDate
{
get { return this._datePickerDate; }
set
{
if (Equals(value, _datePickerDate))
{
return;
}
_datePickerDate = value;
RaisePropertyChanged("DatePickerDate");
}
}
private bool _quitConfirmationEnabled;
public bool QuitConfirmationEnabled
{
get { return _quitConfirmationEnabled; }
set
{
if (value.Equals(_quitConfirmationEnabled)) return;
_quitConfirmationEnabled = value;
RaisePropertyChanged("QuitConfirmationEnabled");
}
}
private bool showMyTitleBar = true;
public bool ShowMyTitleBar
{
get { return showMyTitleBar; }
set
{
if (value.Equals(showMyTitleBar)) return;
showMyTitleBar = value;
RaisePropertyChanged("ShowMyTitleBar");
}
}
private bool canCloseFlyout = true;
public bool CanCloseFlyout
{
get { return this.canCloseFlyout; }
set
{
if (Equals(value, this.canCloseFlyout))
{
return;
}
this.canCloseFlyout = value;
this.RaisePropertyChanged("CanCloseFlyout");
}
}
private ICommand closeCmd;
public ICommand CloseCmd
{
get
{
return this.closeCmd ?? (this.closeCmd = new SimpleCommand
{
CanExecuteDelegate = x => this.CanCloseFlyout,
ExecuteDelegate = x => ((Flyout)x).IsOpen = false
});
}
}
private bool canShowHamburgerAboutCommand = true;
public bool CanShowHamburgerAboutCommand
{
get { return this.canShowHamburgerAboutCommand; }
set
{
if (Equals(value, this.canShowHamburgerAboutCommand))
{
return;
}
this.canShowHamburgerAboutCommand = value;
this.RaisePropertyChanged("CanShowHamburgerAboutCommand");
}
}
private bool isHamburgerMenuPaneOpen;
public bool IsHamburgerMenuPaneOpen
{
get { return this.isHamburgerMenuPaneOpen; }
set
{
if (Equals(value, this.isHamburgerMenuPaneOpen))
{
return;
}
this.isHamburgerMenuPaneOpen = value;
this.RaisePropertyChanged("IsHamburgerMenuPaneOpen");
}
}
private ICommand textBoxButtonCmd;
public ICommand TextBoxButtonCmd
{
get
{
return this.textBoxButtonCmd ?? (this.textBoxButtonCmd = new SimpleCommand
{
CanExecuteDelegate = x => true,
ExecuteDelegate = async x =>
{
if (x is string)
{
await ((MetroWindow) Application.Current.MainWindow).ShowMessageAsync("Wow, you typed Return and got", (string)x);
}
else if (x is RichTextBox)
{
var richTextBox = x as RichTextBox;
var text = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd).Text;
await ((MetroWindow) Application.Current.MainWindow).ShowMessageAsync("RichTextBox Button was clicked!", text);
}
else if (x is TextBox)
{
await ((MetroWindow) Application.Current.MainWindow).ShowMessageAsync("TextBox Button was clicked!", ((TextBox) x).Text);
}
else if (x is PasswordBox)
{
await ((MetroWindow) Application.Current.MainWindow).ShowMessageAsync("PasswordBox Button was clicked!", ((PasswordBox) x).Password);
}
}
});
}
}
private ICommand textBoxButtonCmdWithParameter;
public ICommand TextBoxButtonCmdWithParameter
{
get
{
return this.textBoxButtonCmdWithParameter ?? (this.textBoxButtonCmdWithParameter = new SimpleCommand
{
CanExecuteDelegate = x => true,
ExecuteDelegate = async x =>
{
if (x is String)
{
await ((MetroWindow) Application.Current.MainWindow).ShowMessageAsync("TextBox Button with parameter was clicked!",
string.Format("Parameter: {0}", x));
}
}
});
}
}
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises the PropertyChanged event if needed.
/// </summary>
/// <param name="propertyName">The name of the property that changed.</param>
protected virtual void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public string this[string columnName]
{
get
{
if (columnName == "IntegerGreater10Property" && this.IntegerGreater10Property < 10)
{
return "Number is not greater than 10!";
}
if (columnName == "DatePickerDate" && this.DatePickerDate == null)
{
return "No date given!";
}
if (columnName == "HotKey" && this.HotKey != null && this.HotKey.Key == Key.D && this.HotKey.ModifierKeys == ModifierKeys.Shift)
{
return "SHIFT-D is not allowed";
}
if (columnName == "TimePickerDate" && this.TimePickerDate == null) {
return "No time given!";
}
return null;
}
}
[Description("Test-Property")]
public string Error { get { return string.Empty; } }
DateTime? _timePickerDate;
[Display(Prompt = "Time needed...")]
public DateTime? TimePickerDate {
get { return this._timePickerDate; }
set {
if (Equals(value, _timePickerDate)) {
return;
}
_timePickerDate = value;
RaisePropertyChanged("TimePickerDate");
}
}
private ICommand singleCloseTabCommand;
public ICommand SingleCloseTabCommand
{
get
{
return this.singleCloseTabCommand ?? (this.singleCloseTabCommand = new SimpleCommand
{
CanExecuteDelegate = x => true,
ExecuteDelegate = async x =>
{
await ((MetroWindow) Application.Current.MainWindow).ShowMessageAsync("Closing tab!", string.Format("You are now closing the '{0}' tab", x));
}
});
}
}
private ICommand neverCloseTabCommand;
public ICommand NeverCloseTabCommand
{
get { return this.neverCloseTabCommand ?? (this.neverCloseTabCommand = new SimpleCommand { CanExecuteDelegate = x => false }); }
}
private ICommand showInputDialogCommand;
public ICommand ShowInputDialogCommand
{
get
{
return this.showInputDialogCommand ?? (this.showInputDialogCommand = new SimpleCommand
{
CanExecuteDelegate = x => true,
ExecuteDelegate = async x =>
{
await _dialogCoordinator.ShowInputAsync(this, "From a VM", "This dialog was shown from a VM, without knowledge of Window").ContinueWith(t => Console.WriteLine(t.Result));
}
});
}
}
private ICommand showLoginDialogCommand;
public ICommand ShowLoginDialogCommand
{
get
{
return this.showLoginDialogCommand ?? (this.showLoginDialogCommand = new SimpleCommand
{
CanExecuteDelegate = x => true,
ExecuteDelegate = async x =>
{
await _dialogCoordinator.ShowLoginAsync(this, "Login from a VM", "This login dialog was shown from a VM, so you can be all MVVM.").ContinueWith(t => Console.WriteLine(t.Result));
}
});
}
}
private ICommand showMessageDialogCommand;
public ICommand ShowMessageDialogCommand
{
get
{
return this.showMessageDialogCommand ?? (this.showMessageDialogCommand = new SimpleCommand
{
CanExecuteDelegate = x => true,
ExecuteDelegate = x => PerformDialogCoordinatorAction(this.ShowMessage((string)x), (string)x == "DISPATCHER_THREAD")
});
}
}
private Action ShowMessage(string startingThread)
{
return () =>
{
var message = $"MVVM based messages!\n\nThis dialog was created by {startingThread} Thread with ID=\"{Thread.CurrentThread.ManagedThreadId}\"\n" +
$"The current DISPATCHER_THREAD Thread has the ID=\"{Application.Current.Dispatcher.Thread.ManagedThreadId}\"";
this._dialogCoordinator.ShowMessageAsync(this, $"Message from VM created by {startingThread}", message).ContinueWith(t => Console.WriteLine(t.Result));
};
}
private ICommand showProgressDialogCommand;
public ICommand ShowProgressDialogCommand
{
get
{
return this.showProgressDialogCommand ?? (this.showProgressDialogCommand = new SimpleCommand
{
CanExecuteDelegate = x => true,
ExecuteDelegate = x => RunProgressFromVm()
});
}
}
private async void RunProgressFromVm()
{
var controller = await _dialogCoordinator.ShowProgressAsync(this, "Progress from VM", "Progressing all the things, wait 3 seconds");
controller.SetIndeterminate();
await Task.Delay(3000);
await controller.CloseAsync();
}
private static void PerformDialogCoordinatorAction(Action action, bool runInMainThread)
{
if (!runInMainThread)
{
Task.Factory.StartNew(action);
}
else
{
action();
}
}
private ICommand showCustomDialogCommand;
public ICommand ShowCustomDialogCommand
{
get
{
return this.showCustomDialogCommand ?? (this.showCustomDialogCommand = new SimpleCommand
{
CanExecuteDelegate = x => true,
ExecuteDelegate = x => RunCustomFromVm()
});
}
}
private async void RunCustomFromVm()
{
var customDialog = new CustomDialog() { Title = "Custom Dialog" };
var dataContext = new CustomDialogExampleContent(instance =>
{
_dialogCoordinator.HideMetroDialogAsync(this, customDialog);
System.Diagnostics.Debug.WriteLine(instance.FirstName);
});
customDialog.Content = new CustomDialogExample { DataContext = dataContext};
await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog);
}
public IEnumerable<string> BrushResources { get; private set; }
public bool AnimateOnPositionChange
{
get
{
return _animateOnPositionChange;
}
set
{
if (Equals(_animateOnPositionChange, value)) return;
_animateOnPositionChange = value;
RaisePropertyChanged("AnimateOnPositionChange");
}
}
private IEnumerable<string> FindBrushResources()
{
if (Application.Current.MainWindow != null)
{
var theme = ThemeManager.DetectTheme(Application.Current.MainWindow);
var resources = theme.Resources.Keys.Cast<object>()
.Where(key => theme.Resources[key] is SolidColorBrush)
.Select(key => key.ToString())
.OrderBy(s => s)
.ToList();
return resources;
}
return Enumerable.Empty<string>();
}
public Uri[] FlipViewImages
{
get;
set;
}
public class RandomDataTemplateSelector : DataTemplateSelector
{
public DataTemplate TemplateOne { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
return TemplateOne;
}
}
private HotKey _hotKey = new HotKey(Key.Home, ModifierKeys.Control | ModifierKeys.Shift);
public HotKey HotKey
{
get { return _hotKey; }
set
{
if (_hotKey != value)
{
_hotKey = value;
if (_hotKey != null && _hotKey.Key != Key.None)
{
HotkeyManager.Current.AddOrReplace("demo", HotKey.Key, HotKey.ModifierKeys, (sender, e) => OnHotKey(sender, e));
}
else
{
HotkeyManager.Current.Remove("demo");
}
RaisePropertyChanged("HotKey");
}
}
}
private async Task OnHotKey(object sender, HotkeyEventArgs e)
{
await ((MetroWindow)Application.Current.MainWindow).ShowMessageAsync(
"Hotkey pressed",
"You pressed the hotkey '" + HotKey + "' registered with the name '" + e.Name + "'");
}
private ICommand toggleIconScalingCommand;
public ICommand ToggleIconScalingCommand
{
get {
return toggleIconScalingCommand ?? (toggleIconScalingCommand = new SimpleCommand
{
ExecuteDelegate = ToggleIconScaling
});
}
}
private void ToggleIconScaling(object obj) {
var multiFrameImageMode = (MultiFrameImageMode)obj;
((MetroWindow)Application.Current.MainWindow).IconScalingMode = multiFrameImageMode;
RaisePropertyChanged("IsScaleDownLargerFrame");
RaisePropertyChanged("IsNoScaleSmallerFrame");
}
public bool IsScaleDownLargerFrame { get { return ((MetroWindow)Application.Current.MainWindow).IconScalingMode == MultiFrameImageMode.ScaleDownLargerFrame; } }
public bool IsNoScaleSmallerFrame { get { return ((MetroWindow)Application.Current.MainWindow).IconScalingMode == MultiFrameImageMode.NoScaleSmallerFrame; } }
}
}
| |
namespace MotionDetectorSample
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose( bool disposing )
{
if ( disposing && ( components != null ) )
{
components.Dispose( );
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent( )
{
this.components = new System.ComponentModel.Container( );
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager( typeof( MainForm ) );
this.menuMenu = new System.Windows.Forms.MenuStrip( );
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( );
this.openVideoFileusingDirectShowToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( );
this.localVideoCaptureDeviceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( );
this.openJPEGURLToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( );
this.openMJPEGURLToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( );
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( );
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator( );
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( );
this.motionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( );
this.motionDetectionAlgorithmToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( );
this.noneToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem( );
this.twoFramesDifferenceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( );
this.simpleBackgroundModelingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( );
this.motionProcessingAlgorithmToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( );
this.noneToolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem( );
this.motionAreaHighlightingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( );
this.motionBorderHighlightingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( );
this.blobCountingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( );
this.gridMotionAreaProcessingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( );
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator( );
this.defineMotionregionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( );
this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator( );
this.showMotionHistoryToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( );
this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( );
this.localVideoCaptureSettingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( );
this.crossbarVideoSettingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( );
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( );
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( );
this.openFileDialog = new System.Windows.Forms.OpenFileDialog( );
this.timer = new System.Windows.Forms.Timer( this.components );
this.statusBar = new System.Windows.Forms.StatusStrip( );
this.fpsLabel = new System.Windows.Forms.ToolStripStatusLabel( );
this.objectsCountLabel = new System.Windows.Forms.ToolStripStatusLabel( );
this.panel1 = new System.Windows.Forms.Panel( );
this.videoSourcePlayer = new AForge.Controls.VideoSourcePlayer( );
this.alarmTimer = new System.Windows.Forms.Timer( this.components );
this.menuMenu.SuspendLayout( );
this.statusBar.SuspendLayout( );
this.panel1.SuspendLayout( );
this.SuspendLayout( );
//
// menuMenu
//
this.menuMenu.Items.AddRange( new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.motionToolStripMenuItem,
this.toolsToolStripMenuItem,
this.helpToolStripMenuItem} );
this.menuMenu.Location = new System.Drawing.Point( 0, 0 );
this.menuMenu.Name = "menuMenu";
this.menuMenu.Size = new System.Drawing.Size( 432, 24 );
this.menuMenu.TabIndex = 0;
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange( new System.Windows.Forms.ToolStripItem[] {
this.openVideoFileusingDirectShowToolStripMenuItem,
this.localVideoCaptureDeviceToolStripMenuItem,
this.openJPEGURLToolStripMenuItem,
this.openMJPEGURLToolStripMenuItem,
this.openToolStripMenuItem,
this.toolStripMenuItem1,
this.exitToolStripMenuItem} );
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size( 37, 20 );
this.fileToolStripMenuItem.Text = "&File";
//
// openVideoFileusingDirectShowToolStripMenuItem
//
this.openVideoFileusingDirectShowToolStripMenuItem.Name = "openVideoFileusingDirectShowToolStripMenuItem";
this.openVideoFileusingDirectShowToolStripMenuItem.ShortcutKeys = ( (System.Windows.Forms.Keys) ( ( System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O ) ) );
this.openVideoFileusingDirectShowToolStripMenuItem.Size = new System.Drawing.Size( 270, 22 );
this.openVideoFileusingDirectShowToolStripMenuItem.Text = "&Open";
this.openVideoFileusingDirectShowToolStripMenuItem.Click += new System.EventHandler( this.openVideoFileusingDirectShowToolStripMenuItem_Click );
//
// localVideoCaptureDeviceToolStripMenuItem
//
this.localVideoCaptureDeviceToolStripMenuItem.Name = "localVideoCaptureDeviceToolStripMenuItem";
this.localVideoCaptureDeviceToolStripMenuItem.Size = new System.Drawing.Size( 270, 22 );
this.localVideoCaptureDeviceToolStripMenuItem.Text = "Local &Video Capture Device";
this.localVideoCaptureDeviceToolStripMenuItem.Click += new System.EventHandler( this.localVideoCaptureDeviceToolStripMenuItem_Click );
//
// openJPEGURLToolStripMenuItem
//
this.openJPEGURLToolStripMenuItem.Name = "openJPEGURLToolStripMenuItem";
this.openJPEGURLToolStripMenuItem.Size = new System.Drawing.Size( 270, 22 );
this.openJPEGURLToolStripMenuItem.Text = "Open JPEG &URL";
this.openJPEGURLToolStripMenuItem.Click += new System.EventHandler( this.openJPEGURLToolStripMenuItem_Click );
//
// openMJPEGURLToolStripMenuItem
//
this.openMJPEGURLToolStripMenuItem.Name = "openMJPEGURLToolStripMenuItem";
this.openMJPEGURLToolStripMenuItem.Size = new System.Drawing.Size( 270, 22 );
this.openMJPEGURLToolStripMenuItem.Text = "Open &MJPEG URL";
this.openMJPEGURLToolStripMenuItem.Click += new System.EventHandler( this.openMJPEGURLToolStripMenuItem_Click );
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
this.openToolStripMenuItem.Size = new System.Drawing.Size( 270, 22 );
this.openToolStripMenuItem.Text = "Open video file (using VFW interface)";
this.openToolStripMenuItem.Click += new System.EventHandler( this.openToolStripMenuItem_Click );
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size( 267, 6 );
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size( 270, 22 );
this.exitToolStripMenuItem.Text = "E&xit";
this.exitToolStripMenuItem.Click += new System.EventHandler( this.exitToolStripMenuItem_Click );
//
// motionToolStripMenuItem
//
this.motionToolStripMenuItem.DropDownItems.AddRange( new System.Windows.Forms.ToolStripItem[] {
this.motionDetectionAlgorithmToolStripMenuItem,
this.motionProcessingAlgorithmToolStripMenuItem,
this.toolStripMenuItem2,
this.defineMotionregionsToolStripMenuItem,
this.toolStripMenuItem3,
this.showMotionHistoryToolStripMenuItem} );
this.motionToolStripMenuItem.Name = "motionToolStripMenuItem";
this.motionToolStripMenuItem.Size = new System.Drawing.Size( 58, 20 );
this.motionToolStripMenuItem.Text = "&Motion";
this.motionToolStripMenuItem.DropDownOpening += new System.EventHandler( this.motionToolStripMenuItem_DropDownOpening );
//
// motionDetectionAlgorithmToolStripMenuItem
//
this.motionDetectionAlgorithmToolStripMenuItem.DropDownItems.AddRange( new System.Windows.Forms.ToolStripItem[] {
this.noneToolStripMenuItem1,
this.twoFramesDifferenceToolStripMenuItem,
this.simpleBackgroundModelingToolStripMenuItem} );
this.motionDetectionAlgorithmToolStripMenuItem.Name = "motionDetectionAlgorithmToolStripMenuItem";
this.motionDetectionAlgorithmToolStripMenuItem.Size = new System.Drawing.Size( 230, 22 );
this.motionDetectionAlgorithmToolStripMenuItem.Text = "Motion Detection Algorithm";
//
// noneToolStripMenuItem1
//
this.noneToolStripMenuItem1.Name = "noneToolStripMenuItem1";
this.noneToolStripMenuItem1.Size = new System.Drawing.Size( 231, 22 );
this.noneToolStripMenuItem1.Text = "None";
this.noneToolStripMenuItem1.Click += new System.EventHandler( this.noneToolStripMenuItem1_Click );
//
// twoFramesDifferenceToolStripMenuItem
//
this.twoFramesDifferenceToolStripMenuItem.Name = "twoFramesDifferenceToolStripMenuItem";
this.twoFramesDifferenceToolStripMenuItem.Size = new System.Drawing.Size( 231, 22 );
this.twoFramesDifferenceToolStripMenuItem.Text = "Two Frames Difference";
this.twoFramesDifferenceToolStripMenuItem.Click += new System.EventHandler( this.twoFramesDifferenceToolStripMenuItem_Click );
//
// simpleBackgroundModelingToolStripMenuItem
//
this.simpleBackgroundModelingToolStripMenuItem.Name = "simpleBackgroundModelingToolStripMenuItem";
this.simpleBackgroundModelingToolStripMenuItem.Size = new System.Drawing.Size( 231, 22 );
this.simpleBackgroundModelingToolStripMenuItem.Text = "Simple Background Modeling";
this.simpleBackgroundModelingToolStripMenuItem.Click += new System.EventHandler( this.simpleBackgroundModelingToolStripMenuItem_Click );
//
// motionProcessingAlgorithmToolStripMenuItem
//
this.motionProcessingAlgorithmToolStripMenuItem.DropDownItems.AddRange( new System.Windows.Forms.ToolStripItem[] {
this.noneToolStripMenuItem2,
this.motionAreaHighlightingToolStripMenuItem,
this.motionBorderHighlightingToolStripMenuItem,
this.blobCountingToolStripMenuItem,
this.gridMotionAreaProcessingToolStripMenuItem} );
this.motionProcessingAlgorithmToolStripMenuItem.Name = "motionProcessingAlgorithmToolStripMenuItem";
this.motionProcessingAlgorithmToolStripMenuItem.Size = new System.Drawing.Size( 230, 22 );
this.motionProcessingAlgorithmToolStripMenuItem.Text = "Motion Processing Algorithm";
//
// noneToolStripMenuItem2
//
this.noneToolStripMenuItem2.Name = "noneToolStripMenuItem2";
this.noneToolStripMenuItem2.Size = new System.Drawing.Size( 225, 22 );
this.noneToolStripMenuItem2.Text = "None";
this.noneToolStripMenuItem2.Click += new System.EventHandler( this.noneToolStripMenuItem2_Click );
//
// motionAreaHighlightingToolStripMenuItem
//
this.motionAreaHighlightingToolStripMenuItem.Name = "motionAreaHighlightingToolStripMenuItem";
this.motionAreaHighlightingToolStripMenuItem.Size = new System.Drawing.Size( 225, 22 );
this.motionAreaHighlightingToolStripMenuItem.Text = "Motion Area Highlighting";
this.motionAreaHighlightingToolStripMenuItem.Click += new System.EventHandler( this.motionAreaHighlightingToolStripMenuItem_Click );
//
// motionBorderHighlightingToolStripMenuItem
//
this.motionBorderHighlightingToolStripMenuItem.Name = "motionBorderHighlightingToolStripMenuItem";
this.motionBorderHighlightingToolStripMenuItem.Size = new System.Drawing.Size( 225, 22 );
this.motionBorderHighlightingToolStripMenuItem.Text = "Motion Border Highlighting";
this.motionBorderHighlightingToolStripMenuItem.Click += new System.EventHandler( this.motionBorderHighlightingToolStripMenuItem_Click );
//
// blobCountingToolStripMenuItem
//
this.blobCountingToolStripMenuItem.Name = "blobCountingToolStripMenuItem";
this.blobCountingToolStripMenuItem.Size = new System.Drawing.Size( 225, 22 );
this.blobCountingToolStripMenuItem.Text = "Blob Counting Processing";
this.blobCountingToolStripMenuItem.Click += new System.EventHandler( this.blobCountingToolStripMenuItem_Click );
//
// gridMotionAreaProcessingToolStripMenuItem
//
this.gridMotionAreaProcessingToolStripMenuItem.Name = "gridMotionAreaProcessingToolStripMenuItem";
this.gridMotionAreaProcessingToolStripMenuItem.Size = new System.Drawing.Size( 225, 22 );
this.gridMotionAreaProcessingToolStripMenuItem.Text = "Grid Motion Area Processing";
this.gridMotionAreaProcessingToolStripMenuItem.Click += new System.EventHandler( this.gridMotionAreaProcessingToolStripMenuItem_Click );
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
this.toolStripMenuItem2.Size = new System.Drawing.Size( 227, 6 );
//
// defineMotionregionsToolStripMenuItem
//
this.defineMotionregionsToolStripMenuItem.Name = "defineMotionregionsToolStripMenuItem";
this.defineMotionregionsToolStripMenuItem.Size = new System.Drawing.Size( 230, 22 );
this.defineMotionregionsToolStripMenuItem.Text = "Define motion ®ions";
this.defineMotionregionsToolStripMenuItem.Click += new System.EventHandler( this.defineMotionregionsToolStripMenuItem_Click );
//
// toolStripMenuItem3
//
this.toolStripMenuItem3.Name = "toolStripMenuItem3";
this.toolStripMenuItem3.Size = new System.Drawing.Size( 227, 6 );
//
// showMotionHistoryToolStripMenuItem
//
this.showMotionHistoryToolStripMenuItem.Name = "showMotionHistoryToolStripMenuItem";
this.showMotionHistoryToolStripMenuItem.Size = new System.Drawing.Size( 230, 22 );
this.showMotionHistoryToolStripMenuItem.Text = "Show motion history";
this.showMotionHistoryToolStripMenuItem.Click += new System.EventHandler( this.showMotionHistoryToolStripMenuItem_Click );
//
// toolsToolStripMenuItem
//
this.toolsToolStripMenuItem.DropDownItems.AddRange( new System.Windows.Forms.ToolStripItem[] {
this.localVideoCaptureSettingsToolStripMenuItem,
this.crossbarVideoSettingsToolStripMenuItem} );
this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem";
this.toolsToolStripMenuItem.Size = new System.Drawing.Size( 48, 20 );
this.toolsToolStripMenuItem.Text = "&Tools";
this.toolsToolStripMenuItem.DropDownOpening += new System.EventHandler( this.toolsToolStripMenuItem_DropDownOpening );
//
// localVideoCaptureSettingsToolStripMenuItem
//
this.localVideoCaptureSettingsToolStripMenuItem.Name = "localVideoCaptureSettingsToolStripMenuItem";
this.localVideoCaptureSettingsToolStripMenuItem.Size = new System.Drawing.Size( 225, 22 );
this.localVideoCaptureSettingsToolStripMenuItem.Text = "Local &Video Capture Settings";
this.localVideoCaptureSettingsToolStripMenuItem.Click += new System.EventHandler( this.localVideoCaptureSettingsToolStripMenuItem_Click );
//
// crossbarVideoSettingsToolStripMenuItem
//
this.crossbarVideoSettingsToolStripMenuItem.Name = "crossbarVideoSettingsToolStripMenuItem";
this.crossbarVideoSettingsToolStripMenuItem.Size = new System.Drawing.Size( 225, 22 );
this.crossbarVideoSettingsToolStripMenuItem.Text = "Crossbar Video Settings";
this.crossbarVideoSettingsToolStripMenuItem.Click += new System.EventHandler( this.crossbarVideoSettingsToolStripMenuItem_Click );
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange( new System.Windows.Forms.ToolStripItem[] {
this.aboutToolStripMenuItem} );
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size( 44, 20 );
this.helpToolStripMenuItem.Text = "&Help";
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size( 107, 22 );
this.aboutToolStripMenuItem.Text = "&About";
this.aboutToolStripMenuItem.Click += new System.EventHandler( this.aboutToolStripMenuItem_Click );
//
// openFileDialog
//
this.openFileDialog.Filter = "AVI files (*.avi)|*.avi|All files (*.*)|*.*";
this.openFileDialog.Title = "Opem movie";
//
// timer
//
this.timer.Interval = 1000;
this.timer.Tick += new System.EventHandler( this.timer_Tick );
//
// statusBar
//
this.statusBar.Items.AddRange( new System.Windows.Forms.ToolStripItem[] {
this.fpsLabel,
this.objectsCountLabel} );
this.statusBar.Location = new System.Drawing.Point( 0, 334 );
this.statusBar.Name = "statusBar";
this.statusBar.Size = new System.Drawing.Size( 432, 22 );
this.statusBar.TabIndex = 3;
//
// fpsLabel
//
this.fpsLabel.AutoSize = false;
this.fpsLabel.BorderSides = ( (System.Windows.Forms.ToolStripStatusLabelBorderSides) ( ( ( ( System.Windows.Forms.ToolStripStatusLabelBorderSides.Left | System.Windows.Forms.ToolStripStatusLabelBorderSides.Top )
| System.Windows.Forms.ToolStripStatusLabelBorderSides.Right )
| System.Windows.Forms.ToolStripStatusLabelBorderSides.Bottom ) ) );
this.fpsLabel.BorderStyle = System.Windows.Forms.Border3DStyle.SunkenInner;
this.fpsLabel.Name = "fpsLabel";
this.fpsLabel.Size = new System.Drawing.Size( 150, 17 );
this.fpsLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// objectsCountLabel
//
this.objectsCountLabel.BorderSides = ( (System.Windows.Forms.ToolStripStatusLabelBorderSides) ( ( ( ( System.Windows.Forms.ToolStripStatusLabelBorderSides.Left | System.Windows.Forms.ToolStripStatusLabelBorderSides.Top )
| System.Windows.Forms.ToolStripStatusLabelBorderSides.Right )
| System.Windows.Forms.ToolStripStatusLabelBorderSides.Bottom ) ) );
this.objectsCountLabel.BorderStyle = System.Windows.Forms.Border3DStyle.SunkenInner;
this.objectsCountLabel.Name = "objectsCountLabel";
this.objectsCountLabel.Size = new System.Drawing.Size( 267, 17 );
this.objectsCountLabel.Spring = true;
this.objectsCountLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// panel1
//
this.panel1.Controls.Add( this.videoSourcePlayer );
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point( 0, 24 );
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size( 432, 310 );
this.panel1.TabIndex = 4;
//
// videoSourcePlayer
//
this.videoSourcePlayer.AutoSizeControl = true;
this.videoSourcePlayer.BackColor = System.Drawing.SystemColors.ControlDarkDark;
this.videoSourcePlayer.ForeColor = System.Drawing.Color.White;
this.videoSourcePlayer.Location = new System.Drawing.Point( 55, 34 );
this.videoSourcePlayer.Name = "videoSourcePlayer";
this.videoSourcePlayer.Size = new System.Drawing.Size( 322, 242 );
this.videoSourcePlayer.TabIndex = 0;
this.videoSourcePlayer.VideoSource = null;
this.videoSourcePlayer.NewFrame += new AForge.Controls.VideoSourcePlayer.NewFrameHandler( this.videoSourcePlayer_NewFrame );
//
// alarmTimer
//
this.alarmTimer.Interval = 200;
this.alarmTimer.Tick += new System.EventHandler( this.alarmTimer_Tick );
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F );
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size( 432, 356 );
this.Controls.Add( this.panel1 );
this.Controls.Add( this.statusBar );
this.Controls.Add( this.menuMenu );
this.Icon = ( (System.Drawing.Icon) ( resources.GetObject( "$this.Icon" ) ) );
this.MainMenuStrip = this.menuMenu;
this.Name = "MainForm";
this.Text = "Motion Detector";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler( this.MainForm_FormClosing );
this.menuMenu.ResumeLayout( false );
this.menuMenu.PerformLayout( );
this.statusBar.ResumeLayout( false );
this.statusBar.PerformLayout( );
this.panel1.ResumeLayout( false );
this.ResumeLayout( false );
this.PerformLayout( );
}
#endregion
private System.Windows.Forms.MenuStrip menuMenu;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem motionToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private System.Windows.Forms.OpenFileDialog openFileDialog;
private System.Windows.Forms.Timer timer;
private System.Windows.Forms.StatusStrip statusBar;
private System.Windows.Forms.ToolStripStatusLabel fpsLabel;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.ToolStripMenuItem openJPEGURLToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openMJPEGURLToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem localVideoCaptureDeviceToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openVideoFileusingDirectShowToolStripMenuItem;
private System.Windows.Forms.ToolStripStatusLabel objectsCountLabel;
private System.Windows.Forms.ToolStripMenuItem defineMotionregionsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem localVideoCaptureSettingsToolStripMenuItem;
private AForge.Controls.VideoSourcePlayer videoSourcePlayer;
private System.Windows.Forms.ToolStripMenuItem motionDetectionAlgorithmToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem noneToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem twoFramesDifferenceToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem simpleBackgroundModelingToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem motionProcessingAlgorithmToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem noneToolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem motionBorderHighlightingToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem blobCountingToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem gridMotionAreaProcessingToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem motionAreaHighlightingToolStripMenuItem;
private System.Windows.Forms.Timer alarmTimer;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3;
private System.Windows.Forms.ToolStripMenuItem showMotionHistoryToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem crossbarVideoSettingsToolStripMenuItem;
}
}
| |
// <copyright file="RemoteSessionSettings.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using OpenQA.Selenium.Remote;
namespace OpenQA.Selenium
{
/// <summary>
/// Base class for managing options specific to a browser driver.
/// </summary>
public class RemoteSessionSettings : ICapabilities
{
private const string FirstMatchCapabilityName = "firstMatch";
private const string AlwaysMatchCapabilityName = "alwaysMatch";
private readonly List<string> reservedSettingNames = new List<string>() { FirstMatchCapabilityName, AlwaysMatchCapabilityName };
private DriverOptions mustMatchDriverOptions;
private List<DriverOptions> firstMatchOptions = new List<DriverOptions>();
private Dictionary<string, object> remoteMetadataSettings = new Dictionary<string, object>();
/// <summary>
/// Creates a new instance of the <see cref="RemoteSessionSettings"/> class.
/// </summary>
public RemoteSessionSettings()
{
}
/// <summary>
/// Creates a new instance of the <see cref="RemoteSessionSettings"/> class,
/// containing the specified <see cref="DriverOptions"/> to use in the remote
/// session.
/// </summary>
/// <param name="mustMatchDriverOptions">
/// A <see cref="DriverOptions"/> object that contains values that must be matched
/// by the remote end to create the remote session.
/// </param>
/// <param name="firstMatchDriverOptions">
/// A list of <see cref="DriverOptions"/> objects that contain values that may be matched
/// by the remote end to create the remote session.
/// </param>
public RemoteSessionSettings(DriverOptions mustMatchDriverOptions, params DriverOptions[] firstMatchDriverOptions)
{
this.mustMatchDriverOptions = mustMatchDriverOptions;
foreach (DriverOptions firstMatchOption in firstMatchDriverOptions)
{
this.AddFirstMatchDriverOption(firstMatchOption);
}
}
/// <summary>
/// Gets a value indicating the options that must be matched by the remote end to create a session.
/// </summary>
internal DriverOptions MustMatchDriverOptions
{
get { return this.mustMatchDriverOptions; }
}
/// <summary>
/// Gets a value indicating the number of options that may be matched by the remote end to create a session.
/// </summary>
internal int FirstMatchOptionsCount
{
get { return this.firstMatchOptions.Count; }
}
/// <summary>
/// Gets the capability value with the specified name.
/// </summary>
/// <param name="capabilityName">The name of the capability to get.</param>
/// <returns>The value of the capability.</returns>
/// <exception cref="ArgumentException">
/// The specified capability name is not in the set of capabilities.
/// </exception>
public object this[string capabilityName]
{
get
{
if (capabilityName == AlwaysMatchCapabilityName)
{
return this.GetAlwaysMatchOptionsAsSerializableDictionary();
}
if (capabilityName == FirstMatchCapabilityName)
{
return this.GetFirstMatchOptionsAsSerializableList();
}
if (!this.remoteMetadataSettings.ContainsKey(capabilityName))
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "The capability {0} is not present in this set of capabilities", capabilityName));
}
return this.remoteMetadataSettings[capabilityName];
}
}
/// <summary>
/// Add a metadata setting to this set of remote session settings.
/// </summary>
/// <param name="settingName">The name of the setting to set.</param>
/// <param name="settingValue">The value of the setting.</param>
/// <remarks>
/// The value to be set must be serializable to JSON for transmission
/// across the wire to the remote end. To be JSON-serializable, the value
/// must be a string, a numeric value, a boolean value, an object that
/// implmeents <see cref="IEnumerable"/> that contains JSON-serializable
/// objects, or a <see cref="Dictionary{TKey, TValue}"/> where the keys
/// are strings and the values are JSON-serializable.
/// </remarks>
/// <exception cref="ArgumentException">
/// Thrown if the setting name is null, the empty string, or one of the
/// reserved names of metadata settings; or if the setting value is not
/// JSON serializable.
/// </exception>
public void AddMetadataSetting(string settingName, object settingValue)
{
if (string.IsNullOrEmpty(settingName))
{
throw new ArgumentException("Metadata setting name cannot be null or empty", nameof(settingName));
}
if (this.reservedSettingNames.Contains(settingName))
{
throw new ArgumentException(string.Format("'{0}' is a reserved name for a metadata setting, and cannot be used as a name.", settingName), nameof(settingName));
}
if (!this.IsJsonSerializable(settingValue))
{
throw new ArgumentException("Metadata setting value must be JSON serializable.", nameof(settingValue));
}
this.remoteMetadataSettings[settingName] = settingValue;
}
/// <summary>
/// Adds a <see cref="DriverOptions"/> object to the list of options containing values to be
/// "first matched" by the remote end.
/// </summary>
/// <param name="options">The <see cref="DriverOptions"/> to add to the list of "first matched" options.</param>
public void AddFirstMatchDriverOption(DriverOptions options)
{
if (mustMatchDriverOptions != null)
{
DriverOptionsMergeResult mergeResult = mustMatchDriverOptions.GetMergeResult(options);
if (mergeResult.IsMergeConflict)
{
string msg = string.Format(CultureInfo.InvariantCulture, "You cannot request the same capability in both must-match and first-match capabilities. You are attempting to add a first-match driver options object that defines a capability, '{0}', that is already defined in the must-match driver options.", mergeResult.MergeConflictOptionName);
throw new ArgumentException(msg, nameof(options));
}
}
firstMatchOptions.Add(options);
}
/// <summary>
/// Adds a <see cref="DriverOptions"/> object containing values that must be matched
/// by the remote end to successfully create a session.
/// </summary>
/// <param name="options">The <see cref="DriverOptions"/> that must be matched by
/// the remote end to successfully create a session.</param>
public void SetMustMatchDriverOptions(DriverOptions options)
{
if (this.firstMatchOptions.Count > 0)
{
int driverOptionIndex = 0;
foreach (DriverOptions firstMatchOption in this.firstMatchOptions)
{
DriverOptionsMergeResult mergeResult = firstMatchOption.GetMergeResult(options);
if (mergeResult.IsMergeConflict)
{
string msg = string.Format(CultureInfo.InvariantCulture, "You cannot request the same capability in both must-match and first-match capabilities. You are attempting to add a must-match driver options object that defines a capability, '{0}', that is already defined in the first-match driver options with index {1}.", mergeResult.MergeConflictOptionName, driverOptionIndex);
throw new ArgumentException(msg, nameof(options));
}
driverOptionIndex++;
}
}
this.mustMatchDriverOptions = options;
}
/// <summary>
/// Gets a value indicating whether the browser has a given capability.
/// </summary>
/// <param name="capability">The capability to get.</param>
/// <returns>Returns <see langword="true"/> if this set of capabilities has the capability;
/// otherwise, <see langword="false"/>.</returns>
public bool HasCapability(string capability)
{
if (capability == AlwaysMatchCapabilityName || capability == FirstMatchCapabilityName)
{
return true;
}
return this.remoteMetadataSettings.ContainsKey(capability);
}
/// <summary>
/// Gets a capability of the browser.
/// </summary>
/// <param name="capability">The capability to get.</param>
/// <returns>An object associated with the capability, or <see langword="null"/>
/// if the capability is not set in this set of capabilities.</returns>
public object GetCapability(string capability)
{
if (capability == AlwaysMatchCapabilityName)
{
return this.GetAlwaysMatchOptionsAsSerializableDictionary();
}
if (capability == FirstMatchCapabilityName)
{
return this.GetFirstMatchOptionsAsSerializableList();
}
if (this.remoteMetadataSettings.ContainsKey(capability))
{
return this.remoteMetadataSettings[capability];
}
return null;
}
/// <summary>
/// Return a dictionary representation of this <see cref="RemoteSessionSettings"/>.
/// </summary>
/// <returns>A <see cref="Dictionary{TKey, TValue}"/> representation of this <see cref="RemoteSessionSettings"/>.</returns>
public Dictionary<string, object> ToDictionary()
{
Dictionary<string, object> capabilitiesDictionary = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> remoteMetadataSetting in this.remoteMetadataSettings)
{
capabilitiesDictionary[remoteMetadataSetting.Key] = remoteMetadataSetting.Value;
}
if (this.mustMatchDriverOptions != null)
{
capabilitiesDictionary["alwaysMatch"] = GetAlwaysMatchOptionsAsSerializableDictionary();
}
if (this.firstMatchOptions.Count > 0)
{
List<object> optionsMatches = GetFirstMatchOptionsAsSerializableList();
capabilitiesDictionary["firstMatch"] = optionsMatches;
}
return capabilitiesDictionary;
}
/// <summary>
/// Return a string representation of the remote session settings to be sent.
/// </summary>
/// <returns>String representation of the remote session settings to be sent.</returns>
public override string ToString()
{
return JsonConvert.SerializeObject(this.ToDictionary(), Formatting.Indented);
}
internal DriverOptions GetFirstMatchDriverOptions(int firstMatchIndex)
{
if (firstMatchIndex < 0 || firstMatchIndex >= this.firstMatchOptions.Count)
{
throw new ArgumentException("Requested index must be greater than zero and less than the count of firstMatch options added.");
}
return this.firstMatchOptions[firstMatchIndex];
}
private IDictionary<string, object> GetAlwaysMatchOptionsAsSerializableDictionary()
{
return this.mustMatchDriverOptions.ToDictionary();
}
private List<object> GetFirstMatchOptionsAsSerializableList()
{
List<object> optionsMatches = new List<object>();
foreach (DriverOptions options in this.firstMatchOptions)
{
optionsMatches.Add(options.ToDictionary());
}
return optionsMatches;
}
private bool IsJsonSerializable(object arg)
{
IEnumerable argAsEnumerable = arg as IEnumerable;
IDictionary argAsDictionary = arg as IDictionary;
if (arg is string || arg is float || arg is double || arg is int || arg is long || arg is bool || arg == null)
{
return true;
}
else if (argAsDictionary != null)
{
foreach (object key in argAsDictionary.Keys)
{
if (!(key is string))
{
return false;
}
}
foreach (object value in argAsDictionary.Values)
{
if (!IsJsonSerializable(value))
{
return false;
}
}
}
else if (argAsEnumerable != null)
{
foreach (object item in argAsEnumerable)
{
if (!IsJsonSerializable(item))
{
return false;
}
}
}
else
{
return false;
}
return true;
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="System.CABundleManagerBinding", Namespace="urn:iControl")]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(SystemCABundleManagerCABundleManagerStatistics))]
public partial class SystemCABundleManager : iControlInterface {
public SystemCABundleManager() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// add_exclude_bundle
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
public void add_exclude_bundle(
string [] managers,
string [] [] bundles
) {
this.Invoke("add_exclude_bundle", new object [] {
managers,
bundles});
}
public System.IAsyncResult Beginadd_exclude_bundle(string [] managers,string [] [] bundles, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_exclude_bundle", new object[] {
managers,
bundles}, callback, asyncState);
}
public void Endadd_exclude_bundle(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// add_exclude_url
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
public void add_exclude_url(
string [] managers,
string [] [] urls
) {
this.Invoke("add_exclude_url", new object [] {
managers,
urls});
}
public System.IAsyncResult Beginadd_exclude_url(string [] managers,string [] [] urls, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_exclude_url", new object[] {
managers,
urls}, callback, asyncState);
}
public void Endadd_exclude_url(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// add_include_bundle
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
public void add_include_bundle(
string [] managers,
string [] [] bundles
) {
this.Invoke("add_include_bundle", new object [] {
managers,
bundles});
}
public System.IAsyncResult Beginadd_include_bundle(string [] managers,string [] [] bundles, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_include_bundle", new object[] {
managers,
bundles}, callback, asyncState);
}
public void Endadd_include_bundle(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// add_include_url
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
public void add_include_url(
string [] managers,
string [] [] urls
) {
this.Invoke("add_include_url", new object [] {
managers,
urls});
}
public System.IAsyncResult Beginadd_include_url(string [] managers,string [] [] urls, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_include_url", new object[] {
managers,
urls}, callback, asyncState);
}
public void Endadd_include_url(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
public void create(
string [] managers
) {
this.Invoke("create", new object [] {
managers});
}
public System.IAsyncResult Begincreate(string [] managers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
managers}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_managers
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
public void delete_all_managers(
) {
this.Invoke("delete_all_managers", new object [0]);
}
public System.IAsyncResult Begindelete_all_managers(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_managers", new object[0], callback, asyncState);
}
public void Enddelete_all_managers(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_manager
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
public void delete_manager(
string [] managers
) {
this.Invoke("delete_manager", new object [] {
managers});
}
public System.IAsyncResult Begindelete_manager(string [] managers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_manager", new object[] {
managers}, callback, asyncState);
}
public void Enddelete_manager(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_all_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public SystemCABundleManagerCABundleManagerStatistics get_all_statistics(
) {
object [] results = this.Invoke("get_all_statistics", new object [0]);
return ((SystemCABundleManagerCABundleManagerStatistics)(results[0]));
}
public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState);
}
public SystemCABundleManagerCABundleManagerStatistics Endget_all_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((SystemCABundleManagerCABundleManagerStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] managers
) {
object [] results = this.Invoke("get_description", new object [] {
managers});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] managers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
managers}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_exclude_bundle
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_exclude_bundle(
string [] managers
) {
object [] results = this.Invoke("get_exclude_bundle", new object [] {
managers});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_exclude_bundle(string [] managers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_exclude_bundle", new object[] {
managers}, callback, asyncState);
}
public string [] [] Endget_exclude_bundle(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_exclude_url
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_exclude_url(
string [] managers
) {
object [] results = this.Invoke("get_exclude_url", new object [] {
managers});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_exclude_url(string [] managers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_exclude_url", new object[] {
managers}, callback, asyncState);
}
public string [] [] Endget_exclude_url(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_include_bundle
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_include_bundle(
string [] managers
) {
object [] results = this.Invoke("get_include_bundle", new object [] {
managers});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_include_bundle(string [] managers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_include_bundle", new object[] {
managers}, callback, asyncState);
}
public string [] [] Endget_include_bundle(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_include_url
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_include_url(
string [] managers
) {
object [] results = this.Invoke("get_include_url", new object [] {
managers});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_include_url(string [] managers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_include_url", new object[] {
managers}, callback, asyncState);
}
public string [] [] Endget_include_url(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_proxy_port
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_proxy_port(
string [] managers
) {
object [] results = this.Invoke("get_proxy_port", new object [] {
managers});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_proxy_port(string [] managers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_proxy_port", new object[] {
managers}, callback, asyncState);
}
public long [] Endget_proxy_port(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_proxy_server
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_proxy_server(
string [] managers
) {
object [] results = this.Invoke("get_proxy_server", new object [] {
managers});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_proxy_server(string [] managers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_proxy_server", new object[] {
managers}, callback, asyncState);
}
public string [] Endget_proxy_server(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public SystemCABundleManagerCABundleManagerStatistics get_statistics(
string [] managers
) {
object [] results = this.Invoke("get_statistics", new object [] {
managers});
return ((SystemCABundleManagerCABundleManagerStatistics)(results[0]));
}
public System.IAsyncResult Beginget_statistics(string [] managers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_statistics", new object[] {
managers}, callback, asyncState);
}
public SystemCABundleManagerCABundleManagerStatistics Endget_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((SystemCABundleManagerCABundleManagerStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_timeout(
string [] managers
) {
object [] results = this.Invoke("get_timeout", new object [] {
managers});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_timeout(string [] managers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_timeout", new object[] {
managers}, callback, asyncState);
}
public long [] Endget_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_trusted_ca_bundle
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_trusted_ca_bundle(
string [] managers
) {
object [] results = this.Invoke("get_trusted_ca_bundle", new object [] {
managers});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_trusted_ca_bundle(string [] managers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_trusted_ca_bundle", new object[] {
managers}, callback, asyncState);
}
public string [] Endget_trusted_ca_bundle(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_update_interval
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_update_interval(
string [] managers
) {
object [] results = this.Invoke("get_update_interval", new object [] {
managers});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_update_interval(string [] managers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_update_interval", new object[] {
managers}, callback, asyncState);
}
public long [] Endget_update_interval(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// remove_all_exclude_bundles
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
public void remove_all_exclude_bundles(
string [] managers
) {
this.Invoke("remove_all_exclude_bundles", new object [] {
managers});
}
public System.IAsyncResult Beginremove_all_exclude_bundles(string [] managers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_exclude_bundles", new object[] {
managers}, callback, asyncState);
}
public void Endremove_all_exclude_bundles(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_all_exclude_urls
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
public void remove_all_exclude_urls(
string [] managers
) {
this.Invoke("remove_all_exclude_urls", new object [] {
managers});
}
public System.IAsyncResult Beginremove_all_exclude_urls(string [] managers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_exclude_urls", new object[] {
managers}, callback, asyncState);
}
public void Endremove_all_exclude_urls(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_all_include_bundles
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
public void remove_all_include_bundles(
string [] managers
) {
this.Invoke("remove_all_include_bundles", new object [] {
managers});
}
public System.IAsyncResult Beginremove_all_include_bundles(string [] managers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_include_bundles", new object[] {
managers}, callback, asyncState);
}
public void Endremove_all_include_bundles(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_all_include_urls
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
public void remove_all_include_urls(
string [] managers
) {
this.Invoke("remove_all_include_urls", new object [] {
managers});
}
public System.IAsyncResult Beginremove_all_include_urls(string [] managers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_include_urls", new object[] {
managers}, callback, asyncState);
}
public void Endremove_all_include_urls(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_exclude_bundle
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
public void remove_exclude_bundle(
string [] managers,
string [] [] bundles
) {
this.Invoke("remove_exclude_bundle", new object [] {
managers,
bundles});
}
public System.IAsyncResult Beginremove_exclude_bundle(string [] managers,string [] [] bundles, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_exclude_bundle", new object[] {
managers,
bundles}, callback, asyncState);
}
public void Endremove_exclude_bundle(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_exclude_url
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
public void remove_exclude_url(
string [] managers,
string [] [] urls
) {
this.Invoke("remove_exclude_url", new object [] {
managers,
urls});
}
public System.IAsyncResult Beginremove_exclude_url(string [] managers,string [] [] urls, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_exclude_url", new object[] {
managers,
urls}, callback, asyncState);
}
public void Endremove_exclude_url(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_include_bundle
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
public void remove_include_bundle(
string [] managers,
string [] [] bundles
) {
this.Invoke("remove_include_bundle", new object [] {
managers,
bundles});
}
public System.IAsyncResult Beginremove_include_bundle(string [] managers,string [] [] bundles, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_include_bundle", new object[] {
managers,
bundles}, callback, asyncState);
}
public void Endremove_include_bundle(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_include_url
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
public void remove_include_url(
string [] managers,
string [] [] urls
) {
this.Invoke("remove_include_url", new object [] {
managers,
urls});
}
public System.IAsyncResult Beginremove_include_url(string [] managers,string [] [] urls, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_include_url", new object[] {
managers,
urls}, callback, asyncState);
}
public void Endremove_include_url(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
public void set_description(
string [] managers,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
managers,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] managers,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
managers,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_proxy_port
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
public void set_proxy_port(
string [] managers,
long [] ports
) {
this.Invoke("set_proxy_port", new object [] {
managers,
ports});
}
public System.IAsyncResult Beginset_proxy_port(string [] managers,long [] ports, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_proxy_port", new object[] {
managers,
ports}, callback, asyncState);
}
public void Endset_proxy_port(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_proxy_server
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
public void set_proxy_server(
string [] managers,
string [] servers
) {
this.Invoke("set_proxy_server", new object [] {
managers,
servers});
}
public System.IAsyncResult Beginset_proxy_server(string [] managers,string [] servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_proxy_server", new object[] {
managers,
servers}, callback, asyncState);
}
public void Endset_proxy_server(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
public void set_timeout(
string [] managers,
long [] timeouts
) {
this.Invoke("set_timeout", new object [] {
managers,
timeouts});
}
public System.IAsyncResult Beginset_timeout(string [] managers,long [] timeouts, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_timeout", new object[] {
managers,
timeouts}, callback, asyncState);
}
public void Endset_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_trusted_ca_bundle
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
public void set_trusted_ca_bundle(
string [] managers,
string [] trusted_ca_bundles
) {
this.Invoke("set_trusted_ca_bundle", new object [] {
managers,
trusted_ca_bundles});
}
public System.IAsyncResult Beginset_trusted_ca_bundle(string [] managers,string [] trusted_ca_bundles, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_trusted_ca_bundle", new object[] {
managers,
trusted_ca_bundles}, callback, asyncState);
}
public void Endset_trusted_ca_bundle(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_update_interval
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
public void set_update_interval(
string [] managers,
long [] intervals
) {
this.Invoke("set_update_interval", new object [] {
managers,
intervals});
}
public System.IAsyncResult Beginset_update_interval(string [] managers,long [] intervals, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_update_interval", new object[] {
managers,
intervals}, callback, asyncState);
}
public void Endset_update_interval(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_update_now
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CABundleManager",
RequestNamespace="urn:iControl:System/CABundleManager", ResponseNamespace="urn:iControl:System/CABundleManager")]
public void set_update_now(
string [] managers,
SystemCABundleManagerUpdateNowCommand [] update_now
) {
this.Invoke("set_update_now", new object [] {
managers,
update_now});
}
public System.IAsyncResult Beginset_update_now(string [] managers,SystemCABundleManagerUpdateNowCommand [] update_now, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_update_now", new object[] {
managers,
update_now}, callback, asyncState);
}
public void Endset_update_now(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "System.CABundleManager.UpdateNowCommand", Namespace = "urn:iControl")]
public enum SystemCABundleManagerUpdateNowCommand
{
YES,
NO,
}
//=======================================================================
// Structs
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "System.CABundleManager.CABundleManagerStatistics", Namespace = "urn:iControl")]
public partial class SystemCABundleManagerCABundleManagerStatistics
{
private SystemCABundleManagerCABundleManagerStatisticsEntry [] statisticsField;
public SystemCABundleManagerCABundleManagerStatisticsEntry [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
private CommonTimeStamp time_stampField;
public CommonTimeStamp time_stamp
{
get { return this.time_stampField; }
set { this.time_stampField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "System.CABundleManager.CABundleManagerStatisticsEntry", Namespace = "urn:iControl")]
public partial class SystemCABundleManagerCABundleManagerStatisticsEntry
{
private string nameField;
public string name
{
get { return this.nameField; }
set { this.nameField = value; }
}
private string update_statusField;
public string update_status
{
get { return this.update_statusField; }
set { this.update_statusField = value; }
}
private CommonStatistic [] statisticsField;
public CommonStatistic [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
};
}
| |
/****************************************************************************/
/* */
/* The Mondo Libraries */
/* */
/* Namespace: Mondo.Xml */
/* File: cXMLWriter.cs */
/* Class(es): cXMLWriter */
/* Purpose: An XML writer */
/* */
/* Original Author: Jim Lightfoot */
/* Creation Date: 3 Jan 2002 */
/* */
/* Copyright (c) 2002-2016 - Jim Lightfoot, All rights reserved */
/* */
/* Licensed under the MIT license: */
/* http://www.opensource.org/licenses/mit-license.php */
/* */
/****************************************************************************/
using System;
using System.Xml;
using System.Xml.XPath;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Specialized;
using Mondo.Common;
namespace Mondo.Xml
{
/****************************************************************************/
/****************************************************************************/
/// <summary>
/// An XML writer that writes out a valid XML document
/// </summary>
public class cXMLWriter : Openable
{
private StringBuilder m_objXMLWriter;
private string m_strPath;
private bool m_bEndDocument = false;
private bool m_bHeader = false;
private string m_strIndent = "";
private Stack m_sTags = new Stack();
private bool m_bCurrentTagEnded = true;
private bool m_bSingleLine = false;
private TextWriter m_objTextWriter = null;
private string m_strRoot = "";
/****************************************************************************/
public cXMLWriter()
{
m_objXMLWriter = new StringBuilder();
m_strPath = "";
}
/****************************************************************************/
public cXMLWriter(TextWriter objWriter)
{
m_objXMLWriter = new StringBuilder();
m_strPath = "";
m_objTextWriter = objWriter;
}
/****************************************************************************/
public cXMLWriter(string strPath)
{
m_objXMLWriter = new StringBuilder();
m_strPath = strPath;
}
/****************************************************************************/
public void Clear()
{
m_objXMLWriter.Remove(0, m_objXMLWriter.Length);
}
/****************************************************************************/
public override void Open()
{
base.Open();
WriteStartDocument();
}
/****************************************************************************/
public override void Close()
{
WriteEndDocument();
base.Close();
}
/****************************************************************************/
public virtual void WriteStartDocument(string strFunctionName, string strXSL)
{
}
/****************************************************************************/
public virtual void WriteStartDocument()
{
}
/****************************************************************************/
public string Pop()
{
FinishStartTag();
string strReturn = m_objXMLWriter.ToString();
m_objXMLWriter.Length = 0;
return(strReturn);
}
/****************************************************************************/
public virtual void WriteStartDocument(bool bHeader)
{
m_bHeader = bHeader;
}
/****************************************************************************/
public virtual void WriteEndDocument()
{
if(!m_bEndDocument)
{
m_bEndDocument = true;
if(m_strPath.Length > 0)
ToFile(m_strPath);
if(m_objTextWriter != null)
m_objTextWriter.Write(m_objXMLWriter.ToString());
}
}
/****************************************************************************/
private void FinishStartTag()
{
FinishStartTag(true);
}
/****************************************************************************/
private void FinishStartTag(bool bNewline)
{
if(!m_bCurrentTagEnded)
{
if(bNewline)
m_objXMLWriter.Append(">\r\n");
else
{
m_objXMLWriter.Append(">");
m_bSingleLine = true;
}
m_bCurrentTagEnded = true;
}
}
/****************************************************************************/
public IDisposable Element(string strName)
{
return(new XmlElementWriter(this, strName));
}
/****************************************************************************/
public void WriteStartElement(string strTag)
{
FinishStartTag();
if(m_strRoot == "")
m_strRoot = strTag;
m_objXMLWriter.Append(m_strIndent + "<" + strTag);
m_strIndent += " ";
m_bSingleLine = false;
m_sTags.Push(strTag);
m_bCurrentTagEnded = false;
}
/****************************************************************************/
public void WriteEndElement()
{
m_strIndent = m_strIndent.Remove(0, 2);
string strTag = (string)m_sTags.Pop();
if(m_strRoot.ToLower() == "html" && (strTag.ToLower() == "link" || strTag.ToLower() == "script"))
FinishStartTag();
if(m_bCurrentTagEnded)
{
if(!m_bSingleLine)
m_objXMLWriter.Append(m_strIndent);
m_objXMLWriter.Append("</" + strTag + ">\r\n");
}
else
m_objXMLWriter.Append(" />\r\n");
m_bCurrentTagEnded = true;
m_bSingleLine = false;
}
/****************************************************************************/
public static string Encode(string strValue)
{
return(strValue.Replace("&", "&").Replace("<", "<").Replace(">", ">"));
}
/****************************************************************************/
public static string Decode(string strValue)
{
return(strValue.Replace("<", "<").Replace(">", ">").Replace("&", "&"));
}
/****************************************************************************/
public static string EncodeAttribute(string strValue)
{
return(strValue.Replace("\"", "'").Replace("&", "&").Replace("<", "<").Replace(">", ">"));
}
/****************************************************************************/
public static string EncodeXPath(string strValue)
{
return(strValue.Replace("\'", ""e;"));
}
/****************************************************************************/
public void WriteElementString(string strTag, string strValue, bool bEncode)
{
FinishStartTag();
if(bEncode)
strValue = Encode(strValue);
m_objXMLWriter.Append(m_strIndent + " " + "<" + strTag + ">" + strValue + "</" + strTag + ">\r\n");
}
/****************************************************************************/
public void WriteElementString(string strTag, string strValue)
{
WriteElementString(strTag, strValue, false);
}
/****************************************************************************/
public void WriteString(string strValue)
{
WriteString(strValue, false);
}
/****************************************************************************/
public void WriteString(string strValue, bool bEncode)
{
FinishStartTag(false);
if(bEncode)
strValue = Encode(strValue);
m_objXMLWriter.Append(strValue);
}
/****************************************************************************/
public void WriteAttributeString(string strName, string strValue, bool bEncode)
{
try
{
if(strValue != "")
{
if(bEncode)
strValue = EncodeAttribute(strValue);
_WriteAttributeString(strName, strValue);
}
}
catch(Exception e)
{
throw new Exception("WriteAttributeString(" + strName + "):" + e.Message);
}
}
/****************************************************************************/
private void _WriteAttributeString(string strName, string strValue)
{
m_objXMLWriter.Append(" " + strName + "=\"" + strValue + "\"");
}
/****************************************************************************/
public void WriteAttributeString(string strName, string strValue)
{
if(strValue != "")
_WriteAttributeString(strName, strValue);
}
/****************************************************************************/
public void WriteAttributeString(string strName, uint uValue)
{
_WriteAttributeString(strName, uValue.ToString());
}
/****************************************************************************/
public void WriteAttributeString(string strName, ulong uValue)
{
_WriteAttributeString(strName, uValue.ToString());
}
/****************************************************************************/
public void WriteAttributeString(string strName, double dValue)
{
_WriteAttributeString(strName, dValue.ToString());
}
/****************************************************************************/
public void WriteAttributeString(string strName, int iValue)
{
_WriteAttributeString(strName, iValue.ToString());
}
/****************************************************************************/
public void WriteAttributeString(string strName, long iValue)
{
_WriteAttributeString(strName, iValue.ToString());
}
/****************************************************************************/
public void WriteAttributeString(string strName, decimal dValue)
{
_WriteAttributeString(strName, dValue.ToString());
}
/****************************************************************************/
public void WriteAttributeString(string strName, bool bValue)
{
if(bValue)
_WriteAttributeString(strName, "1");
}
/****************************************************************************/
public void WriteAttributeString(string strName, Guid idValue)
{
_WriteAttributeString(strName, idValue.ToString());
}
/****************************************************************************/
public void WriteElementString(string strTag, uint uValue)
{
WriteElementString(strTag, uValue.ToString(), false);
}
/****************************************************************************/
public void WriteElementString(string strTag, int iValue)
{
WriteElementString(strTag, iValue.ToString(), false);
}
/****************************************************************************/
public void WriteElementString(string strTag, ushort uValue)
{
WriteElementString(strTag, uValue.ToString(), false);
}
/****************************************************************************/
public void WriteElementString(string strTag, double dValue)
{
WriteElementString(strTag, dValue.ToString(), false);
}
/****************************************************************************/
public void WriteElementString(string strTag, Guid idValue)
{
WriteElementString(strTag, idValue.ToString(), false);
}
/****************************************************************************/
public void WriteNode(XmlNode objNode)
{
WriteRaw(objNode.OuterXml);
}
/****************************************************************************/
public void WriteElementCDATA(string strTag, string strText)
{
WriteStartElement(strTag);
WriteCDATA(strText);
WriteEndElement();
}
/****************************************************************************/
public void WriteCDATA(string strText)
{
FinishStartTag(false);
m_objXMLWriter.Append("<![CDATA[" + strText + "]]>");
}
/****************************************************************************/
public void WriteRaw(string strXml)
{
FinishStartTag(true);
m_objXMLWriter.Append(strXml);
}
/****************************************************************************/
public void WriteElementString(string strTag, object objWrite)
{
WriteElementString(strTag, objWrite.ToString(), false);
}
/****************************************************************************/
public void WriteElementString(string strTag, bool bValue)
{
WriteElementString(strTag, bValue ? "1" : "0" , false);
}
/****************************************************************************/
public void WriteText(string strText)
{
WriteRaw(strText);
}
/****************************************************************************/
public void WriteText(string strText, bool bEncode)
{
if(bEncode)
strText = Encode(strText);
WriteRaw(strText);
}
/****************************************************************************/
public XmlDocument Xml
{
get
{
XmlDocument objXML = new XmlDocument();
GetXML(objXML);
return(objXML);
}
}
/****************************************************************************/
public XPathDocument XPath
{
get
{
using(StringReader s = new StringReader(ToString()))
return(new XPathDocument(s));
}
}
/****************************************************************************/
public void GetXML(XmlDocument objXML)
{
string strXML = ToString();
try
{
objXML.LoadXml(strXML);
}
catch(Exception e)
{
throw new Exception(e.Message + "\r\n" + strXML);
}
}
/****************************************************************************/
public void ToFile(string strPath)
{
if(strPath.Length > 0)
DiskFile.ToFile(ToString(), m_strPath);
}
/****************************************************************************/
public override string ToString()
{
WriteEndDocument();
return(m_objXMLWriter.ToString());
}
/****************************************************************************/
public void Write(XPathNodeIterator iterator)
{
while(iterator.MoveNext())
{
XPathNavigator nav = iterator.Current;
WriteRaw( nav.OuterXml );
}
}
/****************************************************************************/
public void WriteElements(StringCollection aElements, string strTagName)
{
if(aElements != null)
{
int nItems = aElements.Count / 2;
if(nItems > 0)
{
if(strTagName.Length > 0)
WriteStartElement(strTagName);
for(int i = 0; i < nItems; ++i)
WriteElementString(aElements[i*2], aElements[i*2+1]);
if(strTagName.Length > 0)
WriteEndElement();
}
}
}
}
/****************************************************************************/
/****************************************************************************/
public class XmlElementWriter : IDisposable
{
private readonly cXMLWriter m_objWriter;
/****************************************************************************/
public XmlElementWriter(cXMLWriter objWriter, string strName)
{
objWriter.WriteStartElement(strName);
m_objWriter = objWriter;
}
#region IDisposable Members
public void Dispose()
{
m_objWriter.WriteEndElement();
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine.Shared;
namespace Microsoft.Build.BuildEngine
{
#region Delegates
/// <summary>
/// Delegate to use for writing a string to some location like
/// the console window or the IDE build window.
/// </summary>
/// <param name="message"></param>
public delegate void WriteHandler(string message);
/// <summary>
/// Type of delegate used to set console color.
/// </summary>
/// <param name="color">Text color</param>
public delegate void ColorSetter(ConsoleColor color);
/// <summary>
/// Type of delegate used to reset console color.
/// </summary>
public delegate void ColorResetter();
#endregion
/// <summary>
/// This class implements the default logger that outputs event data
/// to the console (stdout).
/// It is a facade: it creates, wraps and delegates to a kind of BaseConsoleLogger,
/// either SerialConsoleLogger or ParallelConsoleLogger.
/// </summary>
/// <remarks>This class is not thread safe.</remarks>
public class ConsoleLogger : INodeLogger
{
private BaseConsoleLogger consoleLogger;
private int numberOfProcessors = 1;
private LoggerVerbosity verbosity;
private WriteHandler write;
private ColorSetter colorSet;
private ColorResetter colorReset;
private string parameters;
private bool skipProjectStartedText = false;
private bool? showSummary;
#region Constructors
/// <summary>
/// Default constructor.
/// </summary>
public ConsoleLogger()
: this(LoggerVerbosity.Normal)
{
// do nothing
}
/// <summary>
/// Create a logger instance with a specific verbosity. This logs to
/// the default console.
/// </summary>
/// <param name="verbosity">Verbosity level.</param>
public ConsoleLogger(LoggerVerbosity verbosity)
:
this
(
verbosity,
new WriteHandler(Console.Out.Write),
new ColorSetter(SetColor),
new ColorResetter(Console.ResetColor)
)
{
// do nothing
}
/// <summary>
/// Initializes the logger, with alternate output handlers.
/// </summary>
/// <param name="verbosity"></param>
/// <param name="write"></param>
/// <param name="colorSet"></param>
/// <param name="colorReset"></param>
public ConsoleLogger
(
LoggerVerbosity verbosity,
WriteHandler write,
ColorSetter colorSet,
ColorResetter colorReset
)
{
ErrorUtilities.VerifyThrowArgumentNull(write, nameof(write));
this.verbosity = verbosity;
this.write = write;
this.colorSet = colorSet;
this.colorReset = colorReset;
}
/// <summary>
/// This is called by every event handler for compat reasons -- see DDB #136924
/// However it will skip after the first call
/// </summary>
private void InitializeBaseConsoleLogger()
{
if (consoleLogger == null)
{
bool useMPLogger = false;
if (!string.IsNullOrEmpty(parameters))
{
string [] parameterComponents = parameters.Split(BaseConsoleLogger.parameterDelimiters);
for (int param = 0; param < parameterComponents.Length; param++)
{
if (parameterComponents[param].Length > 0)
{
if (String.Equals(parameterComponents[param], "ENABLEMPLOGGING", StringComparison.OrdinalIgnoreCase))
{
useMPLogger = true;
}
if (String.Equals(parameterComponents[param], "DISABLEMPLOGGING", StringComparison.OrdinalIgnoreCase))
{
useMPLogger = false;
}
}
}
}
if (numberOfProcessors == 1 && !useMPLogger)
{
consoleLogger = new SerialConsoleLogger(verbosity, write, colorSet, colorReset);
}
else
{
consoleLogger = new ParallelConsoleLogger(verbosity, write, colorSet, colorReset);
}
if(!string.IsNullOrEmpty(parameters))
{
consoleLogger.Parameters = parameters;
parameters = null;
}
if (showSummary != null)
{
consoleLogger.ShowSummary = (bool)showSummary;
}
consoleLogger.SkipProjectStartedText = skipProjectStartedText;
}
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the level of detail to show in the event log.
/// </summary>
/// <value>Verbosity level.</value>
public LoggerVerbosity Verbosity
{
get
{
return consoleLogger == null ? verbosity : consoleLogger.Verbosity;
}
set
{
if (consoleLogger == null)
{
verbosity = value;
}
else
{
consoleLogger.Verbosity = value;
}
}
}
/// <summary>
/// The console logger takes a single parameter to suppress the output of the errors
/// and warnings summary at the end of a build.
/// </summary>
/// <value>null</value>
public string Parameters
{
get
{
return consoleLogger == null ? parameters : consoleLogger.Parameters;
}
set
{
if (consoleLogger == null)
{
parameters = value;
}
else
{
consoleLogger.Parameters = value;
}
}
}
/// <summary>
/// Suppresses the display of project headers. Project headers are
/// displayed by default unless this property is set.
/// </summary>
/// <remarks>This is only needed by the IDE logger.</remarks>
public bool SkipProjectStartedText
{
get
{
return consoleLogger == null ? skipProjectStartedText : consoleLogger.SkipProjectStartedText;
}
set
{
if (consoleLogger == null)
{
skipProjectStartedText = value;
}
else
{
consoleLogger.SkipProjectStartedText = value;
}
}
}
/// <summary>
/// Suppresses the display of error and warnings summary.
/// </summary>
public bool ShowSummary
{
get
{
return (consoleLogger == null ? showSummary : consoleLogger.ShowSummary) ?? false;
}
set
{
if (consoleLogger == null)
{
showSummary = value;
}
else
{
consoleLogger.ShowSummary = value;
}
}
}
/// <summary>
/// Provide access to the write hander delegate so that it can be redirected
/// if necessary (e.g. to a file)
/// </summary>
protected WriteHandler WriteHandler
{
get
{
return consoleLogger == null ? write : consoleLogger.write;
}
set
{
if (consoleLogger == null)
{
write = value;
}
else
{
consoleLogger.write = value;
}
}
}
#endregion
#region Methods
/// <summary>
/// Apply a parameter.
/// NOTE: This method was public by accident in Whidbey, so it cannot be made internal now. It has
/// no good reason for being public.
/// </summary>
public void ApplyParameter(string parameterName, string parameterValue)
{
ErrorUtilities.VerifyThrowInvalidOperation(consoleLogger != null, "MustCallInitializeBeforeApplyParameter");
consoleLogger.ApplyParameter(parameterName, parameterValue);
}
/// <summary>
/// Signs up the console logger for all build events.
/// </summary>
/// <param name="eventSource">Available events.</param>
public virtual void Initialize(IEventSource eventSource)
{
InitializeBaseConsoleLogger();
consoleLogger.Initialize(eventSource);
}
public virtual void Initialize(IEventSource eventSource, int nodeCount)
{
this.numberOfProcessors = nodeCount;
InitializeBaseConsoleLogger();
consoleLogger.Initialize(eventSource, nodeCount);
}
/// <summary>
/// The console logger does not need to release any resources.
/// This method does nothing.
/// </summary>
public virtual void Shutdown()
{
consoleLogger?.Shutdown();
}
/// <summary>
/// Handler for build started events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
public void BuildStartedHandler(object sender, BuildStartedEventArgs e)
{
InitializeBaseConsoleLogger(); // for compat: see DDB#136924
consoleLogger.BuildStartedHandler(sender, e);
}
/// <summary>
/// Handler for build finished events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
public void BuildFinishedHandler(object sender, BuildFinishedEventArgs e)
{
InitializeBaseConsoleLogger(); // for compat: see DDB#136924
consoleLogger.BuildFinishedHandler(sender, e);
}
/// <summary>
/// Handler for project started events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
public void ProjectStartedHandler(object sender, ProjectStartedEventArgs e)
{
InitializeBaseConsoleLogger(); // for compat: see DDB#136924
consoleLogger.ProjectStartedHandler(sender, e);
}
/// <summary>
/// Handler for project finished events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
public void ProjectFinishedHandler(object sender, ProjectFinishedEventArgs e)
{
InitializeBaseConsoleLogger(); // for compat: see DDB#136924
consoleLogger.ProjectFinishedHandler(sender, e);
}
/// <summary>
/// Handler for target started events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
public void TargetStartedHandler(object sender, TargetStartedEventArgs e)
{
InitializeBaseConsoleLogger(); // for compat: see DDB#136924
consoleLogger.TargetStartedHandler(sender, e);
}
/// <summary>
/// Handler for target finished events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
public void TargetFinishedHandler(object sender, TargetFinishedEventArgs e)
{
InitializeBaseConsoleLogger(); // for compat: see DDB#136924
consoleLogger.TargetFinishedHandler(sender, e);
}
/// <summary>
/// Handler for task started events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
public void TaskStartedHandler(object sender, TaskStartedEventArgs e)
{
InitializeBaseConsoleLogger(); // for compat: see DDB#136924
consoleLogger.TaskStartedHandler(sender, e);
}
/// <summary>
/// Handler for task finished events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
public void TaskFinishedHandler(object sender, TaskFinishedEventArgs e)
{
InitializeBaseConsoleLogger(); // for compat: see DDB#136924
consoleLogger.TaskFinishedHandler(sender, e);
}
/// <summary>
/// Prints an error event
/// </summary>
public void ErrorHandler(object sender, BuildErrorEventArgs e)
{
InitializeBaseConsoleLogger(); // for compat: see DDB#136924
consoleLogger.ErrorHandler(sender, e);
}
/// <summary>
/// Prints a warning event
/// </summary>
public void WarningHandler(object sender, BuildWarningEventArgs e)
{
InitializeBaseConsoleLogger(); // for compat: see DDB#136924
consoleLogger.WarningHandler(sender, e);
}
/// <summary>
/// Prints a message event
/// </summary>
public void MessageHandler(object sender, BuildMessageEventArgs e)
{
InitializeBaseConsoleLogger(); // for compat: see DDB#136924
consoleLogger.MessageHandler(sender, e);
}
/// <summary>
/// Prints a custom event
/// </summary>
public void CustomEventHandler(object sender, CustomBuildEventArgs e)
{
InitializeBaseConsoleLogger(); // for compat: see DDB#136924
consoleLogger.CustomEventHandler(sender, e);
}
/// <summary>
/// Sets foreground color to color specified
/// </summary>
/// <param name="c">foreground color</param>
internal static void SetColor(ConsoleColor c)
{
Console.ForegroundColor =
TransformColor(c, Console.BackgroundColor);
}
/// <summary>
/// Changes the foreground color to black if the foreground is the
/// same as the background. Changes the foreground to white if the
/// background is black.
/// </summary>
/// <param name="foreground">foreground color for black</param>
/// <param name="background">current background</param>
private static ConsoleColor TransformColor(ConsoleColor foreground,
ConsoleColor background)
{
ConsoleColor result = foreground; //typically do nothing ...
if (foreground == background)
{
if (background != ConsoleColor.Black)
{
result = ConsoleColor.Black;
}
else
{
result = ConsoleColor.Gray;
}
}
return result;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Serialization.Formatters;
using System.Threading;
using System.Web;
using Codentia.Common.Logging.DL;
namespace Codentia.Common.Logging.BL
{
/// <summary>
/// Singleton class responsible for managing logging. From specification:
/// <para></para>
/// * Creates and manages message queue
/// * Exposes methods for logging messages
/// * Exception
/// * Message by elements (e.g. source, etc)
/// * Source can be passed in as an object or a string
/// * Will flush messages out upon disposal
/// * Responsible for log-roll-over and creation of folders if absent
/// <para></para>
/// <seealso cref="LogMessage"/>
/// </summary>
public sealed class LogManager : MarshalByRefObject, IDisposable
{
private static LogManager _instance;
private static object _instanceLock = new object();
private static object _queueLock = new object();
private static object _writerLock = new object();
private static int _portNumber = LogManager.RemotingPort;
private Thread _writerThread;
private Thread _cleanupThread;
private bool _running;
private Dictionary<LogMessageType, LogTarget[]> _mappings = new Dictionary<LogMessageType, LogTarget[]>();
private Dictionary<LogMessageType, string[]> _mappingEmail = new Dictionary<LogMessageType, string[]>();
private Dictionary<LogMessageType, string> _mappingFilename = new Dictionary<LogMessageType, string>();
private Dictionary<LogMessageType, string> _mappingDatabaseName = new Dictionary<LogMessageType, string>();
private List<LogMessage> _messageQueue;
private bool _autoCleanUpDatabase = false;
private int _databaseRetentionDays = 0;
private bool _autoCleanUpFile = false;
private int _fileRetentionSizeKB = 0;
private int _fileRetentionCount = 0;
private LogManager()
{
// load mapping configuration
NameValueCollection targetMappings = (NameValueCollection)ConfigurationManager.GetSection("Codentia.Common.Logging/TargetMapping");
if (targetMappings != null)
{
for (int i = 0; i < targetMappings.AllKeys.Length; i++)
{
LogMessageType current = (LogMessageType)Enum.Parse(typeof(LogMessageType), targetMappings.AllKeys[i], true);
string[] targets = Convert.ToString(targetMappings[current.ToString()]).Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
List<LogTarget> targetList = new List<LogTarget>();
List<string> emailList = new List<string>();
string alternativeFile = null;
string databaseName = null;
for (int j = 0; j < targets.Length; j++)
{
if (targets[j].StartsWith("email", StringComparison.CurrentCultureIgnoreCase))
{
targetList.Add(LogTarget.Email);
emailList.Add(targets[j].Substring(targets[j].IndexOf("~") + 1));
}
else
{
if (targets[j].StartsWith("file", StringComparison.CurrentCultureIgnoreCase))
{
targetList.Add(LogTarget.File);
if (targets[j].Contains("~"))
{
alternativeFile = targets[j].Substring(targets[j].IndexOf("~") + 1);
}
}
else
if (targets[j].StartsWith("database", StringComparison.CurrentCultureIgnoreCase))
{
targetList.Add(LogTarget.Database);
if (targets[j].Contains("~"))
{
databaseName = targets[j].Substring(targets[j].IndexOf("~") + 1);
}
}
else
{
targetList.Add((LogTarget)Enum.Parse(typeof(LogTarget), targets[j], true));
}
}
}
_mappings.Add(current, targetList.ToArray());
if (targetList.Contains(LogTarget.Email))
{
if (emailList.Count > 0)
{
_mappingEmail.Add(current, emailList.ToArray());
}
}
if (targetList.Contains(LogTarget.File))
{
if (!string.IsNullOrEmpty(alternativeFile))
{
_mappingFilename.Add(current, alternativeFile);
}
else
{
_mappingFilename.Add(current, "SystemLog.txt");
}
}
if (targetList.Contains(LogTarget.Database))
{
_mappingDatabaseName.Add(current, databaseName);
}
}
}
// load retention/clean-up configuration
NameValueCollection databaseRetention = (NameValueCollection)ConfigurationManager.GetSection("Codentia.Common.Logging/RetentionPolicy/Database");
NameValueCollection fileRetention = (NameValueCollection)ConfigurationManager.GetSection("Codentia.Common.Logging/RetentionPolicy/File");
if (databaseRetention != null)
{
_autoCleanUpDatabase = Convert.ToBoolean(databaseRetention["AutoCleanUp"]);
_databaseRetentionDays = Convert.ToInt32(databaseRetention["RetainDays"]);
}
if (fileRetention != null)
{
_autoCleanUpFile = Convert.ToBoolean(fileRetention["AutoCleanUp"]);
_fileRetentionSizeKB = Convert.ToInt32(fileRetention["RollOverSizeKB"]);
_fileRetentionCount = Convert.ToInt32(fileRetention["RollOverFileCount"]);
}
// now set up remaining objects
_running = true;
_messageQueue = new List<LogMessage>();
if (_autoCleanUpDatabase || _autoCleanUpFile)
{
_cleanupThread = new Thread(new ThreadStart(CleanUp));
_cleanupThread.Start();
}
_writerThread = new Thread(new ThreadStart(WriteMessages));
_writerThread.Start();
}
/// <summary>
/// Gets the instance.
/// </summary>
public static LogManager Instance
{
get
{
lock (_instanceLock)
{
// safety check
if (_instance != null)
{
try
{
_instance.CheckConnectionIsValid();
}
catch (Exception)
{
_instance = null;
}
}
if (_instance == null)
{
TcpChannel channel;
try
{
IDictionary props = (IDictionary)new Hashtable();
props["port"] = _portNumber;
props["name"] = System.AppDomain.CurrentDomain.FriendlyName;
// Creating a custom formatter for a TcpChannel sink chain.
BinaryServerFormatterSinkProvider provider = new BinaryServerFormatterSinkProvider();
provider.TypeFilterLevel = TypeFilterLevel.Full;
channel = new TcpChannel(props, null, provider);
ChannelServices.RegisterChannel(channel, false);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(LogManager), "LogManager", WellKnownObjectMode.Singleton);
_instance = (LogManager)Activator.GetObject(typeof(LogManager), string.Format("tcp://localhost:{0}/LogManager", _portNumber));
}
catch (SocketException)
{
_instance = (LogManager)Activator.GetObject(typeof(LogManager), string.Format("tcp://localhost:{0}/LogManager", _portNumber));
}
}
return _instance;
}
}
}
/// <summary>
/// Gets the get remoting port.
/// </summary>
private static int RemotingPort
{
get
{
// generate a unique, predictable port number by hashing the current app domain and seeding the RNG with it
Random r = new Random(System.AppDomain.CurrentDomain.FriendlyName.GetHashCode());
int port = r.Next(11000, 21999);
return port;
}
}
/// <summary>
/// Checks the connection is valid.
/// This is a dummy method - calls to it will throw an exception on the remote end (which is used in the instance property above), if invalid.
/// </summary>
/// <returns>bool - true</returns>
public bool CheckConnectionIsValid()
{
return true;
}
/// <summary>
/// Add a message to the logging queue
/// </summary>
/// <param name="request">HttpRequest to log</param>
public void AddToLog(UrlAccessMessage request)
{
AddMessageToQueue(request);
}
/// <summary>
/// Add a message to the logging queue
/// </summary>
/// <param name="exception">Exception to be logged</param>
/// <param name="source">Source of the exception</param>
public void AddToLog(Exception exception, string source)
{
UrlAccessMessage httpMessage = null;
if (HttpContext.Current != null && HttpContext.Current.Request != null)
{
httpMessage = new UrlAccessMessage(HttpContext.Current.Request);
}
AddMessageToQueue(new LogMessage(LogMessageType.FatalError, source, string.Format("{0}{1}{2}{3}{4}{5}{6}{7}", exception.Source, System.Environment.NewLine, exception.Message, System.Environment.NewLine, exception.StackTrace, System.Environment.NewLine, exception.TargetSite, httpMessage != null ? string.Concat(System.Environment.NewLine, httpMessage.Message) : string.Empty)));
}
/// <summary>
/// Add a message to the logging queue
/// </summary>
/// <param name="exception">Exception to be logged</param>
/// <param name="source">Source of the exception</param>
public void AddToLog(WebException exception, string source)
{
string errorResponse = string.Empty;
if (exception.Response != null)
{
StreamReader sr = new StreamReader(exception.Response.GetResponseStream());
errorResponse = sr.ReadToEnd();
sr.Close();
sr.Dispose();
}
AddMessageToQueue(new LogMessage(LogMessageType.FatalError, source, string.Format("Response={0}, Message={1}, StackTrace={2}", errorResponse, exception.Message, System.Environment.NewLine, exception.StackTrace)));
}
/// <summary>
/// Add a message to the logging queue
/// </summary>
/// <param name="type">Type of message</param>
/// <param name="source">Source of message</param>
/// <param name="message">Content of message</param>
public void AddToLog(LogMessageType type, string source, string message)
{
AddMessageToQueue(new LogMessage(type, source, message));
}
/// <summary>
/// Force all queued messages to be written out immediately
/// </summary>
public void Flush()
{
lock (_queueLock)
{
if (_messageQueue.Count > 0)
{
for (int i = 0; i < _messageQueue.Count; i++)
{
WriteMessage(_messageQueue[i]);
}
_messageQueue.Clear();
_messageQueue.TrimExcess();
}
}
}
/// <summary>
/// Stop processing and clean up the object immediately
/// </summary>
public void Dispose()
{
Flush();
lock (_instanceLock)
{
_running = false;
if (_writerThread != null)
{
_writerThread.Join();
}
if (_cleanupThread != null)
{
_cleanupThread.Join();
}
_instance = null;
}
}
private void WriteMessages()
{
while (_running)
{
LogMessage[] messagesToWrite = null;
lock (_queueLock)
{
_messageQueue.TrimExcess();
if (_messageQueue.Count > 0)
{
if (_messageQueue.Count < 10)
{
messagesToWrite = _messageQueue.ToArray();
_messageQueue.Clear();
_messageQueue.TrimExcess();
}
else
{
messagesToWrite = new LogMessage[10];
_messageQueue.CopyTo(0, messagesToWrite, 0, 10);
_messageQueue.RemoveRange(0, 10);
_messageQueue.TrimExcess();
}
}
}
// write messages here
if (messagesToWrite != null)
{
for (int i = 0; i < messagesToWrite.Length; i++)
{
WriteMessage(messagesToWrite[i]);
}
}
Thread.Sleep(50);
}
}
private void WriteMessage(LogMessage message)
{
lock (_writerLock)
{
if (_mappings.ContainsKey(message.Type))
{
LogTarget[] targets = _mappings[message.Type];
string[] emailAddresses = null;
if (_mappingEmail.ContainsKey(message.Type))
{
emailAddresses = _mappingEmail[message.Type];
}
int emailPointer = 0;
for (int i = 0; i < targets.Length; i++)
{
switch (targets[i])
{
case LogTarget.Console:
ConsoleLogWriter consoleWriter = new ConsoleLogWriter();
consoleWriter.Write(message);
consoleWriter.Dispose();
break;
case LogTarget.Database:
DatabaseLogWriter databaseWriter = new DatabaseLogWriter();
databaseWriter.LogTarget = _mappingDatabaseName[message.Type];
databaseWriter.Write(message);
databaseWriter.Dispose();
break;
case LogTarget.Email:
EmailLogWriter emailWriter = new EmailLogWriter();
emailWriter.LogTarget = emailAddresses[emailPointer];
emailWriter.Write(message);
emailWriter.Dispose();
emailPointer++;
break;
case LogTarget.File:
FileLogWriter fileWriter = new FileLogWriter();
fileWriter.LogTarget = _mappingFilename[message.Type];
fileWriter.Write(message);
fileWriter.Dispose();
break;
}
}
}
}
}
private void AddMessageToQueue(LogMessage message)
{
lock (_queueLock)
{
_messageQueue.Add(message);
}
}
private void CleanUp()
{
while (_running)
{
if (_autoCleanUpDatabase)
{
lock (_writerLock)
{
Dictionary<LogMessageType, DateTime> retentionDates = new Dictionary<LogMessageType, DateTime>();
retentionDates[LogMessageType.FatalError] = DateTime.Now.AddDays(-1 * _databaseRetentionDays);
retentionDates[LogMessageType.NonFatalError] = DateTime.Now.AddDays(-1 * _databaseRetentionDays);
retentionDates[LogMessageType.Information] = DateTime.Now.AddDays(-1 * _databaseRetentionDays);
retentionDates[LogMessageType.UrlRequest] = DateTime.Now.AddDays(-1 * _databaseRetentionDays);
Dictionary<LogMessageType, string>.Enumerator enumMappings = _mappingDatabaseName.GetEnumerator();
while (enumMappings.MoveNext())
{
DatabaseLogWriter writer = new DatabaseLogWriter();
writer.LogTarget = enumMappings.Current.Value;
writer.CleanUp(0, 0, retentionDates);
writer.Close();
writer.Dispose();
}
}
}
if (_autoCleanUpFile)
{
lock (_writerLock)
{
IEnumerator<LogMessageType> files = _mappingFilename.Keys.GetEnumerator();
while (files.MoveNext())
{
FileLogWriter writer = new FileLogWriter();
writer.LogTarget = _mappingFilename[files.Current];
writer.CleanUp(_fileRetentionSizeKB, _fileRetentionCount, null);
writer.Close();
writer.Dispose();
}
}
}
for (int i = 0; i < 300 && _running; i++)
{
Thread.Sleep(100);
}
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Orleans.Internal;
using Orleans.Runtime;
using Orleans.Serialization;
namespace Orleans.CodeGeneration
{
/// <summary>
/// Functionality for invoking calls on a generic instance method.
/// </summary>
/// <remarks>
/// Each instance of this class can invoke calls on one generic method.
/// </remarks>
public class GenericMethodInvoker : IEqualityComparer<object[]>
{
private static readonly ConcurrentDictionary<Type, MethodInfo> BoxMethods = new ConcurrentDictionary<Type, MethodInfo>();
private static readonly Func<Type, MethodInfo> CreateBoxMethod = GetTaskConversionMethod;
private static readonly MethodInfo GenericMethodInvokerDelegateMethodInfo =
TypeUtils.Method((GenericMethodInvokerDelegate del) => del.Invoke(null, null));
private static readonly ILFieldBuilder FieldBuilder = new ILFieldBuilder();
private readonly MethodInfo genericMethodInfo;
private readonly Type grainInterfaceType;
private readonly int typeParameterCount;
private readonly ConcurrentDictionary<object[], GenericMethodInvokerDelegate> invokers;
private readonly Func<object[], GenericMethodInvokerDelegate> createInvoker;
/// <summary>
/// Invoke the generic method described by this instance on the provided <paramref name="grain"/>.
/// </summary>
/// <param name="grain">The grain.</param>
/// <param name="arguments">The arguments, including the method's type parameters.</param>
/// <returns>The method result.</returns>
private delegate Task<object> GenericMethodInvokerDelegate(IAddressable grain, object[] arguments);
/// <summary>
/// Initializes a new instance of the <see cref="GenericMethodInvoker"/> class.
/// </summary>
/// <param name="grainInterfaceType">The grain interface type which the method exists on.</param>
/// <param name="methodName">The name of the method.</param>
/// <param name="typeParameterCount">The number of type parameters which the method has.</param>
public GenericMethodInvoker(Type grainInterfaceType, string methodName, int typeParameterCount)
{
this.grainInterfaceType = grainInterfaceType;
this.typeParameterCount = typeParameterCount;
this.invokers = new ConcurrentDictionary<object[], GenericMethodInvokerDelegate>(this);
this.genericMethodInfo = GetMethod(grainInterfaceType, methodName, typeParameterCount);
this.createInvoker = this.CreateInvoker;
}
/// <summary>
/// Invoke the defined method on the provided <paramref name="grain"/> instance with the given <paramref name="arguments"/>.
/// </summary>
/// <param name="grain">The grain.</param>
/// <param name="arguments">The arguments to the method with the type parameters first, followed by the method parameters.</param>
/// <returns>The invocation result.</returns>
public Task<object> Invoke(IAddressable grain, object[] arguments)
{
var invoker = this.invokers.GetOrAdd(arguments, this.createInvoker);
return invoker(grain, arguments);
}
/// <summary>
/// Creates an invoker delegate for the type arguments specified in <paramref name="arguments"/>.
/// </summary>
/// <param name="arguments">The arguments.</param>
/// <returns>A new invoker delegate.</returns>
private GenericMethodInvokerDelegate CreateInvoker(object[] arguments)
{
// First, create the concrete method which will be called.
var typeParameters = arguments.Take(this.typeParameterCount).Cast<Type>().ToArray();
var concreteMethod = this.genericMethodInfo.MakeGenericMethod(typeParameters);
// Next, create a delegate which will call the method on the grain, pushing each of the arguments,
var il = new ILDelegateBuilder<GenericMethodInvokerDelegate>(
FieldBuilder,
$"GenericMethodInvoker_{this.grainInterfaceType}_{concreteMethod.Name}",
GenericMethodInvokerDelegateMethodInfo);
// Load the grain and cast it to the type the concrete method is declared on.
// Eg: cast from IAddressable to IGrainWithGenericMethod.
il.LoadArgument(0);
il.CastOrUnbox(this.grainInterfaceType);
// Load each of the method parameters from the argument array, skipping the type parameters.
var methodParameters = concreteMethod.GetParameters();
for (var i = 0; i < methodParameters.Length; i++)
{
il.LoadArgument(1); // Load the argument array.
// Skip the type parameters and load the particular argument.
il.LoadConstant(i + this.typeParameterCount);
il.LoadReferenceElement();
// Cast the argument from 'object' to the type expected by the concrete method.
il.CastOrUnbox(methodParameters[i].ParameterType);
}
// Call the concrete method.
il.Call(concreteMethod);
// If the result type is Task or Task<T>, convert it to Task<object>.
var returnType = concreteMethod.ReturnType;
if (returnType != typeof(Task<object>))
{
var boxMethod = BoxMethods.GetOrAdd(returnType, CreateBoxMethod);
il.Call(boxMethod);
}
// Return the resulting Task<object>.
il.Return();
return il.CreateDelegate();
}
/// <summary>
/// Returns a suitable <see cref="MethodInfo"/> for a method which will convert an argument of type <paramref name="taskType"/>
/// into <see cref="Task{Object}"/>.
/// </summary>
/// <param name="taskType">The type to convert.</param>
/// <returns>A suitable conversion method.</returns>
private static MethodInfo GetTaskConversionMethod(Type taskType)
{
if (taskType == typeof(Task)) return TypeUtils.Method((Task task) => task.ToUntypedTask());
if (taskType == typeof(Task<object>)) return TypeUtils.Method((Task<object> task) => task.ToUntypedTask());
if (taskType == typeof(void)) return TypeUtils.Property(() => Task.CompletedTask).GetMethod;
if (taskType.GetGenericTypeDefinition() != typeof(Task<>))
throw new ArgumentException($"Unsupported return type {taskType}.");
var innerType = taskType.GenericTypeArguments[0];
var methods = typeof(OrleansTaskExtentions).GetMethods(BindingFlags.Static | BindingFlags.Public);
foreach (var method in methods)
{
if (method.Name != nameof(OrleansTaskExtentions.ToUntypedTask) || !method.ContainsGenericParameters) continue;
return method.MakeGenericMethod(innerType);
}
throw new ArgumentException($"Could not find conversion method for type {taskType}");
}
/// <summary>
/// Performs equality comparison for the purpose of comparing type parameters only.
/// </summary>
/// <param name="x">One argument list.</param>
/// <param name="y">The other argument list.</param>
/// <returns><see langword="true"/> if the type parameters in the respective arguments are equal, <see langword="false"/> otherwise.</returns>
bool IEqualityComparer<object[]>.Equals(object[] x, object[] y)
{
if (ReferenceEquals(x, y)) return true;
if (ReferenceEquals(x, null)) return false;
if (ReferenceEquals(null, y)) return false;
// Since this equality compararer only compares type parameters, ignore any elements after
// the defined type parameter count.
if (x.Length < this.typeParameterCount || y.Length < this.typeParameterCount) return false;
// Compare each type parameter.
for (var i = 0; i < this.typeParameterCount; i++)
{
if (x[i] as Type != y[i] as Type) return false;
}
return true;
}
/// <summary>
/// Returns a hash code for the type parameters in the provided argument list.
/// </summary>
/// <param name="obj">The argument list.</param>
/// <returns>A hash code.</returns>
int IEqualityComparer<object[]>.GetHashCode(object[] obj)
{
if (obj == null || obj.Length == 0) return 0;
unchecked
{
// Only consider the type parameters.
var result = 0;
for (var i = 0; i < this.typeParameterCount && i < obj.Length; i++)
{
var type = obj[i] as Type;
if (type == null) break;
result = (result * 367) ^ type.GetHashCode();
}
return result;
}
}
/// <summary>
/// Returns the <see cref="MethodInfo"/> for the method on <paramref name="declaringType"/> with the provided name
/// and number of generic type parameters.
/// </summary>
/// <param name="declaringType">The type which the method is declared on.</param>
/// <param name="methodName">The method name.</param>
/// <param name="typeParameterCount">The number of generic type parameters.</param>
/// <returns>The identified method.</returns>
private static MethodInfo GetMethod(Type declaringType, string methodName, int typeParameterCount)
{
var methods = declaringType.GetMethods(BindingFlags.Instance | BindingFlags.Public);
foreach (var method in methods)
{
if (!method.IsGenericMethodDefinition) continue;
if (!string.Equals(method.Name, methodName, StringComparison.Ordinal)) continue;
if (method.GetGenericArguments().Length != typeParameterCount) continue;
return method;
}
throw new ArgumentException(
$"Could not find generic method {declaringType}.{methodName}<{new string(',', typeParameterCount - 1)}>(...).");
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System.Collections.Generic;
using Microsoft.PythonTools.Analysis.Values;
using Microsoft.PythonTools.Parsing.Ast;
namespace Microsoft.PythonTools.Intellisense {
/// <summary>
/// Finds the outer most enclosing node(s) for the given selection as well as the set of parent nodes
/// which lead to the selected nodes. Provides this back as a SelectionTarget which encapsulates all
/// of the data for performing the refactoring.
/// </summary>
class EnclosingNodeWalker : PythonWalker {
private readonly PythonAst _root;
private readonly int _start, _end;
private SelectionTarget _targetNode;
private List<ScopeStatement> _parents = new List<ScopeStatement>();
private List<SuiteStatement> _suites = new List<SuiteStatement>();
private Dictionary<ScopeStatement, int> _insertLocations = new Dictionary<ScopeStatement, int>();
public EnclosingNodeWalker(PythonAst root, int start, int end) {
_start = start;
_end = end;
_root = root;
}
/// <summary>
/// Provides information about the target node(s) which end up being selected.
/// </summary>
public SelectionTarget Target {
get {
return _targetNode;
}
}
private bool ShouldWalkWorker(Node node) {
if (node is ScopeStatement) {
_suites.Add(null); // marker for a function/class boundary
_parents.Add((ScopeStatement)node);
}
return node.StartIndex <= _end && node.EndIndex >= _start;
}
private bool ShouldWalkWorker(SuiteStatement node) {
if (ShouldWalkWorker((Node)node)) {
_suites.Add(node);
foreach (var stmt in node.Statements) {
stmt.Walk(this);
if (_targetNode != null) {
// we have found our extracted code below this,
// we should insert before this statement.
_insertLocations[_parents[_parents.Count - 1]] = stmt.GetStartIncludingIndentation(_root);
break;
}
}
_suites.Pop();
}
return false;
}
private void PostWalkWorker(SuiteStatement node) {
if (_targetNode == null && node.StartIndex <= _start && node.EndIndex >= _end) {
// figure out the range of statements we cover...
int startIndex = 0, endIndex = node.Statements.Count - 1;
for (int i = 0; i < node.Statements.Count; i++) {
if (node.Statements[i].EndIndex >= _start) {
startIndex = i;
break;
}
}
for (int i = node.Statements.Count - 1; i >= 0; i--) {
if (node.Statements[i].StartIndex < _end) {
endIndex = i;
break;
}
}
List<SuiteStatement> followingSuites = new List<SuiteStatement>();
for (int i = _suites.Count - 1; i >= 0; i--) {
if (_suites[i] == null) {
// we hit our marker, this is a function/class boundary
// We don't care about any suites which come before the marker
// because they live in a different scope. We insert the marker in
// ShouldWalkWorker(Node node) when we have a ScopeStatement.
break;
}
followingSuites.Add(_suites[i]);
}
_targetNode = new SuiteTarget(
_insertLocations,
_parents.ToArray(),
node,
followingSuites.ToArray(),
_end,
startIndex,
endIndex
);
_insertLocations[_parents[_parents.Count - 1]] = node.Statements.Count == 0 ?
node.GetStartIncludingIndentation(_root) :
node.Statements[startIndex].GetStartIncludingIndentation(_root);
}
}
private void PostWalkWorker(IfStatementTest node) {
}
private void PostWalkWorker(Node node) {
if (node is ScopeStatement) {
_suites.Pop();
_parents.Remove((ScopeStatement)node);
}
if (_targetNode == null &&
node.StartIndex <= _start &&
node.EndIndex >= _end &&
node is Expression) {
_targetNode = new NodeTarget(_insertLocations, _parents.ToArray(), node);
}
}
#region Walk/PostWalk Overrides
// AndExpression
public override bool Walk(AndExpression node) { return ShouldWalkWorker(node); }
public override void PostWalk(AndExpression node) { PostWalkWorker(node); }
// BackQuoteExpression
public override bool Walk(BackQuoteExpression node) { return ShouldWalkWorker(node); }
public override void PostWalk(BackQuoteExpression node) { PostWalkWorker(node); }
// BinaryExpression
public override bool Walk(BinaryExpression node) { return ShouldWalkWorker(node); }
public override void PostWalk(BinaryExpression node) { PostWalkWorker(node); }
// CallExpression
public override bool Walk(CallExpression node) { return ShouldWalkWorker(node); }
public override void PostWalk(CallExpression node) { PostWalkWorker(node); }
// ConditionalExpression
public override bool Walk(ConditionalExpression node) { return ShouldWalkWorker(node); }
public override void PostWalk(ConditionalExpression node) { PostWalkWorker(node); }
// ConstantExpression
public override bool Walk(ConstantExpression node) { return ShouldWalkWorker(node); }
public override void PostWalk(ConstantExpression node) { PostWalkWorker(node); }
// DictionaryComprehension
public override bool Walk(DictionaryComprehension node) { return ShouldWalkWorker(node); }
public override void PostWalk(DictionaryComprehension node) { PostWalkWorker(node); }
// DictionaryExpression
public override bool Walk(DictionaryExpression node) { return ShouldWalkWorker(node); }
public override void PostWalk(DictionaryExpression node) { PostWalkWorker(node); }
// ErrorExpression
public override bool Walk(ErrorExpression node) { return ShouldWalkWorker(node); }
public override void PostWalk(ErrorExpression node) { PostWalkWorker(node); }
// GeneratorExpression
public override bool Walk(GeneratorExpression node) { return ShouldWalkWorker(node); }
public override void PostWalk(GeneratorExpression node) { PostWalkWorker(node); }
// IndexExpression
public override bool Walk(IndexExpression node) { return ShouldWalkWorker(node); }
public override void PostWalk(IndexExpression node) { PostWalkWorker(node); }
// LambdaExpression
public override bool Walk(LambdaExpression node) { return ShouldWalkWorker(node); }
public override void PostWalk(LambdaExpression node) { PostWalkWorker(node); }
// ListComprehension
public override bool Walk(ListComprehension node) { return ShouldWalkWorker(node); }
public override void PostWalk(ListComprehension node) { PostWalkWorker(node); }
// ListExpression
public override bool Walk(ListExpression node) { return ShouldWalkWorker(node); }
public override void PostWalk(ListExpression node) { PostWalkWorker(node); }
// MemberExpression
public override bool Walk(MemberExpression node) { return ShouldWalkWorker(node); }
public override void PostWalk(MemberExpression node) { PostWalkWorker(node); }
// NameExpression
public override bool Walk(NameExpression node) { return ShouldWalkWorker(node); }
public override void PostWalk(NameExpression node) { PostWalkWorker(node); }
// OrExpression
public override bool Walk(OrExpression node) { return ShouldWalkWorker(node); }
public override void PostWalk(OrExpression node) { PostWalkWorker(node); }
// ParenthesisExpression
public override bool Walk(ParenthesisExpression node) { return ShouldWalkWorker(node); }
public override void PostWalk(ParenthesisExpression node) { PostWalkWorker(node); }
// SetComprehension
public override bool Walk(SetComprehension node) { return ShouldWalkWorker(node); }
public override void PostWalk(SetComprehension node) { PostWalkWorker(node); }
// SetExpression
public override bool Walk(SetExpression node) { return ShouldWalkWorker(node); }
public override void PostWalk(SetExpression node) { PostWalkWorker(node); }
// SliceExpression
public override bool Walk(SliceExpression node) { return ShouldWalkWorker(node); }
public override void PostWalk(SliceExpression node) { PostWalkWorker(node); }
// TupleExpression
public override bool Walk(TupleExpression node) { return ShouldWalkWorker(node); }
public override void PostWalk(TupleExpression node) { PostWalkWorker(node); }
// UnaryExpression
public override bool Walk(UnaryExpression node) { return ShouldWalkWorker(node); }
public override void PostWalk(UnaryExpression node) { PostWalkWorker(node); }
// YieldExpression
public override bool Walk(YieldExpression node) { return ShouldWalkWorker(node); }
public override void PostWalk(YieldExpression node) { PostWalkWorker(node); }
// YieldFromExpression
public override bool Walk(YieldFromExpression node) { return ShouldWalkWorker(node); }
public override void PostWalk(YieldFromExpression node) { PostWalkWorker(node); }
// StarredExpression
public override bool Walk(StarredExpression node) { return ShouldWalkWorker(node); }
public override void PostWalk(StarredExpression node) { PostWalkWorker(node); }
// AssertStatement
public override bool Walk(AssertStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(AssertStatement node) { PostWalkWorker(node); }
// AssignmentStatement
public override bool Walk(AssignmentStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(AssignmentStatement node) { PostWalkWorker(node); }
// AugmentedAssignStatement
public override bool Walk(AugmentedAssignStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(AugmentedAssignStatement node) { PostWalkWorker(node); }
// BreakStatement
public override bool Walk(BreakStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(BreakStatement node) { PostWalkWorker(node); }
// ClassDefinition
public override bool Walk(ClassDefinition node) { return ShouldWalkWorker(node); }
public override void PostWalk(ClassDefinition node) { PostWalkWorker(node); }
// ContinueStatement
public override bool Walk(ContinueStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(ContinueStatement node) { PostWalkWorker(node); }
// DelStatement
public override bool Walk(DelStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(DelStatement node) { PostWalkWorker(node); }
// EmptyStatement
public override bool Walk(EmptyStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(EmptyStatement node) { PostWalkWorker(node); }
// ExecStatement
public override bool Walk(ExecStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(ExecStatement node) { PostWalkWorker(node); }
// ExpressionStatement
public override bool Walk(ExpressionStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(ExpressionStatement node) { PostWalkWorker(node); }
// ForStatement
public override bool Walk(ForStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(ForStatement node) { PostWalkWorker(node); }
// FromImportStatement
public override bool Walk(FromImportStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(FromImportStatement node) { PostWalkWorker(node); }
// FunctionDefinition
public override bool Walk(FunctionDefinition node) { return ShouldWalkWorker(node); }
public override void PostWalk(FunctionDefinition node) { PostWalkWorker(node); }
// GlobalStatement
public override bool Walk(GlobalStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(GlobalStatement node) { PostWalkWorker(node); }
// NonlocalStatement
public override bool Walk(NonlocalStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(NonlocalStatement node) { PostWalkWorker(node); }
// IfStatement
public override bool Walk(IfStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(IfStatement node) { PostWalkWorker(node); }
// ImportStatement
public override bool Walk(ImportStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(ImportStatement node) { PostWalkWorker(node); }
// PrintStatement
public override bool Walk(PrintStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(PrintStatement node) { PostWalkWorker(node); }
// PythonAst
public override bool Walk(PythonAst node) { return ShouldWalkWorker(node); }
public override void PostWalk(PythonAst node) { PostWalkWorker(node); }
// RaiseStatement
public override bool Walk(RaiseStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(RaiseStatement node) { PostWalkWorker(node); }
// ReturnStatement
public override bool Walk(ReturnStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(ReturnStatement node) { PostWalkWorker(node); }
// SuiteStatement
public override bool Walk(SuiteStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(SuiteStatement node) { PostWalkWorker(node); }
// TryStatement
public override bool Walk(TryStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(TryStatement node) { PostWalkWorker(node); }
// WhileStatement
public override bool Walk(WhileStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(WhileStatement node) { PostWalkWorker(node); }
// WithStatement
public override bool Walk(WithStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(WithStatement node) { PostWalkWorker(node); }
// Arg
public override bool Walk(Arg node) { return ShouldWalkWorker(node); }
public override void PostWalk(Arg node) { PostWalkWorker(node); }
// ComprehensionFor
public override bool Walk(ComprehensionFor node) { return ShouldWalkWorker(node); }
public override void PostWalk(ComprehensionFor node) { PostWalkWorker(node); }
// ComprehensionIf
public override bool Walk(ComprehensionIf node) { return ShouldWalkWorker(node); }
public override void PostWalk(ComprehensionIf node) { PostWalkWorker(node); }
// DottedName
public override bool Walk(DottedName node) { return ShouldWalkWorker(node); }
public override void PostWalk(DottedName node) { PostWalkWorker(node); }
// IfStatementTest
public override bool Walk(IfStatementTest node) { return ShouldWalkWorker(node); }
public override void PostWalk(IfStatementTest node) { PostWalkWorker(node); }
// ModuleName
public override bool Walk(ModuleName node) { return ShouldWalkWorker(node); }
public override void PostWalk(ModuleName node) { PostWalkWorker(node); }
// Parameter
public override bool Walk(Parameter node) { return ShouldWalkWorker(node); }
public override void PostWalk(Parameter node) { PostWalkWorker(node); }
// RelativeModuleName
public override bool Walk(RelativeModuleName node) { return ShouldWalkWorker(node); }
public override void PostWalk(RelativeModuleName node) { PostWalkWorker(node); }
// SublistParameter
public override bool Walk(SublistParameter node) { return ShouldWalkWorker(node); }
public override void PostWalk(SublistParameter node) { PostWalkWorker(node); }
// TryStatementHandler
public override bool Walk(TryStatementHandler node) { return ShouldWalkWorker(node); }
public override void PostWalk(TryStatementHandler node) { PostWalkWorker(node); }
// ErrorStatement
public override bool Walk(ErrorStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(ErrorStatement node) { PostWalkWorker(node); }
// DecoratorStatement
public override bool Walk(DecoratorStatement node) { return ShouldWalkWorker(node); }
public override void PostWalk(DecoratorStatement node) { PostWalkWorker(node); }
#endregion
}
}
| |
using ReactiveUI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Reactive.Subjects;
namespace F2F.ReactiveNavigation.ViewModel
{
public abstract class ReactiveItemsViewModel<TCollectionItem> : ReactiveValidatedViewModel
where TCollectionItem : class, INotifyPropertyChanged
{
private ReactiveCommand<Unit, Unit> _addItem;
private ReactiveCommand<TCollectionItem, Unit> _removeItem;
private ReactiveCommand<object, Unit> _clearItems;
private ReactiveList<TCollectionItem> _items = new ReactiveList<TCollectionItem>();
private TCollectionItem _selectedItem;
protected ReactiveItemsViewModel()
{
}
protected internal override async Task Initialize()
{
await base.Initialize();
var canAddItems =
CanAddItemObservables()
.Select(o => o.StartWith(false))
.CombineLatest()
.Select(bs => bs.All(b => b))
.Catch<bool, Exception>(ex =>
{
ThrownExceptionsSource.OnNext(ex);
return Observable.Return(false);
});
this.AddItem = ReactiveCommand.CreateFromTask(_ => AddNewItem(), canAddItems, RxApp.MainThreadScheduler);
var isItemSelected =
this.RemoveRequiresSelectedItem
? this.WhenNotNull(x => x.SelectedItem)
: new BehaviorSubject<bool>(true);
var canRemoveItems =
CanRemoveItemObservables()
.Select(o => o.StartWith(false))
.Concat(new[] { isItemSelected })
.CombineLatest()
.Select(bs => bs.All(b => b))
.Catch<bool, Exception>(ex =>
{
ThrownExceptionsSource.OnNext(ex);
return Observable.Return(false);
});
this.RemoveItem = this.CreateAsyncObservableCommand<TCollectionItem>(canRemoveItems, x => { Remove(x); }, RxApp.MainThreadScheduler);
var canClearItems =
CanClearItemsObservables()
.Select(o => o.StartWith(false))
.CombineLatest()
.Select(bs => bs.All(b => b))
.Catch<bool, Exception>(ex =>
{
ThrownExceptionsSource.OnNext(ex);
return Observable.Return(false);
});
this.ClearItems = this.CreateAsyncObservableCommand(canClearItems, _ => Items.Clear(), RxApp.MainThreadScheduler);
}
protected virtual bool RemoveRequiresSelectedItem
{
get { return true; }
}
public ReactiveCommand<Unit, Unit> AddItem
{
get { return _addItem; }
protected set { this.RaiseAndSetIfChanged(ref _addItem, value); }
}
public ReactiveCommand<TCollectionItem, Unit> RemoveItem
{
get { return _removeItem; }
protected set { this.RaiseAndSetIfChanged(ref _removeItem, value); }
}
public ReactiveCommand<object, Unit> ClearItems
{
get { return _clearItems; }
protected set { this.RaiseAndSetIfChanged(ref _clearItems, value); }
}
public TCollectionItem SelectedItem
{
get { return _selectedItem; }
set { this.RaiseAndSetIfChanged(ref _selectedItem, value); }
}
public ReactiveList<TCollectionItem> Items
{
get { return _items; }
protected set { this.RaiseAndSetIfChanged(ref _items, value); }
}
internal protected virtual IEnumerable<IObservable<bool>> CanAddItemObservables()
{
yield return Observable.Return(true);
}
internal protected virtual IEnumerable<IObservable<bool>> CanRemoveItemObservables()
{
yield return Observable.Return(true);
}
internal protected virtual IEnumerable<IObservable<bool>> CanClearItemsObservables()
{
yield return Observable.Return(true);
}
private async Task AddNewItem()
{
var currentItem = SelectedItem;
var newItem = await CreateItem();
Action<TCollectionItem> addItem = item =>
{
if (currentItem != null)
{
// insert new item directly after currentItem
var newItemIndex = 1 + _items.IndexOf(currentItem);
Items.Insert(newItemIndex, newItem);
}
else
{
Items.Add(newItem);
}
SelectedItem = newItem;
};
ConfirmAddOf(newItem, addItem);
}
private void Remove(TCollectionItem itemToRemove)
{
if (itemToRemove == null)
throw new ArgumentNullException("itemToRemove", "itemToRemove is null.");
Action<TCollectionItem> removeItem = item =>
{
var removedItemIndex = this.Items.IndexOf(item);
Items.Remove(item);
if (Items.Count > 0)
{
var newSelectedIndex = Math.Max(0, Math.Min(Items.Count - 1, removedItemIndex));
SelectedItem = _items[newSelectedIndex];
}
};
ConfirmRemoveOf(itemToRemove, removeItem);
}
/// <summary>
/// Creates a new item of type <typeparamref name="TCollectionItem"/>
/// </summary>
/// <returns></returns>
internal protected abstract Task<TCollectionItem> CreateItem();
// TODO: Make this more Rxy
/// <summary>
/// Confirms the removal of the given <paramref name="itemToRemove"/>.
/// </summary>
/// <param name="itemToRemove">The item to delete</param>
/// <param name="removeAction">The action to call, when the removal shall be executed</param>
protected virtual void ConfirmRemoveOf(TCollectionItem itemToRemove, Action<TCollectionItem> removeAction)
{
if (itemToRemove == null)
throw new ArgumentNullException("itemToRemove", "itemToRemove is null.");
if (removeAction == null)
throw new ArgumentNullException("removeAction", "removeAction is null.");
removeAction(itemToRemove);
}
// TODO: Make this more Rxy
/// <summary>
/// Confirms the adding of the given <paramref name="itemToAdd"/>.
/// </summary>
/// <param name="itemToAdd">The item to add</param>
/// <param name="addAction">The action to call, when the add shall be executed</param>
protected virtual void ConfirmAddOf(TCollectionItem itemToAdd, Action<TCollectionItem> addAction)
{
if (itemToAdd == null)
throw new ArgumentNullException("itemToAdd", "itemToAdd is null.");
if (addAction == null)
throw new ArgumentNullException("addAction", "addAction is null.");
addAction(itemToAdd);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
using Microsoft.Build.BuildEngine.Shared;
using Microsoft.Build.Framework;
namespace Microsoft.Build.BuildEngine
{
/// <summary>
/// This exception is used to wrap an unhandled exception from a logger. This exception aborts the build, and it can only be
/// thrown by the MSBuild engine.
/// </summary>
/// <owner>SumedhK</owner>
// WARNING: marking a type [Serializable] without implementing ISerializable imposes a serialization contract -- it is a
// promise to never change the type's fields i.e. the type is immutable; adding new fields in the next version of the type
// without following certain special FX guidelines, can break both forward and backward compatibility
[Serializable]
public sealed class InternalLoggerException : Exception
{
#region Unusable constructors
/// <summary>
/// Default constructor.
/// </summary>
/// <remarks>
/// This constructor only exists to satisfy .NET coding guidelines. Use the rich constructor instead.
/// </remarks>
/// <owner>SumedhK</owner>
/// <exception cref="InvalidOperationException"></exception>
public InternalLoggerException()
{
ErrorUtilities.VerifyThrowInvalidOperation(false, "InternalLoggerExceptionOnlyThrownByEngine");
}
/// <summary>
/// Creates an instance of this exception using the specified error message.
/// </summary>
/// <remarks>
/// This constructor only exists to satisfy .NET coding guidelines. Use the rich constructor instead.
/// </remarks>
/// <owner>SumedhK</owner>
/// <param name="message"></param>
/// <exception cref="InvalidOperationException"></exception>
public InternalLoggerException(string message)
: base(message)
{
ErrorUtilities.VerifyThrowInvalidOperation(false, "InternalLoggerExceptionOnlyThrownByEngine");
}
/// <summary>
/// Creates an instance of this exception using the specified error message and inner exception.
/// </summary>
/// <remarks>
/// This constructor only exists to satisfy .NET coding guidelines. Use the rich constructor instead.
/// </remarks>
/// <owner>SumedhK</owner>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <exception cref="InvalidOperationException"></exception>
public InternalLoggerException(string message, Exception innerException)
: base(message, innerException)
{
ErrorUtilities.VerifyThrowInvalidOperation(false, "InternalLoggerExceptionOnlyThrownByEngine");
}
#endregion
/// <summary>
/// Creates an instance of this exception using rich error information.
/// Internal for unit testing
/// </summary>
/// <remarks>This is the only usable constructor.</remarks>
/// <owner>SumedhK</owner>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="e">Can be null.</param>
/// <param name="errorCode"></param>
/// <param name="helpKeyword"></param>
internal InternalLoggerException
(
string message,
Exception innerException,
BuildEventArgs e,
string errorCode,
string helpKeyword,
bool initializationException
)
: base(message, innerException)
{
ErrorUtilities.VerifyThrow(!string.IsNullOrEmpty(message), "Need error message.");
ErrorUtilities.VerifyThrow(innerException != null || initializationException, "Need the logger exception.");
ErrorUtilities.VerifyThrow(!string.IsNullOrEmpty(errorCode), "Must specify the error message code.");
ErrorUtilities.VerifyThrow(!string.IsNullOrEmpty(helpKeyword), "Must specify the help keyword for the IDE.");
this.e = e;
this.errorCode = errorCode;
this.helpKeyword = helpKeyword;
this.initializationException = initializationException;
}
#region Serialization (update when adding new class members)
/// <summary>
/// Protected constructor used for (de)serialization.
/// If we ever add new members to this class, we'll need to update this.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
private InternalLoggerException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
this.e = (BuildEventArgs) info.GetValue("e", typeof(BuildEventArgs));
this.errorCode = info.GetString("errorCode");
this.helpKeyword = info.GetString("helpKeyword");
this.initializationException = info.GetBoolean("initializationException");
}
/// <summary>
/// ISerializable method which we must override since Exception implements this interface
/// If we ever add new members to this class, we'll need to update this.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
override public void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("e", e);
info.AddValue("errorCode", errorCode);
info.AddValue("helpKeyword", helpKeyword);
info.AddValue("initializationException", initializationException);
}
/// <summary>
/// Provide default values for optional members
/// </summary>
[OnDeserializing] // Will happen before the object is deserialized
private void SetDefaultsBeforeSerialization(StreamingContext sc)
{
initializationException = false;
}
/// <summary>
/// Dont actually have anything to do in the method, but the method is required when implementing an optional field
/// </summary>
[OnDeserialized]
private void SetValueAfterDeserialization(StreamingContext sx)
{
// Have nothing to do
}
#endregion
#region Properties
/// <summary>
/// Gets the details of the build event (if any) that was being logged.
/// </summary>
/// <owner>SumedhK</owner>
/// <value>The build event args, or null.</value>
public BuildEventArgs BuildEventArgs
{
get
{
return e;
}
}
/// <summary>
/// Gets the error code associated with this exception's message (not the inner exception).
/// </summary>
/// <owner>SumedhK</owner>
/// <value>The error code string.</value>
public string ErrorCode
{
get
{
return errorCode;
}
}
/// <summary>
/// Gets the F1-help keyword associated with this error, for the host IDE.
/// </summary>
/// <owner>SumedhK</owner>
/// <value>The keyword string.</value>
public string HelpKeyword
{
get
{
return helpKeyword;
}
}
/// <summary>
/// True if the exception occurred during logger initialization
/// </summary>
public bool InitializationException
{
get
{
return initializationException;
}
}
#endregion
/// <summary>
/// Throws an instance of this exception using rich error information.
/// </summary>
/// <param name="innerException"></param>
/// <param name="e">Can be null.</param>
/// <param name="messageResourceName"></param>
/// <param name="messageArgs"></param>
internal static void Throw
(
Exception innerException,
BuildEventArgs e,
string messageResourceName,
bool initializationException,
params string[] messageArgs
)
{
ErrorUtilities.VerifyThrow(messageResourceName != null, "Need error message.");
string errorCode;
string helpKeyword;
string message = ResourceUtilities.FormatResourceString(out errorCode, out helpKeyword, messageResourceName, messageArgs);
throw new InternalLoggerException(message, innerException, e, errorCode, helpKeyword, initializationException);
}
// the event that was being logged when a logger failed (can be null)
private BuildEventArgs e;
// the error code for this exception's message (not the inner exception)
private string errorCode;
// the F1-help keyword for the host IDE
private string helpKeyword;
// This flag is set to indicate that the exception occurred during logger initialization
[OptionalField(VersionAdded = 2)]
private bool initializationException;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections;
using System.Diagnostics;
namespace System.Xml
{
internal class XmlElementList : XmlNodeList
{
private string _asterisk;
private int _changeCount; //recording the total number that the dom tree has been changed ( insertion and deletion )
//the member vars below are saved for further reconstruction
private string _name; //only one of 2 string groups will be initialized depends on which constructor is called.
private string _localName;
private string _namespaceURI;
private XmlNode _rootNode;
// the member vars below serves the optimization of accessing of the elements in the list
private int _curInd; // -1 means the starting point for a new search round
private XmlNode _curElem; // if sets to rootNode, means the starting point for a new search round
private bool _empty; // whether the list is empty
private bool _atomized; //whether the localname and namespaceuri are atomized
private int _matchCount; // cached list count. -1 means it needs reconstruction
private WeakReference _listener; // XmlElementListListener
private XmlElementList(XmlNode parent)
{
Debug.Assert(parent != null);
Debug.Assert(parent.NodeType == XmlNodeType.Element || parent.NodeType == XmlNodeType.Document);
_rootNode = parent;
Debug.Assert(parent.Document != null);
_curInd = -1;
_curElem = _rootNode;
_changeCount = 0;
_empty = false;
_atomized = true;
_matchCount = -1;
// This can be a regular reference, but it would cause some kind of loop inside the GC
_listener = new WeakReference(new XmlElementListListener(parent.Document, this));
}
~XmlElementList()
{
Dispose(false);
}
internal void ConcurrencyCheck(XmlNodeChangedEventArgs args)
{
if (_atomized == false)
{
XmlNameTable nameTable = _rootNode.Document.NameTable;
_localName = nameTable.Add(_localName);
_namespaceURI = nameTable.Add(_namespaceURI);
_atomized = true;
}
if (IsMatch(args.Node))
{
_changeCount++;
_curInd = -1;
_curElem = _rootNode;
if (args.Action == XmlNodeChangedAction.Insert)
_empty = false;
}
_matchCount = -1;
}
internal XmlElementList(XmlNode parent, string name) : this(parent)
{
Debug.Assert(parent.Document != null);
XmlNameTable nt = parent.Document.NameTable;
Debug.Assert(nt != null);
_asterisk = nt.Add("*");
_name = nt.Add(name);
_localName = null;
_namespaceURI = null;
}
internal XmlElementList(XmlNode parent, string localName, string namespaceURI) : this(parent)
{
Debug.Assert(parent.Document != null);
XmlNameTable nt = parent.Document.NameTable;
Debug.Assert(nt != null);
_asterisk = nt.Add("*");
_localName = nt.Get(localName);
_namespaceURI = nt.Get(namespaceURI);
if ((_localName == null) || (_namespaceURI == null))
{
_empty = true;
_atomized = false;
_localName = localName;
_namespaceURI = namespaceURI;
}
_name = null;
}
internal int ChangeCount
{
get { return _changeCount; }
}
// return the next element node that is in PreOrder
private XmlNode NextElemInPreOrder(XmlNode curNode)
{
Debug.Assert(curNode != null);
//For preorder walking, first try its child
XmlNode retNode = curNode.FirstChild;
if (retNode == null)
{
//if no child, the next node forward will the be the NextSibling of the first ancestor which has NextSibling
//so, first while-loop find out such an ancestor (until no more ancestor or the ancestor is the rootNode
retNode = curNode;
while (retNode != null
&& retNode != _rootNode
&& retNode.NextSibling == null)
{
retNode = retNode.ParentNode;
}
//then if such ancestor exists, set the retNode to its NextSibling
if (retNode != null && retNode != _rootNode)
retNode = retNode.NextSibling;
}
if (retNode == _rootNode)
//if reach the rootNode, consider having walked through the whole tree and no more element after the curNode
retNode = null;
return retNode;
}
// return the previous element node that is in PreOrder
private XmlNode PrevElemInPreOrder(XmlNode curNode)
{
Debug.Assert(curNode != null);
//For preorder walking, the previous node will be the right-most node in the tree of PreviousSibling of the curNode
XmlNode retNode = curNode.PreviousSibling;
// so if the PreviousSibling is not null, going through the tree down to find the right-most node
while (retNode != null)
{
if (retNode.LastChild == null)
break;
retNode = retNode.LastChild;
}
// if no PreviousSibling, the previous node will be the curNode's parentNode
if (retNode == null)
retNode = curNode.ParentNode;
// if the final retNode is rootNode, consider having walked through the tree and no more previous node
if (retNode == _rootNode)
retNode = null;
return retNode;
}
// if the current node a matching element node
private bool IsMatch(XmlNode curNode)
{
if (curNode.NodeType == XmlNodeType.Element)
{
if (_name != null)
{
if (Ref.Equal(_name, _asterisk) || Ref.Equal(curNode.Name, _name))
return true;
}
else
{
if (
(Ref.Equal(_localName, _asterisk) || Ref.Equal(curNode.LocalName, _localName)) &&
(Ref.Equal(_namespaceURI, _asterisk) || curNode.NamespaceURI == _namespaceURI)
)
{
return true;
}
}
}
return false;
}
private XmlNode GetMatchingNode(XmlNode n, bool bNext)
{
Debug.Assert(n != null);
XmlNode node = n;
do
{
if (bNext)
node = NextElemInPreOrder(node);
else
node = PrevElemInPreOrder(node);
} while (node != null && !IsMatch(node));
return node;
}
private XmlNode GetNthMatchingNode(XmlNode n, bool bNext, int nCount)
{
Debug.Assert(n != null);
XmlNode node = n;
for (int ind = 0; ind < nCount; ind++)
{
node = GetMatchingNode(node, bNext);
if (node == null)
return null;
}
return node;
}
//the function is for the enumerator to find out the next available matching element node
public XmlNode GetNextNode(XmlNode n)
{
if (_empty == true)
return null;
XmlNode node = (n == null) ? _rootNode : n;
return GetMatchingNode(node, true);
}
public override XmlNode Item(int index)
{
if (_rootNode == null || index < 0)
return null;
if (_empty == true)
return null;
if (_curInd == index)
return _curElem;
int nDiff = index - _curInd;
bool bForward = (nDiff > 0);
if (nDiff < 0)
nDiff = -nDiff;
XmlNode node;
if ((node = GetNthMatchingNode(_curElem, bForward, nDiff)) != null)
{
_curInd = index;
_curElem = node;
return _curElem;
}
return null;
}
public override int Count
{
get
{
if (_empty == true)
return 0;
if (_matchCount < 0)
{
int currMatchCount = 0;
int currChangeCount = _changeCount;
XmlNode node = _rootNode;
while ((node = GetMatchingNode(node, true)) != null)
{
currMatchCount++;
}
if (currChangeCount != _changeCount)
{
return currMatchCount;
}
_matchCount = currMatchCount;
}
return _matchCount;
}
}
public override IEnumerator GetEnumerator()
{
if (_empty == true)
return new XmlEmptyElementListEnumerator(this); ;
return new XmlElementListEnumerator(this);
}
protected override void PrivateDisposeNodeList()
{
GC.SuppressFinalize(this);
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (_listener != null)
{
XmlElementListListener listener = (XmlElementListListener)_listener.Target;
if (listener != null)
{
listener.Unregister();
}
_listener = null;
}
}
}
internal class XmlElementListEnumerator : IEnumerator
{
private XmlElementList _list;
private XmlNode _curElem;
private int _changeCount; //save the total number that the dom tree has been changed ( insertion and deletion ) when this enumerator is created
public XmlElementListEnumerator(XmlElementList list)
{
_list = list;
_curElem = null;
_changeCount = list.ChangeCount;
}
public bool MoveNext()
{
if (_list.ChangeCount != _changeCount)
{
//the number mismatch, there is new change(s) happened since last MoveNext() is called.
throw new InvalidOperationException(SR.Xdom_Enum_ElementList);
}
else
{
_curElem = _list.GetNextNode(_curElem);
}
return _curElem != null;
}
public void Reset()
{
_curElem = null;
//reset the number of changes to be synced with current dom tree as well
_changeCount = _list.ChangeCount;
}
public object Current
{
get { return _curElem; }
}
}
internal class XmlEmptyElementListEnumerator : IEnumerator
{
public XmlEmptyElementListEnumerator(XmlElementList list)
{
}
public bool MoveNext()
{
return false;
}
public void Reset()
{
}
public object Current
{
get { return null; }
}
}
internal class XmlElementListListener
{
private WeakReference _elemList;
private XmlDocument _doc;
private XmlNodeChangedEventHandler _nodeChangeHandler = null;
internal XmlElementListListener(XmlDocument doc, XmlElementList elemList)
{
_doc = doc;
_elemList = new WeakReference(elemList);
_nodeChangeHandler = new XmlNodeChangedEventHandler(this.OnListChanged);
doc.NodeInserted += _nodeChangeHandler;
doc.NodeRemoved += _nodeChangeHandler;
}
private void OnListChanged(object sender, XmlNodeChangedEventArgs args)
{
lock (this)
{
if (_elemList != null)
{
XmlElementList el = (XmlElementList)_elemList.Target;
if (null != el)
{
el.ConcurrencyCheck(args);
}
else
{
_doc.NodeInserted -= _nodeChangeHandler;
_doc.NodeRemoved -= _nodeChangeHandler;
_elemList = null;
}
}
}
}
// This method is called from the finalizer of XmlElementList
internal void Unregister()
{
lock (this)
{
if (_elemList != null)
{
_doc.NodeInserted -= _nodeChangeHandler;
_doc.NodeRemoved -= _nodeChangeHandler;
_elemList = null;
}
}
}
}
}
| |
/*
* Container.cs - Implementation of the
* "System.ComponentModel.Container" 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 System.ComponentModel
{
#if CONFIG_COMPONENT_MODEL
using System;
public class Container : IContainer, IDisposable
{
// Internal state.
private ISite[] sites;
private int numSites;
// Constructor.
public Container() {}
// Destructor.
~Container()
{
Dispose(false);
}
// Get a collection of all components within this container.
// The collection is a copy, not live.
public virtual ComponentCollection Components
{
get
{
lock(this)
{
IComponent[] components;
int posn;
components = new IComponent [numSites];
for(posn = 0; posn < numSites; ++posn)
{
components[posn] = sites[posn].Component;
}
return new ComponentCollection(components);
}
}
}
// Add a component to this container.
public virtual void Add(IComponent component)
{
Add(component, null);
}
public virtual void Add(IComponent component, String name)
{
ISite site;
int posn;
// Nothing to do if component is null or already in the list.
if(component == null)
{
return;
}
site = component.Site;
if(site != null && site.Container == this)
{
return;
}
// Check for name duplicates and add the new component.
lock(this)
{
if(name != null)
{
for(posn = 0; posn < numSites; ++posn)
{
if(String.Compare
(sites[posn].Name, name, true) == 0)
{
throw new ArgumentException
(S._("Arg_DuplicateComponent"));
}
}
}
if(site != null)
{
site.Container.Remove(component);
}
if(sites == null)
{
sites = new ISite [4];
}
else if(numSites >= sites.Length)
{
ISite[] newList = new ISite [numSites * 2];
Array.Copy(sites, 0, newList, 0, numSites);
sites = newList;
}
site = CreateSite(component, name);
sites[numSites++] = site;
}
}
// Create a site for a component within this container.
protected virtual ISite CreateSite(IComponent component, String name)
{
return new ContainSite(this, component, name);
}
// Implement the IDisposable interface.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Dispose of this object.
protected virtual void Dispose(bool disposing)
{
if(disposing)
{
// Dispose all of the components in reverse order.
lock(this)
{
IComponent component;
while(numSites > 0)
{
--numSites;
component = sites[numSites].Component;
component.Site = null;
component.Dispose();
}
sites = null;
}
}
}
// Get a service from this object (the only service we support
// in the base class is "get container".
protected virtual Object GetService(Type service)
{
if(service == typeof(IContainer))
{
return this;
}
else
{
return null;
}
}
// Remove a component from this container.
public virtual void Remove(IComponent component)
{
// Bail out if the component is not in this container.
if(component == null)
{
return;
}
ISite site = component.Site;
if(site == null || site.Container != this)
{
return;
}
// Lock down the container and remove the component.
lock(this)
{
component.Site = null;
int posn = 0;
while(posn < numSites)
{
if(sites[posn] == site)
{
Array.Copy(sites, posn + 1, sites, posn,
numSites - (posn + 1));
sites[numSites - 1] = null;
--numSites;
break;
}
++posn;
}
}
}
// Site information for this type of container.
private sealed class ContainSite : ISite
{
// Internal state.
private Container container;
private IComponent component;
private String name;
// Constructor
public ContainSite(Container container, IComponent component,
String name)
{
this.container = container;
this.component = component;
this.name = name;
component.Site = this;
}
// Get the component associated with this site.
public IComponent Component
{
get
{
return component;
}
}
// Get the container associated with this site.
public IContainer Container
{
get
{
return container;
}
}
// Determine if the component is in design mode.
public bool DesignMode
{
get
{
return false;
}
}
// Get or set the name of the component.
public String Name
{
get
{
return name;
}
set
{
name = value;
}
}
// Get a service that is provided by this object.
public Object GetService(Type serviceType)
{
if(serviceType == typeof(ISite))
{
return this;
}
else
{
return container.GetService(serviceType);
}
}
}; // class ContainSite
}; // class Container
#endif // CONFIG_COMPONENT_MODEL
}; // namespace System.ComponentModel
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
partial class TcpClient
{
// The Unix implementation is separate from the Windows implementation due to a fundamental
// difference in socket support on the two platforms: on Unix once a socket has been used
// in a failed connect, its state is undefined and it can no longer be used (Windows supports
// this). This then means that the instance Socket.Connect methods that take either multiple
// addresses or a string host name that could be mapped to multiple addresses via DNS don't
// work, because we can't try to individually connect to a second address after failing the
// first. That then impacts TcpClient, which exposes not only such Connect methods that
// just delegate to the underlying Socket, but also the Socket itself.
//
// To address the most common cases, where the Socket isn't actually accessed directly by
// a consumer of TcpClient, whereas on Windows TcpClient creates the socket during construction,
// on Unix we create the socket on-demand, either when it's explicitly asked for via the Client
// property or when the TcpClient.Connect methods are called. In the former case, we have no
// choice but to create a Socket, after which point we'll throw PlatformNotSupportedException
// on any subsequent attempts to use Connect with multiple addresses. In the latter case, though,
// we can create a new Socket for each address we try, and only store as the "real" Client socket
// the one that successfully connected.
//
// However, TcpClient also exposes some properties for common configuration of the Socket, and
// if we simply forwarded those through Client, we'd frequently end up forcing the Socket's
// creation before Connect is used, thwarting this whole scheme. To address that, we maintain
// shadow values for the relevant state. When the properties are read, we read them initially
// from a temporary socket created just for the purpose of getting the system's default. When
// the properties are written, we store their values into these shadow properties instead of into
// an actual socket (though we do also create a temporary socket and store the property onto it,
// enabling errors to be caught earlier). This is a relatively expensive, but it enables
// TcpClient to be used in its recommended fashion and with its most popular APIs.
// Shadow values for storing data set through TcpClient's properties.
// We use a separate bool field to store whether the value has been set.
// We don't use nullables, due to one of the properties being a reference type.
private ShadowOptions _shadowOptions; // shadow state used in public properties before the socket is created
private int _connectRunning; // tracks whether a connect operation that could set _clientSocket is currently running
private void InitializeClientSocket()
{
// Nop. We want to lazily-allocate the socket.
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)] // TODO: Remove once https://github.com/dotnet/corefx/issues/5868 is addressed.
private Socket Client
{
get
{
EnterClientLock();
try
{
// The Client socket is being explicitly accessed, so we're forced
// to create it if it doesn't exist.
if (_clientSocket == null)
{
// Create the socket, and transfer to it any of our shadow properties.
_clientSocket = CreateSocket();
ApplyInitializedOptionsToSocket(_clientSocket);
}
return _clientSocket;
}
finally
{
ExitClientLock();
}
}
}
private void ApplyInitializedOptionsToSocket(Socket socket)
{
ShadowOptions so = _shadowOptions;
if (so == null)
{
return;
}
// For each shadow property where we have an initialized value,
// transfer that value to the provided socket.
if (so._exclusiveAddressUseInitialized)
{
socket.ExclusiveAddressUse = so._exclusiveAddressUse != 0;
}
if (so._receiveBufferSizeInitialized)
{
socket.ReceiveBufferSize = so._receiveBufferSize;
}
if (so._sendBufferSizeInitialized)
{
socket.SendBufferSize = so._sendBufferSize;
}
if (so._receiveTimeoutInitialized)
{
socket.ReceiveTimeout = so._receiveTimeout;
}
if (so._sendTimeoutInitialized)
{
socket.SendTimeout = so._sendTimeout;
}
if (so._lingerStateInitialized)
{
socket.LingerState = so._lingerState;
}
if (so._noDelayInitialized)
{
socket.NoDelay = so._noDelay != 0;
}
}
private int AvailableCore
{
get
{
// If we have a client socket, return its available value.
// Otherwise, there isn't data available, so return 0.
return _clientSocket != null ? _clientSocket.Available : 0;
}
}
private bool ConnectedCore
{
get
{
// If we have a client socket, return whether it's connected.
// Otherwise as we don't have a socket, by definition it's not.
return _clientSocket != null && _clientSocket.Connected;
}
}
private Task ConnectAsyncCore(string host, int port)
{
// Validate the args, similar to how Socket.Connect(string, int) would.
if (host == null)
{
throw new ArgumentNullException(nameof(host));
}
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException(nameof(port));
}
// If the client socket has already materialized, this API can't be used.
if (_clientSocket != null)
{
throw new PlatformNotSupportedException(SR.net_sockets_connect_multiaddress_notsupported);
}
// Do the real work.
EnterClientLock();
return ConnectAsyncCorePrivate(host, port);
}
private async Task ConnectAsyncCorePrivate(string host, int port)
{
try
{
// Since Socket.Connect(host, port) won't work, get the addresses manually,
// and then delegate to Connect(IPAddress[], int).
IPAddress[] addresses = await Dns.GetHostAddressesAsync(host).ConfigureAwait(false);
await ConnectAsyncCorePrivate(addresses, port).ConfigureAwait(false);
}
finally
{
ExitClientLock();
}
}
private Task ConnectAsyncCore(IPAddress[] addresses, int port)
{
// Validate the args, similar to how Socket.Connect(IPAddress[], int) would.
if (addresses == null)
{
throw new ArgumentNullException(nameof(addresses));
}
if (addresses.Length == 0)
{
throw new ArgumentException(SR.net_invalidAddressList, nameof(addresses));
}
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException(nameof(port));
}
// If the client socket has already materialized, this API can't be used.
// Similarly if another operation to set the socket is already in progress.
if (_clientSocket != null)
{
throw new PlatformNotSupportedException(SR.net_sockets_connect_multiaddress_notsupported);
}
// Do the real work.
EnterClientLock();
return ConnectAsyncCorePrivate(addresses, port);
}
private async Task ConnectAsyncCorePrivate(IPAddress[] addresses, int port)
{
try
{
// For each address, create a new socket (configured appropriately) and try to connect
// to the endpoint. If we're successful, set the newly connected socket as the client
// socket, and we're done. If we're unsuccessful, try the next address.
ExceptionDispatchInfo lastException = null;
foreach (IPAddress address in addresses)
{
Socket s = CreateSocket();
try
{
ApplyInitializedOptionsToSocket(s);
await s.ConnectAsync(address, port).ConfigureAwait(false);
_clientSocket = s;
_active = true;
return;
}
catch (Exception exc)
{
s.Dispose();
lastException = ExceptionDispatchInfo.Capture(exc);
}
}
// None of the addresses worked. Throw whatever exception we last captured, or a
// new one if something went terribly wrong.
if (lastException != null)
{
lastException.Throw();
}
throw new ArgumentException(SR.net_invalidAddressList, nameof(addresses));
}
finally
{
ExitClientLock();
}
}
private int ReceiveBufferSizeCore
{
get
{
ShadowOptions so = EnsureShadowValuesInitialized();
return GetOption(ref so._receiveBufferSize, ref so._receiveBufferSizeInitialized, SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer);
}
set
{
ShadowOptions so = EnsureShadowValuesInitialized();
SetOption(ref so._receiveBufferSize, ref so._receiveBufferSizeInitialized, SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value);
}
}
private int SendBufferSizeCore
{
get
{
ShadowOptions so = EnsureShadowValuesInitialized();
return GetOption(ref so._sendBufferSize, ref so._sendBufferSizeInitialized, SocketOptionLevel.Socket, SocketOptionName.SendBuffer);
}
set
{
ShadowOptions so = EnsureShadowValuesInitialized();
SetOption(ref so._sendBufferSize, ref so._sendBufferSizeInitialized, SocketOptionLevel.Socket, SocketOptionName.SendBuffer, value);
}
}
private int ReceiveTimeoutCore
{
get
{
ShadowOptions so = EnsureShadowValuesInitialized();
return GetOption(ref so._receiveTimeout, ref so._receiveTimeoutInitialized, SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
}
set
{
ShadowOptions so = EnsureShadowValuesInitialized();
SetOption(ref so._receiveTimeout, ref so._receiveTimeoutInitialized, SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, value);
}
}
private int SendTimeoutCore
{
get
{
ShadowOptions so = EnsureShadowValuesInitialized();
return GetOption(ref so._sendTimeout, ref so._sendTimeoutInitialized, SocketOptionLevel.Socket, SocketOptionName.SendTimeout);
}
set
{
ShadowOptions so = EnsureShadowValuesInitialized();
SetOption(ref so._sendTimeout, ref so._sendTimeoutInitialized, SocketOptionLevel.Socket, SocketOptionName.SendTimeout, value);
}
}
private LingerOption LingerStateCore
{
get
{
ShadowOptions so = EnsureShadowValuesInitialized();
return GetOption(ref so._lingerState, ref so._lingerStateInitialized, SocketOptionLevel.Socket, SocketOptionName.Linger);
}
set
{
ShadowOptions so = EnsureShadowValuesInitialized();
SetOption(ref so._lingerState, ref so._lingerStateInitialized, SocketOptionLevel.Socket, SocketOptionName.Linger, value);
}
}
private bool NoDelayCore
{
get
{
ShadowOptions so = EnsureShadowValuesInitialized();
return GetOption(ref so._noDelay, ref so._noDelayInitialized, SocketOptionLevel.Tcp, SocketOptionName.NoDelay) != 0;
}
set
{
ShadowOptions so = EnsureShadowValuesInitialized();
SetOption(ref so._noDelay, ref so._noDelayInitialized, SocketOptionLevel.Tcp, SocketOptionName.NoDelay, value ? 1 : 0);
}
}
private bool ExclusiveAddressUseCore
{
get
{
ShadowOptions so = EnsureShadowValuesInitialized();
return GetOption(ref so._exclusiveAddressUse, ref so._exclusiveAddressUseInitialized, SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse) != 0;
}
set
{
// Unlike the rest of the properties, we code this one explicitly, so as to take advantage of validation done by Socket's property.
ShadowOptions so = EnsureShadowValuesInitialized();
so._exclusiveAddressUse = value ? 1 : 0;
so._exclusiveAddressUseInitialized = true;
if (_clientSocket != null)
{
_clientSocket.ExclusiveAddressUse = value; // Use setter explicitly as it does additional validation beyond that done by SetOption
}
}
}
private ShadowOptions EnsureShadowValuesInitialized()
{
return _shadowOptions ?? (_shadowOptions = new ShadowOptions());
}
private T GetOption<T>(ref T location, ref bool initialized, SocketOptionLevel level, SocketOptionName name)
{
// Used in the getter for each shadow property.
// If we already have our client socket set up, just get its value for the option.
// Otherwise, return our shadow property. If that shadow hasn't yet been initialized,
// first initialize it by creating a temporary socket from which we can obtain a default value.
if (_clientSocket != null)
{
return (T)_clientSocket.GetSocketOption(level, name);
}
if (!initialized)
{
using (Socket s = CreateSocket())
{
location = (T)s.GetSocketOption(level, name);
}
initialized = true;
}
return location;
}
private void SetOption<T>(ref T location, ref bool initialized, SocketOptionLevel level, SocketOptionName name, T value)
{
// Used in the setter for each shadow property.
// Store the option on to the client socket. If the client socket isn't yet set, we still want to set
// the property onto a socket so we can get validation performed by the underlying system on the option being
// set... so, albeit being a bit expensive, we create a temporary socket we can use for validation purposes.
Socket s = _clientSocket ?? CreateSocket();
try
{
if (typeof(T) == typeof(int))
{
s.SetSocketOption(level, name, (int)(object)value);
}
else
{
Debug.Assert(typeof(T) == typeof(LingerOption), $"Unexpected type: {typeof(T)}");
s.SetSocketOption(level, name, value);
}
}
finally
{
if (s != _clientSocket)
{
s.Dispose();
}
}
// Then if it was successful, store it into the shadow.
location = value;
initialized = true;
}
private void EnterClientLock()
{
// TcpClient is not safe to be used concurrently. But in case someone does access various members
// while an async Connect operation is running that could asynchronously transition _clientSocket
// from null to non-null, we have a simple lock... if it's taken when you try to take it, it throws
// a PlatformNotSupportedException indicating the limitations of Connect.
if (Interlocked.CompareExchange(ref _connectRunning, 1, 0) != 0)
{
throw new PlatformNotSupportedException(SR.net_sockets_connect_multiaddress_notsupported);
}
}
private void ExitClientLock()
{
Volatile.Write(ref _connectRunning, 0);
}
private sealed class ShadowOptions
{
internal int _exclusiveAddressUse;
internal bool _exclusiveAddressUseInitialized;
internal int _receiveBufferSize;
internal bool _receiveBufferSizeInitialized;
internal int _sendBufferSize;
internal bool _sendBufferSizeInitialized;
internal int _receiveTimeout;
internal bool _receiveTimeoutInitialized;
internal int _sendTimeout;
internal bool _sendTimeoutInitialized;
internal LingerOption _lingerState;
internal bool _lingerStateInitialized;
internal int _noDelay;
internal bool _noDelayInitialized;
}
}
}
| |
// <copyright file=Matrix3D.cs
// <copyright>
// Copyright (c) 2016, University of Stuttgart
// 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.
// </copyright>
// <license>MIT License</license>
// <main contributors>
// Markus Funk, Thomas Kosch, Sven Mayer
// </main contributors>
// <co-contributors>
// Paul Brombosch, Mai El-Komy, Juana Heusler,
// Matthias Hoppe, Robert Konrad, Alexander Martin
// </co-contributors>
// <patent information>
// We are aware that this software implements patterns and ideas,
// which might be protected by patents in your country.
// Example patents in Germany are:
// Patent reference number: DE 103 20 557.8
// Patent reference number: DE 10 2013 220 107.9
// Please make sure when using this software not to violate any existing patents in your country.
// </patent information>
// <date> 11/2/2016 12:25:57 PM</date>
#region Sharp3D.Math, Copyright(C) 2003-2004 Eran Kampf, Licensed under LGPL.
// Sharp3D.Math math library
// Copyright (C) 2003-2004
// Eran Kampf
// [email protected]
// http://www.ekampf.com/Sharp3D.Math/
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#endregion
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Text;
using System.Runtime.InteropServices;
namespace HciLab.Utilities.Mathematics.Core
{
/// <summary>
/// Represents a 3-dimentional double-precision floating point matrix.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[TypeConverter(typeof(ExpandableObjectConverter))]
public class Matrix3D : ISerializable, ICloneable
{
#region Private Fields
private double _m11 = 0.0, _m12 = 0.0, _m13 = 0.0;
private double _m21 = 0.0, _m22 = 0.0, _m23 = 0.0;
private double _m31 = 0.0, _m32 = 0.0, _m33 = 0.0;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Matrix3D"/> structure with out values.
/// </summary>
public Matrix3D ()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Matrix3D"/> structure with the specified values.
/// </summary>
public Matrix3D(
double m11, double m12, double m13,
double m21, double m22, double m23,
double m31, double m32, double m33
)
{
_m11 = m11; _m12 = m12; _m13 = m13;
_m21 = m21; _m22 = m22; _m23 = m23;
_m31 = m31; _m32 = m32; _m33 = m33;
}
/// <summary>
/// Initializes a new instance of the <see cref="Matrix3D"/> structure with the specified values.
/// </summary>
/// <param name="elements">An array containing the matrix values in row-major order.</param>
public Matrix3D(double[] elements)
{
Debug.Assert(elements != null);
Debug.Assert(elements.Length >= 9);
_m11 = elements[0]; _m12 = elements[1]; _m13 = elements[2];
_m21 = elements[3]; _m22 = elements[4]; _m23 = elements[5];
_m31 = elements[6]; _m32 = elements[7]; _m33 = elements[8];
}
/// <summary>
/// Initializes a new instance of the <see cref="Matrix3F"/> structure with the specified values.
/// </summary>
/// <param name="elements">An array containing the matrix values in row-major order.</param>
public Matrix3D(DoubleArrayList elements)
{
Debug.Assert(elements != null);
Debug.Assert(elements.Count >= 9);
_m11 = elements[0]; _m12 = elements[1]; _m13 = elements[2];
_m21 = elements[3]; _m22 = elements[4]; _m23 = elements[5];
_m31 = elements[6]; _m32 = elements[7]; _m33 = elements[8];
}
/// <summary>
/// Initializes a new instance of the <see cref="Matrix3D"/> structure with the specified values.
/// </summary>
/// <param name="column1">A <see cref="Vector2"/> instance holding values for the first column.</param>
/// <param name="column2">A <see cref="Vector2"/> instance holding values for the second column.</param>
/// <param name="column3">A <see cref="Vector2"/> instance holding values for the third column.</param>
public Matrix3D(Vector3 column1, Vector3 column2, Vector3 column3)
{
_m11 = column1.X; _m12 = column2.X; _m13 = column3.X;
_m21 = column1.Y; _m22 = column2.Y; _m23 = column3.Y;
_m31 = column1.Z; _m32 = column2.Z; _m33 = column3.Z;
}
/// <summary>
/// Initializes a new instance of the <see cref="Matrix3D"/> class using a given matrix.
/// </summary>
public Matrix3D(Matrix3D m)
{
_m11 = m.M11; _m12 = m.M12; _m13 = m.M13;
_m21 = m.M21; _m22 = m.M22; _m23 = m.M23;
_m31 = m.M31; _m32 = m.M32; _m33 = m.M33;
}
/// <summary>
/// Initializes a new instance of the <see cref="Matrix3D"/> class with serialized data.
/// </summary>
/// <param name="info">The object that holds the serialized object data.</param>
/// <param name="context">The contextual information about the source or destination.</param>
private Matrix3D(SerializationInfo info, StreamingContext context)
{
// Get the first row
_m11 = info.GetSingle("M11");
_m12 = info.GetSingle("M12");
_m13 = info.GetSingle("M13");
// Get the second row
_m21 = info.GetSingle("M21");
_m22 = info.GetSingle("M22");
_m23 = info.GetSingle("M23");
// Get the third row
_m31 = info.GetSingle("M31");
_m32 = info.GetSingle("M32");
_m33 = info.GetSingle("M33");
}
#endregion
#region Constants
/// <summary>
/// 3-dimentional double-precision floating point zero matrix.
/// </summary>
public static readonly Matrix3D Zero = new Matrix3D(0,0,0,0,0,0,0,0,0);
/// <summary>
/// 3-dimentional double-precision floating point identity matrix.
/// </summary>
public static readonly Matrix3D Identity = new Matrix3D(
1,0,0,
0,1,0,
0,0,1
);
#endregion
#region ICloneable Members
/// <summary>
/// Creates an exact copy of this <see cref="Matrix3D"/> object.
/// </summary>
/// <returns>The <see cref="Matrix3D"/> object this method creates, cast as an object.</returns>
object ICloneable.Clone()
{
return new Matrix3D(this);
}
/// <summary>
/// Creates an exact copy of this <see cref="Matrix3D"/> object.
/// </summary>
/// <returns>The <see cref="Matrix3D"/> object this method creates.</returns>
public Matrix3D Clone()
{
return new Matrix3D(this);
}
#endregion
#region ISerializable Members
/// <summary>
/// Populates a <see cref="SerializationInfo"/> with the data needed to serialize this object.
/// </summary>
/// <param name="info">The <see cref="SerializationInfo"/> to populate with data. </param>
/// <param name="context">The destination (see <see cref="StreamingContext"/>) for this serialization.</param>
//[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter=true)]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// First row
info.AddValue("M11", _m11);
info.AddValue("M12", _m12);
info.AddValue("M13", _m13);
// Second row
info.AddValue("M21", _m21);
info.AddValue("M22", _m22);
info.AddValue("M23", _m23);
// Third row
info.AddValue("M31", _m31);
info.AddValue("M32", _m32);
info.AddValue("M33", _m33);
}
#endregion
#region Public Static Matrix Arithmetics
/// <summary>
/// Adds two matrices.
/// </summary>
/// <param name="a">A <see cref="Matrix3D"/> instance.</param>
/// <param name="b">A <see cref="Matrix3D"/> instance.</param>
/// <returns>A new <see cref="Matrix3D"/> instance containing the sum.</returns>
public static Matrix3D Add(Matrix3D a, Matrix3D b)
{
return new Matrix3D(
a.M11 + b.M11, a.M12 + b.M12, a.M13 + b.M13,
a.M21 + b.M21, a.M22 + b.M22, a.M23 + b.M23,
a.M31 + b.M31, a.M32 + b.M32, a.M33 + b.M33
);
}
/// <summary>
/// Adds a matrix and a scalar.
/// </summary>
/// <param name="a">A <see cref="Matrix3D"/> instance.</param>
/// <param name="s">A scalar.</param>
/// <returns>A new <see cref="Matrix3D"/> instance containing the sum.</returns>
public static Matrix3D Add(Matrix3D a, double s)
{
return new Matrix3D(
a.M11 + s, a.M12 + s, a.M13 + s,
a.M21 + s, a.M22 + s, a.M23 + s,
a.M31 + s, a.M32 + s, a.M33 + s
);
}
/// <summary>
/// Adds two matrices and put the result in a third matrix.
/// </summary>
/// <param name="a">A <see cref="Matrix3D"/> instance.</param>
/// <param name="b">A <see cref="Matrix3D"/> instance.</param>
/// <param name="result">A <see cref="Matrix3D"/> instance to hold the result.</param>
public static void Add(Matrix3D a, Matrix3D b, ref Matrix3D result)
{
result.M11 = a.M11 + b.M11;
result.M12 = a.M12 + b.M12;
result.M13 = a.M13 + b.M13;
result.M21 = a.M21 + b.M21;
result.M22 = a.M22 + b.M22;
result.M23 = a.M23 + b.M23;
result.M31 = a.M31 + b.M31;
result.M32 = a.M32 + b.M32;
result.M33 = a.M33 + b.M33;
}
/// <summary>
/// Adds a matrix and a scalar and put the result in a third matrix.
/// </summary>
/// <param name="a">A <see cref="Matrix3D"/> instance.</param>
/// <param name="s">A scalar.</param>
/// <param name="result">A <see cref="Matrix3D"/> instance to hold the result.</param>
public static void Add(Matrix3D a, double s, ref Matrix3D result)
{
result.M11 = a.M11 + s;
result.M12 = a.M12 + s;
result.M13 = a.M13 + s;
result.M21 = a.M21 + s;
result.M22 = a.M22 + s;
result.M23 = a.M23 + s;
result.M31 = a.M31 + s;
result.M32 = a.M32 + s;
result.M33 = a.M33 + s;
}
/// <summary>
/// Subtracts a matrix from a matrix.
/// </summary>
/// <param name="a">A <see cref="Matrix3D"/> instance to subtract from.</param>
/// <param name="b">A <see cref="Matrix3D"/> instance to subtract.</param>
/// <returns>A new <see cref="Matrix3D"/> instance containing the difference.</returns>
/// <remarks>result[x][y] = a[x][y] - b[x][y]</remarks>
public static Matrix3D Subtract(Matrix3D a, Matrix3D b)
{
return new Matrix3D(
a.M11 - b.M11, a.M12 - b.M12, a.M13 - b.M13,
a.M21 - b.M21, a.M22 - b.M22, a.M23 - b.M23,
a.M31 - b.M31, a.M32 - b.M32, a.M33 - b.M33
);
}
/// <summary>
/// Subtracts a scalar from a matrix.
/// </summary>
/// <param name="a">A <see cref="Matrix3D"/> instance.</param>
/// <param name="s">A scalar.</param>
/// <returns>A new <see cref="Matrix3D"/> instance containing the difference.</returns>
public static Matrix3D Subtract(Matrix3D a, double s)
{
return new Matrix3D(
a.M11 - s, a.M12 - s, a.M13 - s,
a.M21 - s, a.M22 - s, a.M23 - s,
a.M31 - s, a.M32 - s, a.M33 - s
);
}
/// <summary>
/// Subtracts a matrix from a matrix and put the result in a third matrix.
/// </summary>
/// <param name="a">A <see cref="Matrix3D"/> instance to subtract from.</param>
/// <param name="b">A <see cref="Matrix3D"/> instance to subtract.</param>
/// <param name="result">A <see cref="Matrix3D"/> instance to hold the result.</param>
/// <remarks>result[x][y] = a[x][y] - b[x][y]</remarks>
public static void Subtract(Matrix3D a, Matrix3D b, ref Matrix3D result)
{
result.M11 = a.M11 - b.M11;
result.M12 = a.M12 - b.M12;
result.M13 = a.M13 - b.M13;
result.M21 = a.M21 - b.M21;
result.M22 = a.M22 - b.M22;
result.M23 = a.M23 - b.M23;
result.M31 = a.M31 - b.M31;
result.M32 = a.M32 - b.M32;
result.M33 = a.M33 - b.M33;
}
/// <summary>
/// Subtracts a scalar from a matrix and put the result in a third matrix.
/// </summary>
/// <param name="a">A <see cref="Matrix3D"/> instance.</param>
/// <param name="s">A scalar.</param>
/// <param name="result">A <see cref="Matrix3D"/> instance to hold the result.</param>
public static void Subtract(Matrix3D a, double s, ref Matrix3D result)
{
result.M11 = a.M11 - s;
result.M12 = a.M12 - s;
result.M13 = a.M13 - s;
result.M21 = a.M21 - s;
result.M22 = a.M22 - s;
result.M23 = a.M23 - s;
result.M31 = a.M31 - s;
result.M32 = a.M32 - s;
result.M33 = a.M33 - s;
}
/// <summary>
/// Multiplies two matrices.
/// </summary>
/// <param name="a">A <see cref="Matrix3D"/> instance.</param>
/// <param name="b">A <see cref="Matrix3D"/> instance.</param>
/// <returns>A new <see cref="Matrix3D"/> instance containing the result.</returns>
public static Matrix3D Multiply(Matrix3D a, Matrix3D b)
{
return new Matrix3D(
a.M11 * b.M11 + a.M12 * b.M21 + a.M13 * b.M31,
a.M11 * b.M12 + a.M12 * b.M22 + a.M13 * b.M32,
a.M11 * b.M13 + a.M12 * b.M23 + a.M13 * b.M33,
a.M21 * b.M11 + a.M22 * b.M21 + a.M23 * b.M31,
a.M21 * b.M12 + a.M22 * b.M22 + a.M23 * b.M32,
a.M21 * b.M13 + a.M22 * b.M23 + a.M23 * b.M33,
a.M31 * b.M11 + a.M32 * b.M21 + a.M33 * b.M31,
a.M31 * b.M12 + a.M32 * b.M22 + a.M33 * b.M32,
a.M31 * b.M13 + a.M32 * b.M23 + a.M33 * b.M33
);
}
/// <summary>
/// Multiplies two matrices and put the result in a third matrix.
/// </summary>
/// <param name="a">A <see cref="Matrix3D"/> instance.</param>
/// <param name="b">A <see cref="Matrix3D"/> instance.</param>
/// <param name="result">A <see cref="Matrix3D"/> instance to hold the result.</param>
public static void Multiply(Matrix3D a, Matrix3D b, ref Matrix3D result)
{
result.M11 = a.M11 * b.M11 + a.M12 * b.M21 + a.M13 * b.M31;
result.M12 = a.M11 * b.M12 + a.M12 * b.M22 + a.M13 * b.M32;
result.M13 = a.M11 * b.M13 + a.M12 * b.M23 + a.M13 * b.M33;
result.M21 = a.M21 * b.M11 + a.M22 * b.M21 + a.M23 * b.M31;
result.M22 = a.M21 * b.M12 + a.M22 * b.M22 + a.M23 * b.M32;
result.M23 = a.M21 * b.M13 + a.M22 * b.M23 + a.M23 * b.M33;
result.M31 = a.M31 * b.M11 + a.M32 * b.M21 + a.M33 * b.M31;
result.M32 = a.M31 * b.M12 + a.M32 * b.M22 + a.M33 * b.M32;
result.M33 = a.M31 * b.M13 + a.M32 * b.M23 + a.M33 * b.M33;
}
/// <summary>
/// Transforms a given vector by a matrix.
/// </summary>
/// <param name="matrix">A <see cref="Matrix3D"/> instance.</param>
/// <param name="vector">A <see cref="Vector3"/> instance.</param>
/// <returns>A new <see cref="Vector3"/> instance containing the result.</returns>
public static Vector3 Transform(Matrix3D matrix, Vector3 vector)
{
return new Vector3(
(matrix.M11 * vector.X) + (matrix.M12 * vector.Y) + (matrix.M13 * vector.Z),
(matrix.M21 * vector.X) + (matrix.M22 * vector.Y) + (matrix.M23 * vector.Z),
(matrix.M31 * vector.X) + (matrix.M32 * vector.Y) + (matrix.M33 * vector.Z));
}
/// <summary>
/// Transforms a given vector by a matrix and put the result in a vector.
/// </summary>
/// <param name="matrix">A <see cref="Matrix3D"/> instance.</param>
/// <param name="vector">A <see cref="Vector3"/> instance.</param>
/// <param name="result">A <see cref="Vector3"/> instance to hold the result.</param>
public static void Transform(Matrix3D matrix, Vector3 vector, ref Vector3 result)
{
result.X = (matrix.M11 * vector.X) + (matrix.M12 * vector.Y) + (matrix.M13 * vector.Z);
result.Y = (matrix.M21 * vector.X) + (matrix.M22 * vector.Y) + (matrix.M23 * vector.Z);
result.Z = (matrix.M31 * vector.X) + (matrix.M32 * vector.Y) + (matrix.M33 * vector.Z);
}
/// <summary>
/// Transposes a matrix.
/// </summary>
/// <param name="m">A <see cref="Matrix3D"/> instance.</param>
/// <returns>A new <see cref="Matrix3D"/> instance containing the transposed matrix.</returns>
public static Matrix3D Transpose(Matrix3D m)
{
Matrix3D t = new Matrix3D(m);
t.Transpose();
return t;
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the value of the [1,1] matrix element.
/// </summary>
public double M11
{
get { return _m11; }
set { _m11 = value;}
}
/// <summary>
/// Gets or sets the value of the [1,2] matrix element.
/// </summary>
public double M12
{
get { return _m12; }
set { _m12 = value;}
}
/// <summary>
/// Gets or sets the value of the [1,3] matrix element.
/// </summary>
public double M13
{
get { return _m13; }
set { _m13 = value;}
}
/// <summary>
/// Gets or sets the value of the [2,1] matrix element.
/// </summary>
public double M21
{
get { return _m21; }
set { _m21 = value;}
}
/// <summary>
/// Gets or sets the value of the [2,2] matrix element.
/// </summary>
public double M22
{
get { return _m22; }
set { _m22 = value;}
}
/// <summary>
/// Gets or sets the value of the [2,3] matrix element.
/// </summary>
public double M23
{
get { return _m23; }
set { _m23 = value;}
}
/// <summary>
/// Gets or sets the value of the [3,1] matrix element.
/// </summary>
public double M31
{
get { return _m31; }
set { _m31 = value;}
}
/// <summary>
/// Gets or sets the value of the [3,2] matrix element.
/// </summary>
public double M32
{
get { return _m32; }
set { _m32 = value;}
}
/// <summary>
/// Gets or sets the value of the [3,3] matrix element.
/// </summary>
public double M33
{
get { return _m33; }
set { _m33 = value;}
}
#endregion
#region Overrides
/// <summary>
/// Returns the hashcode for this instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return
_m11.GetHashCode() ^ _m12.GetHashCode() ^ _m13.GetHashCode() ^
_m21.GetHashCode() ^ _m22.GetHashCode() ^ _m23.GetHashCode() ^
_m31.GetHashCode() ^ _m32.GetHashCode() ^ _m33.GetHashCode();
}
/// <summary>
/// Returns a value indicating whether this instance is equal to
/// the specified object.
/// </summary>
/// <param name="obj">An object to compare to this instance.</param>
/// <returns><see langword="true"/> if <paramref name="obj"/> is a <see cref="Matrix3D"/> and has the same values as this instance; otherwise, <see langword="false"/>.</returns>
public override bool Equals(object obj)
{
if (obj is Matrix3D)
{
Matrix3D m = (Matrix3D)obj;
return
(_m11 == m.M11) && (_m12 == m.M12) && (_m13 == m.M13) &&
(_m21 == m.M21) && (_m22 == m.M22) && (_m23 == m.M23) &&
(_m31 == m.M31) && (_m32 == m.M32) && (_m33 == m.M33);
}
return false;
}
/// <summary>
/// Returns a string representation of this object.
/// </summary>
/// <returns>A string representation of this object.</returns>
public override string ToString()
{
StringBuilder s = new StringBuilder();
s.Append(String.Format( "|{0}, {1}, {2}|\n", _m11, _m12, _m13));
s.Append(String.Format( "|{0}, {1}, {2}|\n", _m21, _m22, _m23));
s.Append(String.Format( "|{0}, {1}, {2}|\n", _m31, _m32, _m33));
return s.ToString();
}
#endregion
#region Public Methods
/// <summary>
/// Calculates the determinant value of the matrix.
/// </summary>
/// <returns>The determinant value of the matrix.</returns>
public double Determinant()
{
// rule of Sarrus
return
_m11 * _m22 * _m33 + _m12 * _m23 * _m31 + _m13 * _m21 * _m32 -
_m13 * _m22 * _m31 - _m11 * _m23 * _m32 - _m12 * _m21 * _m33;
}
/*
/// <summary>
/// Calculates the adjoint of the matrix.
/// </summary>
/// <returns>A <see cref="Matrix3D"/> instance containing the adjoint of the matrix.</returns>
public Matrix3D Adjoint()
{
Matrix3D result = new Matrix3D();
for (int row = 0; row < 4; row++)
{
for (int col = 0; col < 4; col++)
{
if (((col+row) % 2) == 0)
result[row, col] = Minor(col, row).Determinant();
else
result[row, col] = -Minor(col, row).Determinant();
}
}
return result;
}
/// <summary>
/// Build a 3x3 matrix from from the current matrix without the given row and column.
/// </summary>
/// <param name="row">The row to remove.</param>
/// <param name="column">The column to remove.</param>
/// <returns>A <see cref="Matrix3D"/> instance containing the result Minor.</returns>
public Matrix3D Minor(int row, int column)
{
int r = 0;
Matrix3D result = new Matrix3D();
for (int row = 0; row < 4; row++)
{
int c = 0;
if (row != row)
{
for (int column = 0; column < 4; column++)
{
if (column != column)
{
result[r,c] = this[row, column];
c++;
}
}
r++;
}
}
return result;
}
*/
/// <summary>
/// Calculates the trace the matrix which is the sum of its diagonal elements.
/// </summary>
/// <returns>Returns the trace value of the matrix.</returns>
public double Trace()
{
return _m11 + _m22 + _m33;
}
/// <summary>
/// Transposes this matrix.
/// </summary>
public void Transpose()
{
MathFunctions.Swap(ref _m12, ref _m21);
MathFunctions.Swap(ref _m13, ref _m31);
MathFunctions.Swap(ref _m23, ref _m32);
}
#endregion
#region Comparison Operators
/// <summary>
/// Tests whether two specified matrices are equal.
/// </summary>
/// <param name="a">The left-hand matrix.</param>
/// <param name="b">The right-hand matrix.</param>
/// <returns><see langword="true"/> if the two matrices are equal; otherwise, <see langword="false"/>.</returns>
public static bool operator==(Matrix3D a, Matrix3D b)
{
return ValueType.Equals(a,b);
}
/// <summary>
/// Tests whether two specified matrices are not equal.
/// </summary>
/// <param name="a">The left-hand matrix.</param>
/// <param name="b">The right-hand matrix.</param>
/// <returns><see langword="true"/> if the two matrices are not equal; otherwise, <see langword="false"/>.</returns>
public static bool operator!=(Matrix3D a, Matrix3D b)
{
return !ValueType.Equals(a,b);
}
#endregion
#region Binary Operators
/// <summary>
/// Adds two matrices.
/// </summary>
/// <param name="a">A <see cref="Matrix3D"/> instance.</param>
/// <param name="b">A <see cref="Matrix3D"/> instance.</param>
/// <returns>A new <see cref="Matrix3D"/> instance containing the sum.</returns>
public static Matrix3D operator+(Matrix3D a, Matrix3D b)
{
return Matrix3D.Add(a,b);
}
/// <summary>
/// Adds a matrix and a scalar.
/// </summary>
/// <param name="a">A <see cref="Matrix3D"/> instance.</param>
/// <param name="s">A scalar.</param>
/// <returns>A new <see cref="Matrix3D"/> instance containing the sum.</returns>
public static Matrix3D operator+(Matrix3D a, double s)
{
return Matrix3D.Add(a,s);
}
/// <summary>
/// Adds a matrix and a scalar.
/// </summary>
/// <param name="a">A <see cref="Matrix3D"/> instance.</param>
/// <param name="s">A scalar.</param>
/// <returns>A new <see cref="Matrix3D"/> instance containing the sum.</returns>
public static Matrix3D operator+(double s, Matrix3D a)
{
return Matrix3D.Add(a,s);
}
/// <summary>
/// Subtracts a matrix from a matrix.
/// </summary>
/// <param name="a">A <see cref="Matrix3D"/> instance.</param>
/// <param name="b">A <see cref="Matrix3D"/> instance.</param>
/// <returns>A new <see cref="Matrix3D"/> instance containing the difference.</returns>
public static Matrix3D operator-(Matrix3D a, Matrix3D b)
{
return Matrix3D.Subtract(a,b);
}
/// <summary>
/// Subtracts a scalar from a matrix.
/// </summary>
/// <param name="a">A <see cref="Matrix3D"/> instance.</param>
/// <param name="s">A scalar.</param>
/// <returns>A new <see cref="Matrix3D"/> instance containing the difference.</returns>
public static Matrix3D operator-(Matrix3D a, double s)
{
return Matrix3D.Subtract(a,s);
}
/// <summary>
/// Multiplies two matrices.
/// </summary>
/// <param name="a">A <see cref="Matrix3D"/> instance.</param>
/// <param name="b">A <see cref="Matrix3D"/> instance.</param>
/// <returns>A new <see cref="Matrix3D"/> instance containing the result.</returns>
public static Matrix3D operator*(Matrix3D a, Matrix3D b)
{
return Matrix3D.Multiply(a,b);
}
/// <summary>
/// Transforms a given vector by a matrix.
/// </summary>
/// <param name="matrix">A <see cref="Matrix3D"/> instance.</param>
/// <param name="vector">A <see cref="Vector3"/> instance.</param>
/// <returns>A new <see cref="Vector3"/> instance containing the result.</returns>
public static Vector3 operator*(Matrix3D matrix, Vector3 vector)
{
return Matrix3D.Transform(matrix, vector);
}
#endregion
#region Indexing Operators
/// <summary>
/// Indexer allowing to access the matrix elements by an index
/// where index = 3*row + column.
/// </summary>
public double this [int index]
{
get
{
if (index < 0 || index >= 9)
throw new IndexOutOfRangeException("Invalid matrix index!");
if (index == 1) return _m11;
else if (index == 2) return _m12;
else if (index == 3) return _m13;
else if (index == 4) return _m21;
else if (index == 5) return _m22;
else if (index == 6) return _m23;
else if (index == 7) return _m31;
else if (index == 8) return _m32;
else if (index == 9) return _m33;
return Double.NaN;
}
set
{
if (index < 0 || index >= 9)
throw new IndexOutOfRangeException("Invalid matrix index!");
if (index == 1) _m11 = value;
else if (index == 2) _m12 = value;
else if (index == 3) _m13 = value;
else if (index == 4) _m21 = value;
else if (index == 5) _m22 = value;
else if (index == 6) _m23 = value;
else if (index == 7) _m31 = value;
else if (index == 8) _m32 = value;
else if (index == 9) _m33 = value;
}
}
/// <summary>
/// Indexer allowing to access the matrix elements by row and column.
/// </summary>
public double this[int row, int column]
{
get
{
return this[ (row-1)*3 + (column-1) ];
}
set
{
this[ (row-1)*3 + (column-1) ] = value;
}
}
#endregion
}
}
| |
// 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.ContainerInstance.Fluent
{
using Microsoft.Azure.Management.ContainerInstance.Fluent.Models;
using Microsoft.Azure.Management.ContainerInstance.Fluent.ContainerGroup.Definition;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition;
using System.Collections.Generic;
internal partial class ContainerImpl
{
/// <summary>
/// Specifies the container's TCP port is available to internal clients only (other container instances within the container group).
/// Containers within a group can reach each other via localhost on the ports that they have exposed,
/// even if those ports are not exposed externally on the group's IP address.
/// </summary>
/// <param name="port">TCP port to be exposed internally.</param>
/// <return>The next stage of the definition.</return>
ContainerGroup.Definition.IWithPortsOrContainerInstanceAttach<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithPorts<ContainerGroup.Definition.IWithNextContainerInstance>.WithInternalTcpPort(int port)
{
return this.WithInternalTcpPort(port);
}
/// <summary>
/// Specifies the container's UDP port is available to internal clients only (other container instances within the container group).
/// Containers within a group can reach each other via localhost on the ports that they have exposed,
/// even if those ports are not exposed externally on the group's IP address.
/// </summary>
/// <param name="port">UDP port to be exposed internally.</param>
/// <return>The next stage of the definition.</return>
ContainerGroup.Definition.IWithPortsOrContainerInstanceAttach<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithPorts<ContainerGroup.Definition.IWithNextContainerInstance>.WithInternalUdpPort(int port)
{
return this.WithInternalUdpPort(port);
}
/// <summary>
/// Specifies the container's TCP ports are available to internal clients only (other container instances within the container group).
/// Containers within a group can reach each other via localhost on the ports that they have exposed,
/// even if those ports are not exposed externally on the group's IP address.
/// </summary>
/// <param name="ports">Array of TCP ports to be exposed internally.</param>
/// <return>The next stage of the definition.</return>
ContainerGroup.Definition.IWithPortsOrContainerInstanceAttach<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithPorts<ContainerGroup.Definition.IWithNextContainerInstance>.WithInternalTcpPorts(params int[] ports)
{
return this.WithInternalTcpPorts(ports);
}
/// <summary>
/// Specifies the container's UDP ports are available to internal clients only (other container instances within the container group).
/// Containers within a group can reach each other via localhost on the ports that they have exposed,
/// even if those ports are not exposed externally on the group's IP address.
/// </summary>
/// <param name="ports">Array of UDP ports to be exposed internally.</param>
/// <return>The next stage of the definition.</return>
ContainerGroup.Definition.IWithPortsOrContainerInstanceAttach<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithPorts<ContainerGroup.Definition.IWithNextContainerInstance>.WithInternalUdpPorts(params int[] ports)
{
return this.WithInternalUdpPorts(ports);
}
/// <summary>
/// Specifies the container's TCP port available to external clients.
/// A public IP address will be create to allow external clients to reach the containers within the group.
/// To enable external clients to reach a container within the group, you must expose the port on the
/// IP address and from the container. Because containers within the group share a port namespace, port
/// mapping is not supported.
/// </summary>
/// <param name="port">TCP port to be exposed externally.</param>
/// <return>The next stage of the definition.</return>
ContainerGroup.Definition.IWithPortsOrContainerInstanceAttach<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithPorts<ContainerGroup.Definition.IWithNextContainerInstance>.WithExternalTcpPort(int port)
{
return this.WithExternalTcpPort(port);
}
/// <summary>
/// Specifies the container's UDP ports available to external clients.
/// A public IP address will be create to allow external clients to reach the containers within the group.
/// To enable external clients to reach a container within the group, you must expose the port on the
/// IP address and from the container. Because containers within the group share a port namespace, port
/// mapping is not supported.
/// </summary>
/// <param name="ports">Array of UDP ports to be exposed externally.</param>
/// <return>The next stage of the definition.</return>
ContainerGroup.Definition.IWithPortsOrContainerInstanceAttach<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithPorts<ContainerGroup.Definition.IWithNextContainerInstance>.WithExternalUdpPorts(params int[] ports)
{
return this.WithExternalUdpPorts(ports);
}
/// <summary>
/// Specifies the container's UDP port available to external clients.
/// A public IP address will be create to allow external clients to reach the containers within the group.
/// To enable external clients to reach a container within the group, you must expose the port on the
/// IP address and from the container. Because containers within the group share a port namespace, port
/// mapping is not supported.
/// </summary>
/// <param name="port">UDP port to be exposed externally.</param>
/// <return>The next stage of the definition.</return>
ContainerGroup.Definition.IWithPortsOrContainerInstanceAttach<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithPorts<ContainerGroup.Definition.IWithNextContainerInstance>.WithExternalUdpPort(int port)
{
return this.WithExternalUdpPort(port);
}
/// <summary>
/// Specifies the container's TCP ports available to external clients.
/// A public IP address will be create to allow external clients to reach the containers within the group.
/// To enable external clients to reach a container within the group, you must expose the port on the
/// IP address and from the container. Because containers within the group share a port namespace, port
/// mapping is not supported.
/// </summary>
/// <param name="ports">Array of TCP ports to be exposed externally.</param>
/// <return>The next stage of the definition.</return>
ContainerGroup.Definition.IWithPortsOrContainerInstanceAttach<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithPorts<ContainerGroup.Definition.IWithNextContainerInstance>.WithExternalTcpPorts(params int[] ports)
{
return this.WithExternalTcpPorts(ports);
}
/// <summary>
/// Specifies that not ports will be opened internally or externally for this container instance.
/// </summary>
/// <return>The next stage of the definition.</return>
ContainerGroup.Definition.IWithContainerInstanceAttach<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithoutPorts<ContainerGroup.Definition.IWithNextContainerInstance>.WithoutPorts()
{
return this.WithoutPorts();
}
/// <summary>
/// Specifies the starting command line.
/// </summary>
/// <param name="executable">The executable which it will call after initializing the container.</param>
/// <param name="parameters">The parameter list for the executable to be called.</param>
/// <return>The next stage of the definition.</return>
ContainerGroup.Definition.IWithContainerInstanceAttach<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithStartingCommandLineBeta<ContainerGroup.Definition.IWithNextContainerInstance>.WithStartingCommandLine(string executable, params string[] parameters)
{
return this.WithStartingCommandLine(executable, parameters);
}
/// <summary>
/// Specifies the starting command line.
/// </summary>
/// <param name="executable">The executable or path to the executable that will be called after initializing the container.</param>
/// <return>The next stage of the definition.</return>
ContainerGroup.Definition.IWithContainerInstanceAttach<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithStartingCommandLine<ContainerGroup.Definition.IWithNextContainerInstance>.WithStartingCommandLine(string executable)
{
return this.WithStartingCommandLine(executable);
}
/// <summary>
/// Specifies the container group's volume to be mounted by the container instance at a specified mount path.
/// Mounting an Azure file share as a volume in a container is a two-step process. First, you provide
/// the details of the share as part of defining the container group, then you specify how you wan
/// the volume mounted within one or more of the containers in the group.
/// </summary>
/// <param name="volumeName">The volume name as defined in the volumes of the container group.</param>
/// <param name="mountPath">The local path the volume will be mounted at.</param>
/// <return>The next stage of the definition.</return>
/// <throws>IllegalArgumentException thrown if volumeName was not defined in the respective container group definition stage.</throws>
ContainerGroup.Definition.IWithContainerInstanceAttach<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithVolumeMountSetting<ContainerGroup.Definition.IWithNextContainerInstance>.WithVolumeMountSetting(string volumeName, string mountPath)
{
return this.WithVolumeMountSetting(volumeName, mountPath);
}
/// <summary>
/// Specifies the container group's volume to be mounted by the container instance at a specified mount path.
/// Mounting an Azure file share as a volume in a container is a two-step process. First, you provide
/// the details of the share as part of defining the container group, then you specify how you wan
/// the volume mounted within one or more of the containers in the group.
/// </summary>
/// <param name="volumeMountSetting">The name and value pair representing volume names as defined in the volumes of the container group and the local paths the volume will be mounted at.</param>
/// <return>The next stage of the definition.</return>
/// <throws>IllegalArgumentException thrown if volumeName was not defined in the respective container group definition stage.</throws>
ContainerGroup.Definition.IWithContainerInstanceAttach<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithVolumeMountSetting<ContainerGroup.Definition.IWithNextContainerInstance>.WithVolumeMountSetting(IDictionary<string,string> volumeMountSetting)
{
return this.WithVolumeMountSetting(volumeMountSetting);
}
/// <summary>
/// Specifies the container group's volume to be mounted by the container instance at a specified mount path.
/// Mounting an Azure file share as a volume in a container is a two-step process. First, you provide
/// the details of the share as part of defining the container group, then you specify how you wan
/// the volume mounted within one or more of the containers in the group.
/// </summary>
/// <param name="volumeName">The volume name as defined in the volumes of the container group.</param>
/// <param name="mountPath">The local path the volume will be mounted at.</param>
/// <return>The next stage of the definition.</return>
/// <throws>IllegalArgumentException thrown if volumeName was not defined in the respective container group definition stage.</throws>
ContainerGroup.Definition.IWithContainerInstanceAttach<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithVolumeMountSetting<ContainerGroup.Definition.IWithNextContainerInstance>.WithReadOnlyVolumeMountSetting(string volumeName, string mountPath)
{
return this.WithReadOnlyVolumeMountSetting(volumeName, mountPath);
}
/// <summary>
/// Specifies the container group's volume to be mounted by the container instance at a specified mount path.
/// Mounting an Azure file share as a volume in a container is a two-step process. First, you provide
/// the details of the share as part of defining the container group, then you specify how you wan
/// the volume mounted within one or more of the containers in the group.
/// </summary>
/// <param name="volumeMountSetting">The name and value pair representing volume names as defined in the volumes of the container group and the local paths the volume will be mounted at.</param>
/// <return>The next stage of the definition.</return>
/// <throws>IllegalArgumentException thrown if volumeName was not defined in the respective container group definition stage.</throws>
ContainerGroup.Definition.IWithContainerInstanceAttach<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithVolumeMountSetting<ContainerGroup.Definition.IWithNextContainerInstance>.WithReadOnlyVolumeMountSetting(IDictionary<string,string> volumeMountSetting)
{
return this.WithReadOnlyVolumeMountSetting(volumeMountSetting);
}
/// <summary>
/// Specifies the number of CPU cores assigned to this container instance.
/// </summary>
/// <param name="cpuCoreCount">The number of CPU cores.</param>
/// <return>The next stage of the definition.</return>
ContainerGroup.Definition.IWithContainerInstanceAttach<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithCpuCoreCount<ContainerGroup.Definition.IWithNextContainerInstance>.WithCpuCoreCount(double cpuCoreCount)
{
return this.WithCpuCoreCount(cpuCoreCount);
}
/// <summary>
/// Attaches the child definition to the parent resource definiton.
/// </summary>
/// <return>The next stage of the parent definition.</return>
ContainerGroup.Definition.IWithNextContainerInstance Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition.IInDefinition<ContainerGroup.Definition.IWithNextContainerInstance>.Attach()
{
return this.Attach();
}
/// <summary>
/// Specifies the memory size in GB assigned to this container instance.
/// </summary>
/// <param name="memorySize">The memory size in GB.</param>
/// <return>The next stage of the definition.</return>
ContainerGroup.Definition.IWithContainerInstanceAttach<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithMemorySize<ContainerGroup.Definition.IWithNextContainerInstance>.WithMemorySizeInGB(double memorySize)
{
return this.WithMemorySizeInGB(memorySize);
}
/// <summary>
/// Specifies the environment variable.
/// </summary>
/// <param name="envName">The environment variable name.</param>
/// <param name="envValue">The environment variable value.</param>
/// <return>The next stage of the definition.</return>
ContainerGroup.Definition.IWithContainerInstanceAttach<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithEnvironmentVariables<ContainerGroup.Definition.IWithNextContainerInstance>.WithEnvironmentVariable(string envName, string envValue)
{
return this.WithEnvironmentVariable(envName, envValue);
}
/// <summary>
/// Specifies the environment variables.
/// </summary>
/// <param name="environmentVariables">The environment variables in a name and value pair to be set after the container gets initialized.</param>
/// <return>The next stage of the definition.</return>
ContainerGroup.Definition.IWithContainerInstanceAttach<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithEnvironmentVariables<ContainerGroup.Definition.IWithNextContainerInstance>.WithEnvironmentVariables(IDictionary<string,string> environmentVariables)
{
return this.WithEnvironmentVariables(environmentVariables);
}
/// <summary>
/// Specifies a collection of name and secure value pairs for the environment variables.
/// </summary>
/// <param name="envName">The environment variable name.</param>
/// <param name="securedValue">The environment variable secured value.</param>
/// <return>The next stage of the definition.</return>
ContainerGroup.Definition.IWithContainerInstanceAttach<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithEnvironmentVariables<ContainerGroup.Definition.IWithNextContainerInstance>.WithEnvironmentVariableWithSecuredValue(string envName, string securedValue)
{
return this.WithEnvironmentVariableWithSecuredValue(envName, securedValue);
}
/// <summary>
/// Specifies a collection of name and secure value pairs for the environment variables.
/// </summary>
/// <param name="environmentVariables">The environment variables in a name and value pair to be set after the container gets initialized.</param>
/// <return>The next stage of the definition.</return>
ContainerGroup.Definition.IWithContainerInstanceAttach<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithEnvironmentVariables<ContainerGroup.Definition.IWithNextContainerInstance>.WithEnvironmentVariablesWithSecuredValue(IDictionary<string, string> environmentVariables)
{
return this.WithEnvironmentVariablesWithSecuredValue(environmentVariables);
}
/// <summary>
/// Specifies the container image to be used.
/// </summary>
/// <param name="imageName">The container image.</param>
/// <return>The next stage of the definition.</return>
ContainerGroup.Definition.IWithOrWithoutPorts<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithImage<ContainerGroup.Definition.IWithNextContainerInstance>.WithImage(string imageName)
{
return this.WithImage(imageName);
}
}
}
| |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Predator.Characters;
using Predator.Other;
using System;
using System.Collections.Generic;
using VoidEngine.Helpers;
using VoidEngine.Particles;
using VoidEngine.VGame;
using VoidEngine.VGUI;
namespace Predator.Managers
{
/// <summary>
/// This is a game component that implements IUpdateable.
/// </summary>
public class GameManager : Microsoft.Xna.Framework.DrawableGameComponent
{
/// <summary>
/// The game that the game manager runs off of.
/// </summary>
private Game1 myGame;
/// <summary>
/// The sprite batch that the game manager uses.
/// </summary>
private SpriteBatch spriteBatch;
/// <summary>
/// Used to control the game's screen.
/// </summary>
public Camera Camera;
/// <summary>
/// Used to get random real numbers.
/// </summary>
protected Random Random = new Random();
#region Textures
/// <summary>
///
/// </summary>
public Texture2D SlimeTexture;
/// <summary>
///
/// </summary>
public Texture2D SpitterTexture;
/// <summary>
/// Loads the line texture.
/// </summary>
public Texture2D LineTexture;
/// <summary>
/// Loads the shadow tile texture.
/// </summary>
public Texture2D ShadowTileTexture;
/// <summary>
/// Loads the sewer tile texture.
/// </summary>
public Texture2D SewerTileTexture;
/// <summary>
///
/// </summary>
public Texture2D ConcreteTileTexture;
/// <summary>
/// Loads the temp player texture.
/// </summary>
public Texture2D TempPlayerTexture;
/// <summary>
/// Loads the projectile texture.
/// </summary>
public Texture2D ProjectileTexture;
/// <summary>
/// Loads the crawler enemy texture.
/// </summary>
public Texture2D CrawlerTexture;
/// <summary>
/// Loads the temp enemy texture.
/// </summary>
public Texture2D TempEnemyTexture;
/// <summary>
/// Loads the particle texture.
/// </summary>
public Texture2D ParticleTexture;
/// <summary>
/// Loads the health drop texture.
/// </summary>
public Texture2D HealthDropTexture;
/// <summary>
/// Loads the exp drop texture.
/// </summary>
public Texture2D ExpDropTexture;
/// <summary>
/// Loads the temp tile texture.
/// </summary>
public Texture2D TempTileTexture;
/// <summary>
/// Loads the main healthbar background texture.
/// </summary>
public Texture2D HealthBackgroundTexture;
/// <summary>
/// Loads the main healthbar foreground texture.
/// </summary>
public Texture2D HealthForegroundTexture;
/// <summary>
/// Loads the overhead healthbar background texture.
/// </summary>
public Texture2D HealthOverheadBackgroundTexture;
/// <summary>
/// Loads the overhead healthbar foreground texture.
/// </summary>
public Texture2D HealthOverheadForegroundTexture;
/// <summary>
/// Loads the sewer background spray texture.
/// </summary>
public Texture2D SewerBackgroundSprayTexture;
/// <summary>
/// Loads the sewer background texture.
/// </summary>
public Texture2D SewerBackgroundTexture;
/// <summary>
///
/// </summary>
public Texture2D HQBackgroundTexture;
/// <summary>
///
/// </summary>
public Texture2D HQForegroundTexture;
/// <summary>
///
/// </summary>
public Texture2D CityBuildingBackgroundTexture;
/// <summary>
///
/// </summary>
public Texture2D CitySkyBackgroundTexture;
/// <summary>
///
/// </summary>
public Texture2D CityFogBackgroundTexture;
/// <summary>
/// Loads the checkpoint texture.
/// </summary>
public Texture2D CheckpointTexture;
/// <summary>
///
/// </summary>
public Texture2D WaterTileTexture;
/// <summary>
///
/// </summary>
public Texture2D LadderTileTexture;
#endregion
#region Enemy Stuff
/// <summary>
/// The Enemy list.
/// Enemy: UNKNOWN
/// </summary>
public List<Enemy> EnemyList = new List<Enemy>();
/// <summary>
///
/// </summary>
public List<Sprite.AnimationSet> SpitterAnimationSet = new List<Sprite.AnimationSet>();
/// <summary>
///
/// </summary>
public List<Sprite.AnimationSet> JumperAnimationSet = new List<Sprite.AnimationSet>();
/// <summary>
///
/// </summary>
public List<Sprite.AnimationSet> RollerAnimationSet = new List<Sprite.AnimationSet>();
/// <summary>
///
/// </summary>
public List<Sprite.AnimationSet> CrawlerAnimationSet = new List<Sprite.AnimationSet>();
/// <summary>
///
/// </summary>
public int EnemyLevel;
#endregion
#region Tile Stuff
/// <summary>
/// The tile objects
/// </summary>
public List<Tile> TilesList = new List<Tile>();
#endregion
#region Background Stuff
/// <summary>
/// The sewer background parallax.
/// </summary>
public Parallax SewerBackgroundParallax;
/// <summary>
/// The sewer background spray parallax.
/// </summary>
public Parallax SewerBackgroundSprayParallax;
/// <summary>
///
/// </summary>
public Parallax HQBackgroundParallax;
/// <summary>
///
/// </summary>
public Parallax HQForegroundParallax;
/// <summary>
///
/// </summary>
public Parallax CityBuildingBackgroundParallax;
/// <summary>
///
/// </summary>
public Parallax CityFogBackgroundParallax;
/// <summary>
///
/// </summary>
public Parallax CitySkyBackgroundParallax;
#endregion
#region Player Stuff
/// <summary>
/// The default player.
/// </summary>
public Player Player;
/// <summary>
/// The player's movement keys.
/// </summary>
public Keys[,] MovementKeys = new Keys[4, 15];
/// <summary>
/// The main healthbar.
/// </summary>
public HealthBar HealthBar;
/// <summary>
/// The overhead healthbar.
/// </summary>
public HealthBar OverheadHealthBar;
/// <summary>
/// The drop list for the health pickups.
/// </summary>
public List<HealthPickUp> HpDropList = new List<HealthPickUp>();
/// <summary>
/// The drop list for the exp pickups.
/// </summary>
public List<ExpPickUp> ExpDropList = new List<ExpPickUp>();
/// <summary>
/// Gets or sets the amount of time to take the player to respawn.
/// </summary>
public float playerDeathTimer
{
get;
set;
}
#endregion
#region Level & Transition Stuff
/// <summary>
/// The level of the game.
/// </summary>
public int CurrentLevel = 1;
/// <summary>
///
/// </summary>
public int LastLevel
{
get;
set;
}
/// <summary>
/// The map boarders list.
/// </summary>
public List<Rectangle> MapBoundries = new List<Rectangle>();
/// <summary>
/// Gets or sets if the level is loaded.
/// DO NOT SET TO TRUE!!!
/// </summary>
public bool LevelLoaded
{
get;
set;
}
/// <summary>
/// Sets the camera to the player if true.
/// </summary>
public bool CameraToPlayer
{
get;
set;
}
protected Texture2D TestLevelTextureMap;
protected Texture2D Sewer1TextureMap;
protected Texture2D Sewer2TextureMap;
protected Texture2D City1TextureMap;
protected Texture2D City2TextureMap;
protected Texture2D BridgeTextureMap;
protected Texture2D HQ1TextureMap;
public bool Transistioning;
public float alpha = 255;
#endregion
#region Partical System
/// <summary>
/// The list of the particles.
/// </summary>
public List<Particle> ParticleList = new List<Particle>();
/// <summary>
/// Gets or sets the blood's minimum radius.
/// </summary>
public float BloodMinRadius
{
get;
set;
}
/// <summary>
/// Gets or sets the blood's maximum radius.
/// </summary>
public float BloodMaxRadius
{
get;
set;
}
#endregion
#region Checkpoints
/// <summary>
///
/// </summary>
public int LastCheckpoint
{
get;
set;
}
/// <summary>
///
/// </summary>
public Vector2[] ListOfCheckpoints = new Vector2[100];
/// <summary>
///
/// </summary>
int checkpointNum = 1;
#endregion
#region Objects
public List<PlaceableObject> PlaceableObjectsList = new List<PlaceableObject>();
#endregion
/// <summary>
/// Creates the game manager.
/// </summary>
/// <param name="game">The game that the game manager is running off of.</param>
public GameManager(Game1 game)
: base(game)
{
myGame = game;
// TODO: Construct any child components here
Initialize();
}
/// <summary>
/// Allows the game component to perform any initialization it needs to before starting
/// to run. This is where it can query for any required services and load content.
/// </summary>
public override void Initialize()
{
// TODO: Add your initialization code here
base.Initialize();
}
/// <summary>
/// Loads the content for the game manager.
/// </summary>
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(myGame.GraphicsDevice);
LoadTextures();
#region Player Stuff
MovementKeys[0, 0] = Keys.A;
MovementKeys[0, 1] = Keys.W;
MovementKeys[0, 2] = Keys.D;
MovementKeys[0, 3] = Keys.S;
MovementKeys[0, 4] = Keys.Space;
MovementKeys[0, 5] = Keys.E;
MovementKeys[1, 0] = Keys.Left;
MovementKeys[1, 1] = Keys.Up;
MovementKeys[1, 2] = Keys.Right;
MovementKeys[1, 3] = Keys.Down;
Player = new Player(TempPlayerTexture, new Vector2(100, 100), MovementKeys, Color.White, myGame);
Player.ProjectileTexture = ProjectileTexture;
CameraToPlayer = true;
HealthBar = new HealthBar(HealthForegroundTexture, new Vector2(20, 25), Color.White);
OverheadHealthBar = new HealthBar(HealthOverheadForegroundTexture, new Vector2(Player.Position.X - ((48 - 35) / 2), Player.Position.Y - 10), Color.White);
#endregion
#region Game Stuff
Camera = new Camera(myGame.GraphicsDevice.Viewport, new Point(1024, 768), 1.0f);
MapBoundries.Add(new Rectangle(-5, -105, 5, Camera.Size.Y + 10));
MapBoundries.Add(new Rectangle(-5, -105, Camera.Size.X + 10, 5));
MapBoundries.Add(new Rectangle(Camera.Size.X, -105, 5, Camera.Size.Y + 10));
MapBoundries.Add(new Rectangle(-5, Camera.Size.Y, Camera.Size.X + 10, 5));
MapBoundries.Add(new Rectangle(Camera.Size.X, Camera.Size.Y, 25, 5));
SewerBackgroundParallax = new Parallax(SewerBackgroundTexture, new Vector2(Camera.Position.X, Camera.Position.Y), Color.White, new Vector2(2.50f, 2.50f), Camera);
SewerBackgroundSprayParallax = new Parallax(SewerBackgroundSprayTexture, new Vector2(Camera.Position.X, Camera.Position.Y), Color.White, new Vector2(2.50f, 2.50f), Camera);
CityBuildingBackgroundParallax = new Parallax(CityBuildingBackgroundTexture, new Vector2(Camera.Position.X, Camera.Position.Y), Color.White, new Vector2(2.50f, 2.50f), Camera);
CityFogBackgroundParallax = new Parallax(CityFogBackgroundTexture, new Vector2(Camera.Position.X, Camera.Position.Y), Color.White, new Vector2(1.50f, 1.50f), Camera);
CitySkyBackgroundParallax = new Parallax(CitySkyBackgroundTexture, new Vector2(Camera.Position.X, Camera.Position.Y), Color.White, new Vector2(0.50f, 0.50f), Camera);
HQBackgroundParallax = new Parallax(HQBackgroundTexture, new Vector2(Camera.Position.X, Camera.Position.Y), Color.White, new Vector2(2.50f, 2.50f), Camera);
HQForegroundParallax = new Parallax(HQForegroundTexture, new Vector2(Camera.Position.X, Camera.Position.Y), Color.White, new Vector2(1.50f, 1.50f), Camera);
#endregion
base.LoadContent();
}
/// <summary>
/// Loads the textures for the game manager.
/// </summary>
protected void LoadTextures()
{
// Debug
LineTexture = Game.Content.Load<Texture2D>(@"images\other\line");
// Tiles
TempTileTexture = Game.Content.Load<Texture2D>(@"images\tiles\tempTiles");
SewerTileTexture = Game.Content.Load<Texture2D>(@"images\tiles\sewerTiles");
ShadowTileTexture = Game.Content.Load<Texture2D>(@"images\tiles\fadeTiles");
WaterTileTexture = Game.Content.Load<Texture2D>(@"images\tiles\waterTiles");
ConcreteTileTexture = Game.Content.Load<Texture2D>(@"images\tiles\concreteTiles");
LadderTileTexture = Game.Content.Load<Texture2D>(@"images\tiles\ladderTiles");
// Player and entities
TempPlayerTexture = Game.Content.Load<Texture2D>(@"images\player\Player_Spritesheet");
TempEnemyTexture = Game.Content.Load<Texture2D>(@"images\enemy\tempEnemy");
CrawlerTexture = Game.Content.Load<Texture2D>(@"images\enemy\crawler1");
// UI
HealthForegroundTexture = Game.Content.Load<Texture2D>(@"images\gui\game\healthBarFore");
HealthBackgroundTexture = Game.Content.Load<Texture2D>(@"images\gui\game\healthBarBack");
HealthOverheadForegroundTexture = Game.Content.Load<Texture2D>(@"images\gui\game\healthBarOverFore");
HealthOverheadBackgroundTexture = Game.Content.Load<Texture2D>(@"images\gui\game\healthBarOverback");
SlimeTexture = Game.Content.Load<Texture2D>(@"images\enemy\Spit_Glob");
SpitterTexture = Game.Content.Load<Texture2D>(@"images\enemy\spitter1");
// Effects
ProjectileTexture = Game.Content.Load<Texture2D>(@"images\game\particles\tempParticle");
ParticleTexture = Game.Content.Load<Texture2D>(@"images\game\particles\tempParticle");
// Drops
HealthDropTexture = Game.Content.Load<Texture2D>(@"images\game\drops\healthDrop");
ExpDropTexture = Game.Content.Load<Texture2D>(@"images\game\drops\XPSprite");
// Backgrounds
SewerBackgroundSprayTexture = Game.Content.Load<Texture2D>(@"images\game\backgrounds\funBackground");
SewerBackgroundTexture = Game.Content.Load<Texture2D>(@"images\game\backgrounds\sewerBackground");
CityBuildingBackgroundTexture = Game.Content.Load<Texture2D>(@"images\game\backgrounds\cityBuildingBackground");
CitySkyBackgroundTexture = Game.Content.Load<Texture2D>(@"images\game\backgrounds\citySkyBackground");
CityFogBackgroundTexture = Game.Content.Load<Texture2D>(@"images\game\backgrounds\cityFogBackground");
HQBackgroundTexture = Game.Content.Load<Texture2D>(@"images\game\backgrounds\hqBackground");
HQForegroundTexture = Game.Content.Load<Texture2D>(@"images\game\backgrounds\hqForeground");
// Objects
CheckpointTexture = Game.Content.Load<Texture2D>(@"images\objects\checkpoint");
// Levels
TestLevelTextureMap = Game.Content.Load<Texture2D>(@"levels\testlevel");
Sewer1TextureMap = Game.Content.Load<Texture2D>(@"levels\Sewer_1");
Sewer2TextureMap = Game.Content.Load<Texture2D>(@"levels\Sewer_2");
City1TextureMap = Game.Content.Load<Texture2D>(@"levels\City_1");
City2TextureMap = Game.Content.Load<Texture2D>(@"levels\City_2");
BridgeTextureMap = Game.Content.Load<Texture2D>(@"levels\Bridge");
HQ1TextureMap = Game.Content.Load<Texture2D>(@"levels\HQ_1");
// Sprite sheets
CrawlerAnimationSet.Add(new Sprite.AnimationSet("IDLE", CrawlerTexture, new Point(122, 65), new Point(1, 1), new Point(0, 0), 16000, false));
CrawlerAnimationSet.Add(new Sprite.AnimationSet("WALK", CrawlerTexture, new Point(120, 61), new Point(2, 2), new Point(0, 0), 80, true));
CrawlerAnimationSet.Add(new Sprite.AnimationSet("DEATH", CrawlerTexture, new Point(122, 65), new Point(1, 1), new Point(0, 0), 16000, false));
SpitterAnimationSet.Add(new Sprite.AnimationSet("IDLE", SpitterTexture, new Point(120, 240), new Point(1, 1), new Point(0, 0), 16000, false));
SpitterAnimationSet.Add(new Sprite.AnimationSet("WALK", SpitterTexture, new Point(120, 240), new Point(6, 1), new Point(120, 0), 100, true));
SpitterAnimationSet.Add(new Sprite.AnimationSet("SHOOT", SpitterTexture, new Point(120, 240), new Point(5, 1), new Point(120, 240), 130, true));
RollerAnimationSet.Add(new Sprite.AnimationSet("ROLL", CrawlerTexture, new Point(122, 65), new Point(1, 1), new Point(0, 0), 16000, false));
JumperAnimationSet.Add(new Sprite.AnimationSet("IDLE", CrawlerTexture, new Point(122, 65), new Point(1, 1), new Point(0, 0), 16000, false));
JumperAnimationSet.Add(new Sprite.AnimationSet("WALK", CrawlerTexture, new Point(122, 65), new Point(1, 1), new Point(0, 0), 16000, false));
JumperAnimationSet.Add(new Sprite.AnimationSet("DIVE", CrawlerTexture, new Point(122, 65), new Point(1, 1), new Point(0, 0), 16000, false));
}
/// <summary>
/// Allows the game component to update itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public override void Update(GameTime gameTime)
{
#region Camera Controls
#region Debug Camera Controls
if (myGame.IsGameDebug)
{
// Rotate the camera to the left.
if (myGame.KeyboardState.IsKeyDown(Keys.NumPad4))
{
Camera.RotationZ += 1 * (float)Math.PI / 180;
}
// Rotate the camera to the right.
if (myGame.KeyboardState.IsKeyDown(Keys.NumPad6))
{
Camera.RotationZ -= 1 * (float)Math.PI / 180;
}
/// Zoom the camera in.
if (myGame.KeyboardState.IsKeyDown(Keys.NumPad8))
{
Camera.Zoom += 0.01f;
}
/// Zome the camera out.
if (myGame.KeyboardState.IsKeyDown(Keys.NumPad2))
{
Camera.Zoom -= 0.01f;
}
/// Reset the camera.
if (myGame.KeyboardState.IsKeyDown(Keys.NumPad5))
{
Camera.Zoom = 1f;
Camera.RotationZ = 0;
Camera.Position = Player.Position;
}
}
#endregion
// Update the camera's position.
if (CameraToPlayer)
{
Camera.Position = Player.PositionCenter;
}
#endregion
#region Menu Controls
// Open the map.
if (myGame.CheckKey(Keys.M) && !myGame.mapScreenManager.isTransitioningIn)
{
myGame.mapScreenManager.isTransitioningIn = true;
myGame.SetCurrentLevel(Game1.GameLevels.MAP);
}
// Open the stats screen.
if (myGame.CheckKey(Keys.G))
{
myGame.SetCurrentLevel(Game1.GameLevels.STATS);
}
// Open the main menu
if (myGame.CheckKey(Keys.Q))
{
myGame.SetCurrentLevel(Game1.GameLevels.MENU);
}
#endregion
if (Player.isDead)
{
playerDeathTimer -= gameTime.ElapsedGameTime.Milliseconds;
if (LastCheckpoint > 0)
{
if (playerDeathTimer < 0)
{
Player.Position = ListOfCheckpoints[LastCheckpoint];
}
}
else
{
if (playerDeathTimer < 0)
{
RegenerateMap();
}
}
}
if (myGame.KeyboardState.IsKeyDown(Keys.LeftControl) && myGame.KeyboardState.IsKeyDown(Keys.LeftAlt) && myGame.CheckKey(Keys.C))
{
myGame.IsGameDebug = !myGame.IsGameDebug;
}
if (myGame.CheckKey(Keys.X) && myGame.IsGameDebug)
{
myGame.gameManager.Player.PExp += 500;
}
// Reset The level
if (!LevelLoaded && LastLevel != CurrentLevel)
{
LastLevel = CurrentLevel;
Transistioning = true;
RegenerateMap();
}
#region Saving & Loading
if (myGame.CheckKey(Keys.F6))
{
SaveFile tempSaveFile = new SaveFile();
FileManagerTemplate.Game gameData = new FileManagerTemplate.Game();
gameData.CurrentLevel = CurrentLevel;
FileManagerTemplate.Options optionsData = new FileManagerTemplate.Options();
optionsData.VSync = myGame.VSync;
optionsData.WindowSize = myGame.WindowSize;
FileManagerTemplate.PlayerData playerData = new FileManagerTemplate.PlayerData();
playerData.Damage = Player.Damage;
playerData.Defense = Player.Defense;
playerData.Level = Player.Level;
playerData.Lvl = Player.Lvl;
playerData.MainHP = Player.MainHP;
playerData.MaxHP = Player.MaxHP;
playerData.MovementKeys = Player.MovementKeys;
playerData.PAgility = Player.PAgility;
playerData.PDefense = Player.PDefense;
playerData.PExp = Player.PExp;
playerData.Position = Player.Position;
playerData.PStrength = Player.PStrength;
playerData.StatPoints = Player.StatPoints;
playerData.LastCheckpoint = LastCheckpoint;
tempSaveFile.FileSaveVersion = "0.0.0.1";
tempSaveFile.GameData = gameData;
tempSaveFile.OptionsData = optionsData;
tempSaveFile.PlayerData = playerData;
SaveFileManager.SaveFile(tempSaveFile, "", "Save1.sav");
}
if (myGame.CheckKey(Keys.F5))
{
SaveFile tempSaveFile = SaveFileManager.LoadFile("", "Save1.sav");
if (tempSaveFile.FileSaveVersion == "0.0.0.1")
{
CurrentLevel = tempSaveFile.GameData.CurrentLevel;
myGame.VSync = tempSaveFile.OptionsData.VSync;
myGame.WindowSize = tempSaveFile.OptionsData.WindowSize;
myGame.ApplySettings = true;
Player.Damage = tempSaveFile.PlayerData.Damage;
Player.Defense = tempSaveFile.PlayerData.Defense;
Player.Level = tempSaveFile.PlayerData.Level;
Player.Lvl = tempSaveFile.PlayerData.Lvl;
Player.MainHP = tempSaveFile.PlayerData.MainHP;
Player.MaxHP = tempSaveFile.PlayerData.MaxHP;
Player.MovementKeys = tempSaveFile.PlayerData.MovementKeys;
Player.PAgility = tempSaveFile.PlayerData.PAgility;
Player.PDefense = tempSaveFile.PlayerData.PDefense;
Player.PExp = tempSaveFile.PlayerData.PExp;
Player.Position = tempSaveFile.PlayerData.Position;
Player.PStrength = tempSaveFile.PlayerData.PStrength;
Player.StatPoints = tempSaveFile.PlayerData.StatPoints;
LastCheckpoint = tempSaveFile.PlayerData.LastCheckpoint;
Camera.Position = Player.Position;
}
}
#endregion
#region Update when level is loaded.
if (LevelLoaded)
{
#region Update Player Stuff
Player.UpdateKeyboardState(gameTime, myGame.KeyboardState);
Player.Update(gameTime);
//HealthBar.SetPlayer = Player;
HealthBar.Update(gameTime, Player.HP, Player.MaxHP);
OverheadHealthBar.Update(gameTime, Player.HP, Player.MaxHP);
OverheadHealthBar.Position = new Vector2(Player.Position.X - ((44 - 35) / 2), Player.Position.Y - 7);
if (Player.isDead)
{
playerDeathTimer -= gameTime.ElapsedGameTime.Milliseconds;
if (playerDeathTimer <= 0)
{
if (LastCheckpoint > 0)
{
Player.Position = ListOfCheckpoints[LastCheckpoint - 1];
Player.MainHP = Player.MaxHP * 0.75f;
Player.isDead = false;
}
else
{
RegenerateMap();
Player.MainHP += gameTime.ElapsedGameTime.Seconds;
Player.MainHP = Player.MaxHP * 0.75f;
Player.isDead = false;
}
}
}
#endregion
if (myGame.CheckKey(Keys.Z))
{
Player.StatPoints += 500;
}
if (myGame.CheckKey(Keys.X))
{
Player.PExp += 500;
}
#region Update Enemy Stuff
for (int i = 0; i < EnemyList.Count; i++)
{
if (EnemyList[i].isDead)
{
HpDropList.Add(new HealthPickUp(HealthDropTexture, EnemyList[i].Position, myGame));
ExpDropList.Add(new ExpPickUp(ExpDropTexture, EnemyList[i].Position, myGame));
EnemyList.RemoveAt(i);
i--;
}
else
{
if (Camera.IsInView(EnemyList[i].Position, new Vector2(EnemyList[i].BoundingCollisions.Width, EnemyList[i].BoundingCollisions.Height)))
{
EnemyList[i].Update(gameTime);
}
if (EnemyList[i].IsHit)
{
ParticleSystem.CreateParticles(EnemyList[i].Position, ParticleTexture, Random, ParticleList, 230, 255, 0, 0, 0, 0, 5, 10, (int)BloodMinRadius, (int)BloodMaxRadius, 100, 250, 3, 5, 200, 255);
EnemyList[i].IsHit = false;
}
}
}
#endregion
#region Update Particle stuff
for (int i = 0; i < ParticleList.Count; i++)
{
if (ParticleList[i].DeleteMe)
{
ParticleList.RemoveAt(i);
i--;
}
else
{
ParticleList[i].Update(gameTime);
}
}
#endregion
#region Update Pickups
for (int i = 0; i < HpDropList.Count; i++)
{
if (HpDropList[i].DeleteMe)
{
HpDropList.RemoveAt(i);
Player.MainHP += 100000000000000000;
i--;
}
else
{
HpDropList[i].Update(gameTime);
}
}
for (int i = 0; i < ExpDropList.Count; i++)
{
if (ExpDropList[i].DeleteMe)
{
ExpDropList.RemoveAt(i);
Player.PExp += myGame.rng.Next(500, 1000);
i--;
}
else
{
ExpDropList[i].Update(gameTime);
}
}
#endregion
#region Update Checkpoints
foreach (PlaceableObject po in PlaceableObjectsList)
{
if (po is CheckPoint)
{
po.Update(gameTime);
}
}
#endregion
}
#endregion
#region Debug Stuff
if (myGame.IsGameDebug && LevelLoaded)
{
DebugTable debugTable = new DebugTable();
string[,] rawTable = {
{ "Player", "Tings", "Stats" },
{ "Enemy[0]", "Tings", "" },
{ "CheckPoint", "Tings", "Stuff" }
};
debugTable.initalizeTable(rawTable);
myGame.debugStrings[0] = debugTable.ReturnStringSegment(0, 0) + "Level=" + CurrentLevel;
myGame.debugStrings[1] = debugTable.ReturnStringSegment(0, 1) + "Postition=(" + Player.Position.X + "," + Player.Position.Y + ") Velocity=(" + Player.Velocity.X + "," + Player.Velocity.Y + ") IsInWater=" + Player.IsInWater;
myGame.debugStrings[2] = debugTable.ReturnStringSegment(0, 2) + "Agility=" + Player.PAgility + " Strength=" + Player.PStrength + " Defense=" + Player.PDefense + " StatPoints=" + Player.StatPoints + "Stat Level=" + Player.Lvl;
myGame.debugStrings[3] = debugTable.ReturnStringSegment(2, 0);
myGame.debugStrings[4] = debugTable.ReturnStringSegment(2, 1) + "Position[0]=(" + ListOfCheckpoints[0].X + "," + ListOfCheckpoints[0].Y + ") Position[1]=(" + ListOfCheckpoints[1].X + "," + ListOfCheckpoints[1].Y + ")";
myGame.debugStrings[5] = debugTable.ReturnStringSegment(2, 2) + "CurrentCheckPoint=" + LastCheckpoint + " CheckPointIndex[0]=" + (PlaceableObjectsList[0] as CheckPoint).CheckpointIndex + " CheckPointIndex[1]=" + (PlaceableObjectsList[1] as CheckPoint).CheckpointIndex + " Index=" + checkpointNum;
if (LastCheckpoint > 0)
{
myGame.debugStrings[5] = debugTable.ReturnStringSegment(2, 2) + "Cords=(" + ListOfCheckpoints[LastCheckpoint - 1].X + "," + ListOfCheckpoints[LastCheckpoint - 1].Y + ")";
}
}
#endregion
base.Update(gameTime);
}
/// <summary>
/// Draws the content of the game manager.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public override void Draw(GameTime gameTime)
{
spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.LinearWrap, null, null);
{
if (CurrentLevel == 1)
{
SewerBackgroundParallax.Draw(gameTime, spriteBatch);
SewerBackgroundSprayParallax.Draw(gameTime, spriteBatch);
}
if (CurrentLevel == 2)
{
SewerBackgroundParallax.Draw(gameTime, spriteBatch);
SewerBackgroundSprayParallax.Draw(gameTime, spriteBatch);
}
if (CurrentLevel == 3)
{
CitySkyBackgroundParallax.Draw(gameTime, spriteBatch);
CityBuildingBackgroundParallax.Draw(gameTime, spriteBatch);
CityFogBackgroundParallax.Draw(gameTime, spriteBatch);
}
if (CurrentLevel == 4)
{
CitySkyBackgroundParallax.Draw(gameTime, spriteBatch);
CityBuildingBackgroundParallax.Draw(gameTime, spriteBatch);
CityFogBackgroundParallax.Draw(gameTime, spriteBatch);
}
if (CurrentLevel == 5)
{
CitySkyBackgroundParallax.Draw(gameTime, spriteBatch);
CityBuildingBackgroundParallax.Draw(gameTime, spriteBatch);
CityFogBackgroundParallax.Draw(gameTime, spriteBatch);
}
if (CurrentLevel == 6)
{
HQBackgroundParallax.Draw(gameTime, spriteBatch);
HQForegroundParallax.Draw(gameTime, spriteBatch);
}
if (CurrentLevel == 7)
{
HQBackgroundParallax.Draw(gameTime, spriteBatch);
HQForegroundParallax.Draw(gameTime, spriteBatch);
}
}
spriteBatch.End();
spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, Camera.GetTransformation());
{
foreach (PlaceableObject po in PlaceableObjectsList)
{
po.Draw(gameTime, spriteBatch);
}
foreach (HealthPickUp h in HpDropList)
{
h.Draw(gameTime, spriteBatch);
}
foreach (ExpPickUp e in ExpDropList)
{
e.Draw(gameTime, spriteBatch);
}
foreach (Enemy e in EnemyList)
{
e.Draw(gameTime, spriteBatch);
}
Player.Draw(gameTime, spriteBatch);
foreach (Tile t in TilesList)
{
if (Camera.IsInView(t.Position, new Vector2(35, 35)))
{
t.Draw(gameTime, spriteBatch);
}
}
spriteBatch.Draw(HealthOverheadBackgroundTexture, new Vector2(Player.Position.X - ((50 - 35) / 2), Player.Position.Y - 12), Color.White);
OverheadHealthBar.Draw(gameTime, spriteBatch);
foreach (Particle p in ParticleList)
{
p.Draw(gameTime, spriteBatch);
}
}
spriteBatch.End();
spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.LinearClamp, null, null);
{
spriteBatch.Draw(HealthBackgroundTexture, new Vector2(15, 15), Color.White);
HealthBar.Draw(gameTime, spriteBatch);
if (Transistioning)
{
if (alpha > 0)
{
spriteBatch.Draw(LineTexture, new Rectangle(0, 0, (int)Camera.viewportSize.X, (int)Camera.viewportSize.Y), new Color(0, 0, 0, alpha / 255));
alpha -= 5f;
}
if (alpha <= 0)
{
alpha = 255;
Transistioning = false;
}
}
if (myGame.IsGameDebug)
{
myGame.debugLabel.Draw(gameTime, spriteBatch);
}
}
spriteBatch.End();
#region Debug Stuff
spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.PointWrap, null, null, null, Camera.GetTransformation());
{
if (myGame.IsGameDebug && LevelLoaded)
{
foreach (Rectangle r in MapBoundries)
{
spriteBatch.Draw(LineTexture, new Rectangle(r.X, r.Y, r.Width, 1), Color.White);
spriteBatch.Draw(LineTexture, new Rectangle(r.Right - 1, r.Y, 1, r.Height), Color.White);
spriteBatch.Draw(LineTexture, new Rectangle(r.X, r.Bottom - 1, r.Width, 1), Color.White);
spriteBatch.Draw(LineTexture, new Rectangle(r.X, r.Y, 1, r.Height), Color.White);
}
foreach (PlaceableObject po in PlaceableObjectsList)
{
Sprite.DrawBoundingCollisions(LineTexture, po.BoundingCollisions, Color.Red, spriteBatch);
}
foreach (Enemy e in EnemyList)
{
Sprite.DrawBoundingCollisions(LineTexture, e.BoundingCollisions, Color.Magenta, spriteBatch);
}
Sprite.DrawBoundingCollisions(LineTexture, Player.DebugBlock, Color.Lime, spriteBatch);
Sprite.DrawBoundingCollisions(LineTexture, Player.BoundingCollisions, Color.Blue, spriteBatch);
}
}
spriteBatch.End();
#endregion
if (myGame.OptionsChanged > myGame.OldOptionsChanged)
{
Camera.viewportSize = new Vector2(myGame.WindowSize.X, myGame.WindowSize.Y);
}
base.Draw(gameTime);
}
/// <summary>
/// Regenerates the map
/// * Be sure to set level before this and set "LevelLoaded" to false *
/// </summary>
public void RegenerateMap()
{
TilesList.RemoveRange(0, TilesList.Count);
EnemyList.RemoveRange(0, EnemyList.Count);
PlaceableObjectsList.RemoveRange(0, PlaceableObjectsList.Count);
Player.Position = Vector2.Zero;
SpawnTiles(CurrentLevel);
MapBoundries[0] = new Rectangle(-35, -105, 35, Camera.Size.Y + 70);
MapBoundries[1] = new Rectangle(Camera.Size.X, -105, 35, Camera.Size.Y + 70);
MapBoundries[2] = new Rectangle(-35, -105, Camera.Size.X + 70, 35);
MapBoundries[3] = new Rectangle(-35, Camera.Size.Y, Camera.Size.X + 70, 35);
MapBoundries[4] = new Rectangle(Camera.Size.X, Camera.Size.Y, 105, 35);
LevelLoaded = true;
}
/// <summary>
/// Spawns the tiles in the world
/// </summary>
/// <param name="level">The level to spawn.</param>
public void SpawnTiles(int level)
{
Point Size = new Point();
int[,] tiles = new int[0, 0];
switch (level)
{
case 0:
tiles = MapHelper.ImgToLevel(TestLevelTextureMap);
Size = new Point(tiles.GetLength(0), tiles.GetLength(1));
break;
case 1:
tiles = MapHelper.ImgToLevel(Sewer1TextureMap);
Size = new Point(tiles.GetLength(0), tiles.GetLength(1));
break;
case 2:
tiles = MapHelper.ImgToLevel(Sewer2TextureMap);
Size = new Point(tiles.GetLength(0), tiles.GetLength(1));
break;
case 3:
tiles = MapHelper.ImgToLevel(City1TextureMap);
Size = new Point(tiles.GetLength(0), tiles.GetLength(1));
break;
case 4:
tiles = MapHelper.ImgToLevel(City2TextureMap);
Size = new Point(tiles.GetLength(0), tiles.GetLength(1));
break;
case 5:
tiles = MapHelper.ImgToLevel(BridgeTextureMap);
Size = new Point(tiles.GetLength(0), tiles.GetLength(1));
break;
case 6:
tiles = MapHelper.ImgToLevel(HQ1TextureMap);
Size = new Point(tiles.GetLength(0), tiles.GetLength(1));
break;
case 7:
break;
}
Camera.Size = new Point(Size.X * 35, Size.Y * 35);
for (int x = 0; x < Size.X; x++)
{
for (int y = 0; y < Size.Y; y++)
{
if (tiles[x, y] == 77)
{
Player.Position = new Vector2(x * 35, y * 35);
}
else if (tiles[x, y] == 78)
{
Enemy tempEnemy1 = new Enemy(SpitterAnimationSet, "IDLE", new Vector2(x * 35, y * 35), Enemy.EnemyTypes.ROLLER, new Color(myGame.gameManager.Random.Next(0, 255), myGame.gameManager.Random.Next(0, 255), myGame.gameManager.Random.Next(0, 255)), myGame);
tempEnemy1.Scale = 0.5f;
int width = (int)(tempEnemy1.CurrentAnimation.frameSize.X * tempEnemy1.Scale);
int left = (int)(tempEnemy1.CurrentAnimation.frameSize.X * tempEnemy1.Scale - width);
int height = (int)(tempEnemy1.CurrentAnimation.frameSize.Y * tempEnemy1.Scale);
int top = (int)(tempEnemy1.CurrentAnimation.frameSize.Y * tempEnemy1.Scale - height);
tempEnemy1.Inbounds = new Rectangle(left, top, width, height);
EnemyList.Add(tempEnemy1);
}
else if (tiles[x, y] == 79)
{
Enemy tempEnemy2 = new Enemy(SpitterAnimationSet, "IDLE", new Vector2(x * 35, y * 35), Enemy.EnemyTypes.SPITTER, new Color(myGame.gameManager.Random.Next(0, 255), myGame.gameManager.Random.Next(0, 255), myGame.gameManager.Random.Next(0, 255)), myGame);
tempEnemy2.Scale = 0.4f;
int width = (int)(tempEnemy2.CurrentAnimation.frameSize.X * tempEnemy2.Scale);
int left = (int)(tempEnemy2.CurrentAnimation.frameSize.X * tempEnemy2.Scale - width);
int height = (int)(tempEnemy2.CurrentAnimation.frameSize.Y * tempEnemy2.Scale);
int top = (int)(tempEnemy2.CurrentAnimation.frameSize.Y * tempEnemy2.Scale - height);
tempEnemy2.Inbounds = new Rectangle(left, top, width, height);
EnemyList.Add(tempEnemy2);
}
else if (tiles[x, y] == 80)
{
Enemy tempEnemy3 = new Enemy(SpitterAnimationSet, "IDLE", new Vector2(x * 35, y * 35), Enemy.EnemyTypes.JUMPER, new Color(myGame.gameManager.Random.Next(0, 255), myGame.gameManager.Random.Next(0, 255), myGame.gameManager.Random.Next(0, 255)), myGame);
tempEnemy3.Scale = 0.5f;
int width = (int)(tempEnemy3.CurrentAnimation.frameSize.X * tempEnemy3.Scale);
int left = (int)(tempEnemy3.CurrentAnimation.frameSize.X * tempEnemy3.Scale - width);
int height = (int)(tempEnemy3.CurrentAnimation.frameSize.Y * tempEnemy3.Scale);
int top = (int)(tempEnemy3.CurrentAnimation.frameSize.Y * tempEnemy3.Scale - height);
tempEnemy3.Inbounds = new Rectangle(left, top, width, height);
EnemyList.Add(tempEnemy3);
}
else if (tiles[x, y] == 81)
{
Enemy tempEnemy4 = new Enemy(CrawlerAnimationSet, "IDLE", new Vector2(x * 35, y * 35), Enemy.EnemyTypes.CHARGER, new Color(myGame.gameManager.Random.Next(0, 255), myGame.gameManager.Random.Next(0, 255), myGame.gameManager.Random.Next(0, 255)), myGame);
tempEnemy4.Scale = 0.5f;
int width = (int)(tempEnemy4.CurrentAnimation.frameSize.X * tempEnemy4.Scale);
int left = (int)(tempEnemy4.CurrentAnimation.frameSize.X * tempEnemy4.Scale - width);
int height = (int)(tempEnemy4.CurrentAnimation.frameSize.Y * tempEnemy4.Scale);
int top = (int)(tempEnemy4.CurrentAnimation.frameSize.Y * tempEnemy4.Scale - height);
tempEnemy4.Inbounds = new Rectangle(left, top, width, height);
EnemyList.Add(tempEnemy4);
}
else if (tiles[x, y] == 82)
{
Enemy tempEnemy5 = new Enemy(CrawlerAnimationSet, "IDLE", new Vector2(x * 35, y * 35), Enemy.EnemyTypes.BOSS, new Color(myGame.gameManager.Random.Next(0, 255), myGame.gameManager.Random.Next(0, 255), myGame.gameManager.Random.Next(0, 255)), myGame);
tempEnemy5.Scale = 0.7f;
int width = (int)(tempEnemy5.CurrentAnimation.frameSize.X * tempEnemy5.Scale);
int left = (int)(tempEnemy5.CurrentAnimation.frameSize.X * tempEnemy5.Scale - width);
int height = (int)(tempEnemy5.CurrentAnimation.frameSize.Y * tempEnemy5.Scale);
int top = (int)(tempEnemy5.CurrentAnimation.frameSize.Y * tempEnemy5.Scale - height);
tempEnemy5.Inbounds = new Rectangle(left, top, width, height);
EnemyList.Add(tempEnemy5);
}
if (tiles[x, y] == 25)
{
CheckPoint tempCheckPoint = new CheckPoint(CheckpointTexture, new Vector2(x * 35, y * 35), Color.White, checkpointNum, myGame);
PlaceableObjectsList.Add(tempCheckPoint);
ListOfCheckpoints[checkpointNum - 1] = new Vector2(x * 35, y * 35);
checkpointNum += 1;
}
if (tiles[x, y] > 25)
{
tiles[x, y] = 0;
}
if (tiles[x, y] == 1)
{
TilesList.Add(new Tile(SewerTileTexture, new Vector2(x * 35, y * 35), Tile.TileCollisions.Impassable, TilesList, 1, Color.White));
TilesList.Add(new Tile(ShadowTileTexture, new Vector2(x * 35, y * 35), Tile.TileCollisions.Impassable, TilesList, 1, Color.White));
}
if (tiles[x, y] == 2)
{
TilesList.Add(new Tile(WaterTileTexture, new Vector2(x * 35, y * 35), Tile.TileCollisions.Water, 1, 2, Color.White));
}
if (tiles[x, y] == 3)
{
TilesList.Add(new Tile(ConcreteTileTexture, new Vector2(x * 35, y * 35), Tile.TileCollisions.Impassable, TilesList, 3, Color.White));
TilesList.Add(new Tile(ShadowTileTexture, new Vector2(x * 35, y * 35), Tile.TileCollisions.Impassable, TilesList, 3, Color.White));
}
if (tiles[x, y] == 4)
{
TilesList.Add(new Tile(LadderTileTexture, new Vector2(x * 35, y * 35), Tile.TileCollisions.Passable, 1, 4, Color.White));
}
}
}
foreach (Tile t in TilesList)
{
t.UpdateConnections();
}
Camera.Position = Player.Position;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Chatbot4.Events;
using DamageBot.Events.Chat;
using DamageBot.Users;
using Newtonsoft.Json;
namespace Chatbot4.Ai {
/// <summary>
/// Contains all the raw response nodes.
/// Generates from them prepared response nodes and ticker nodes.
/// </summary>
public class ResponsePool {
private Dictionary<Mood, Dictionary<ResponseContext, List<RawResponseNode>>> loadedResponses;
private readonly Random random;
public ResponsePool(ChatbotConfig cfg) {
var rawResponseList = JsonConvert.DeserializeObject<List<RawResponseNode>>(File.ReadAllText("chatter.json"));
PrepareResponseStructure();
this.random = new Random();
foreach (var node in rawResponseList) {
// replace bot name placeholder with a list of all botnames
if (node.PrimaryWordPool != null) {
if (node.PrimaryWordPool.Any((e) => Regex.IsMatch(e, "({BOT_NAME})"))) {
node.PrimaryWordPool.Remove("{BOT_NAME}");
node.PrimaryWordPool.AddRange(cfg.BotNicks);
}
}
if (node.SecondaryWordPool != null) {
if (node.SecondaryWordPool.Any((e) => Regex.IsMatch(e, "({BOT_NAME})"))) {
node.SecondaryWordPool.Remove("{BOT_NAME}");
node.SecondaryWordPool.AddRange(cfg.BotNicks);
}
}
loadedResponses[node.ResponseMood][node.Context].Add(node);
}
}
/// <summary>
/// Find a random node for the given mood or a normal mood and given context, if none is found in the ideal mood list
/// </summary>
/// <param name="idealMood"></param>
/// <param name="context"></param>
/// <param name="user"></param>
/// <returns></returns>
public ResponseInfo FindRandomNodeForContextAndMood(Mood idealMood, ResponseContext context, IUser user) {
var idealNodes = this.loadedResponses[idealMood][context];
var defaultNodes = this.loadedResponses[Mood.Normal][context];
if (idealNodes.Count > 0) {
var node = idealNodes[random.Next(0, idealNodes.Count - 1)];
var replacer = new ReplacePlaceholdersEvent(GetRandomAnswer(node.Answers));
replacer.Call();
return new ResponseInfo(user != null ? replacer.Text.Replace("{CURRENT_USER}", user.Name) : replacer.Text, node.ResponseProbability, node.RespondTime);
}
if (defaultNodes.Count > 0) {
var node = defaultNodes[random.Next(0, idealNodes.Count - 1)];
var replacer = new ReplacePlaceholdersEvent(GetRandomAnswer(node.Answers));
replacer.Call();
return new ResponseInfo(user != null ? replacer.Text.Replace("{CURRENT_USER}", user.Name) : replacer.Text, node.ResponseProbability, node.RespondTime);
}
return null;
}
public ResponseInfo GetTickerNode() {
var nodes = this.loadedResponses[Mood.Normal][ResponseContext.Ticker];
if (nodes.Count > 0) {
var node = nodes[random.Next(0, nodes.Count - 1)];
var replacer = new ReplacePlaceholdersEvent(GetRandomAnswer(node.Answers));
replacer.Call();
return new ResponseInfo(replacer.Text, node.ResponseProbability, node.RespondTime);
}
return null;
}
/// <summary>
/// Find a node with response information for the given message.
/// </summary>
/// <param name="idealMood">The ideal response mood.</param>
/// <param name="context">The context of the given message</param>
/// <param name="allowIgnorePrimary">Set true to skip primary word checks on nodes that allow skipping these checks. (CanIgnorePrimary)</param>
/// <param name="userMessage">the message to find a response for</param>
/// <param name="user"></param>
/// <returns></returns>
public ResponseInfo FindNode(Mood idealMood, ResponseContext context, bool allowIgnorePrimary, string userMessage, IUser user) {
if (context != ResponseContext.Chat) {
return FindRandomNodeForContextAndMood(idealMood, context, user);
}
var idealNodes = this.loadedResponses[idealMood][context];
var defaultNodes = this.loadedResponses[Mood.Normal][context];
foreach (var node in idealNodes) {
if ((node.CanIgnorePrimary && allowIgnorePrimary) || node.RequiredPrimaryMatches <= this.CountMatches(userMessage, node.PrimaryWordPool)) {
if (node.RequiredSecondaryMatches <= this.CountMatches(userMessage, node.SecondaryWordPool)) {
var replacer = new ReplacePlaceholdersEvent(GetRandomAnswer(node.Answers));
replacer.Call();
return new ResponseInfo(replacer.Text.Replace("{CURRENT_USER}", user.Name), node.ResponseProbability, node.RespondTime);
}
}
}
foreach (var node in defaultNodes) {
if ((node.CanIgnorePrimary && allowIgnorePrimary) || node.RequiredPrimaryMatches <= this.CountMatches(userMessage, node.PrimaryWordPool)) {
if (node.RequiredSecondaryMatches <= this.CountMatches(userMessage, node.SecondaryWordPool)) {
var replacer = new ReplacePlaceholdersEvent(GetRandomAnswer(node.Answers));
replacer.Call();
return new ResponseInfo(replacer.Text.Replace("{CURRENT_USER}", user.Name), node.ResponseProbability, node.RespondTime);
}
}
}
return null;
}
private int CountMatches(string msg, List<string> wordMatchList) {
for (int i = 0; i < wordMatchList.Count; ++i) {
wordMatchList[i] = $"({wordMatchList[i]})";
}
var matches = Regex.Matches(msg, string.Join("|", wordMatchList), RegexOptions.IgnoreCase | RegexOptions.Multiline);
return matches.Count;
}
private string GetRandomAnswer(List<string> answers) {
return answers[random.Next(0, answers.Count - 1)];
}
private void PrepareResponseStructure() {
this.loadedResponses = new Dictionary<Mood, Dictionary<ResponseContext, List<RawResponseNode>>>();
var badDictionary = new Dictionary<ResponseContext, List<RawResponseNode>> {
{
ResponseContext.Join, new List<RawResponseNode>()
},
{
ResponseContext.Part, new List<RawResponseNode>()
},
{
ResponseContext.Timeout, new List<RawResponseNode>()
},
{
ResponseContext.Ban, new List<RawResponseNode>()
},
{
ResponseContext.Chat, new List<RawResponseNode>()
},
{
ResponseContext.Ticker, new List<RawResponseNode>()
}
};
this.loadedResponses.Add(Mood.Bad, badDictionary);
var normalDict = new Dictionary<ResponseContext, List<RawResponseNode>> {
{
ResponseContext.Join, new List<RawResponseNode>()
},
{
ResponseContext.Part, new List<RawResponseNode>()
},
{
ResponseContext.Timeout, new List<RawResponseNode>()
},
{
ResponseContext.Ban, new List<RawResponseNode>()
},
{
ResponseContext.Chat, new List<RawResponseNode>()
},
{
ResponseContext.Ticker, new List<RawResponseNode>()
}
};
this.loadedResponses.Add(Mood.Normal, normalDict);
var goodDict = new Dictionary<ResponseContext, List<RawResponseNode>> {
{
ResponseContext.Join, new List<RawResponseNode>()
},
{
ResponseContext.Part, new List<RawResponseNode>()
},
{
ResponseContext.Timeout, new List<RawResponseNode>()
},
{
ResponseContext.Ban, new List<RawResponseNode>()
},
{
ResponseContext.Chat, new List<RawResponseNode>()
},
{
ResponseContext.Ticker, new List<RawResponseNode>()
}
};
this.loadedResponses.Add(Mood.Good, goodDict);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using FizzWare.NBuilder;
using Moq;
using NUnit.Framework;
using ReMi.BusinessEntities.ReleasePlan;
using ReMi.Common.Utils.Repository;
using ReMi.TestUtils.UnitTests;
using ReMi.DataAccess.BusinessEntityGateways.ReleasePlan;
using ReMi.DataAccess.Exceptions;
using ReMi.DataEntities.Products;
using ReMi.DataEntities.ReleaseCalendar;
using ReMi.DataEntities.ReleasePlan;
using BusinessCheckListQuestion = ReMi.BusinessEntities.ReleasePlan.CheckListQuestion;
using CheckListQuestion = ReMi.DataEntities.ReleasePlan.CheckListQuestion;
namespace ReMi.DataAccess.Tests.ReleasePlan
{
public class CheckListGatewayTests : TestClassFor<CheckListGateway>
{
private Mock<IRepository<CheckListQuestion>> _checkListQuestionRepositoryMock;
private Mock<IRepository<CheckListQuestionToProduct>> _checkListQuestionToProductRepositoryMock;
private Mock<IRepository<CheckList>> _checkListRepositoryMock;
private Mock<IRepository<ReleaseWindow>> _releaseWindowRepositoryMock;
protected override CheckListGateway ConstructSystemUnderTest()
{
return new CheckListGateway
{
CheckListQuestionRepository = _checkListQuestionRepositoryMock.Object,
CheckListQuestionToProductRepository = _checkListQuestionToProductRepositoryMock.Object,
CheckListRepository = _checkListRepositoryMock.Object,
ReleaseWindowRepository = _releaseWindowRepositoryMock.Object
};
}
protected override void TestInitialize()
{
_checkListQuestionRepositoryMock = new Mock<IRepository<CheckListQuestion>>(MockBehavior.Strict);
_checkListQuestionToProductRepositoryMock = new Mock<IRepository<CheckListQuestionToProduct>>(MockBehavior.Strict);
_checkListRepositoryMock = new Mock<IRepository<CheckList>>(MockBehavior.Strict);
_releaseWindowRepositoryMock = new Mock<IRepository<ReleaseWindow>>(MockBehavior.Strict);
base.TestInitialize();
}
[Test]
public void Dispose_ShouldDisposeAllRepositories_WhenInvoked()
{
_checkListQuestionRepositoryMock.Setup(x => x.Dispose());
_checkListQuestionToProductRepositoryMock.Setup(x => x.Dispose());
_checkListRepositoryMock.Setup(x => x.Dispose());
_releaseWindowRepositoryMock.Setup(x => x.Dispose());
Sut.Dispose();
_checkListQuestionRepositoryMock.Verify(x => x.Dispose(), Times.Once);
_checkListQuestionToProductRepositoryMock.Verify(x => x.Dispose(), Times.Once);
_checkListRepositoryMock.Verify(x => x.Dispose(), Times.Once);
_releaseWindowRepositoryMock.Verify(x => x.Dispose(), Times.Once);
}
[Test]
public void GetCheckList_ShouldReturnNull_WhenReleaseWindowWasNotFound()
{
_releaseWindowRepositoryMock.SetupEntities(new List<ReleaseWindow>
{
new ReleaseWindow {ExternalId = Guid.NewGuid()}
});
var result = Sut.GetCheckList(Guid.NewGuid());
Assert.IsNull(result);
}
[Test]
public void GetCheckList_ShouldReturnCheckList_WhenReleaseWindowWasFound()
{
var releaseWindowId = Guid.NewGuid();
var releaseWindow = new ReleaseWindow
{
ExternalId = releaseWindowId,
CheckList = new Collection<CheckList>
{
new CheckList
{
CheckListQuestion = new CheckListQuestion {Content = RandomData.RandomString(12)},
Comment = RandomData.RandomString(11),
ExternalId = Guid.NewGuid(),
ReleaseWindow = new ReleaseWindow {ExternalId = releaseWindowId}
}
}
};
_releaseWindowRepositoryMock.SetupEntities(new List<ReleaseWindow> { releaseWindow });
var result = Sut.GetCheckList(releaseWindowId).ToList();
Assert.IsNotNull(result, "Result is null");
Assert.AreEqual(1, result.Count, "Should return only one checklist");
Assert.IsFalse(result[0].Checked, "Checked");
Assert.AreEqual(releaseWindow.CheckList.ToList()[0].CheckListQuestion.Content, result[0].CheckListQuestion,
"CheckListQuestion");
Assert.AreEqual(releaseWindow.CheckList.ToList()[0].Comment, result[0].Comment, "Comment");
Assert.AreEqual(releaseWindowId, result[0].ReleaseWindowId, "ReleaseWindowId");
Assert.AreEqual(releaseWindow.CheckList.ToList()[0].ExternalId, result[0].ExternalId, "ExternalId");
}
[Test]
public void GetAdditionalQuestions_ShouldReturnCorrectResult()
{
var releaseWindowId = Guid.NewGuid();
var otherQuestion = new CheckListQuestion
{
Content = RandomData.RandomString(11),
ExternalId = Guid.NewGuid(),
CheckLists =
new List<CheckList>
{
new CheckList {ReleaseWindow = new ReleaseWindow {ExternalId = Guid.NewGuid()}}
}
};
_checkListQuestionRepositoryMock.SetupEntities(new List<CheckListQuestion> { otherQuestion });
var result = Sut.GetCheckListAdditionalQuestions(releaseWindowId);
Assert.IsNotNull(result, "Null");
Assert.AreEqual(1, result.Count, "result list size");
Assert.AreEqual(otherQuestion.Content, result[0].Question, "content");
Assert.AreEqual(otherQuestion.ExternalId, result[0].ExternalId, "ExternalId");
}
[Test]
public void GetAllQuestions_ShouldReturnCorrectResult()
{
var question = new CheckListQuestion { Content = RandomData.RandomString(11) };
var otherQuestion = new CheckListQuestion { Content = RandomData.RandomString(11) };
_checkListQuestionRepositoryMock.SetupEntities(new List<CheckListQuestion> { question, otherQuestion });
var result = Sut.GetCheckListQuestions();
Assert.IsNotNull(result, "Null");
Assert.AreEqual(2, result.Count, "result list size");
Assert.AreEqual(question.Content, result[0], "content");
Assert.AreEqual(otherQuestion.Content, result[1], "content");
}
[Test]
public void Create_ShouldInsertNewCheckListToRepository()
{
var productId = RandomData.RandomInt(int.MaxValue);
var product = RandomData.RandomString(5);
var releaseWindowId = Guid.NewGuid();
var releaseWindow = new ReleaseWindow
{
ExternalId = releaseWindowId,
ReleaseWindowId = RandomData.RandomInt(231),
ReleaseProducts = new[] { new ReleaseProduct
{
Product = Builder<Product>.CreateNew()
.With(x => x.Description = product)
.With(x => x.ExternalId = Guid.NewGuid())
.With(x => x.ProductId= productId)
.Build()
} }
};
_releaseWindowRepositoryMock.SetupEntities(new List<ReleaseWindow> { releaseWindow });
var question = new CheckListQuestion
{
CheckListQuestionId = RandomData.RandomInt(453),
Content = RandomData.RandomString(23)
};
var otherQuestion = new CheckListQuestion
{
CheckListQuestionId = RandomData.RandomInt(453),
Content = RandomData.RandomString(23)
};
_checkListQuestionRepositoryMock.SetupEntities(new List<CheckListQuestion> { question, otherQuestion });
_checkListQuestionToProductRepositoryMock.SetupEntities(new List<CheckListQuestionToProduct>
{
new CheckListQuestionToProduct
{
CheckListQuestionId = question.CheckListQuestionId,
ProductId = productId,
Product = Builder<Product>.CreateNew().With(x => x.Description = product)
.With(x => x.ExternalId = Guid.NewGuid())
.Build()
},
new CheckListQuestionToProduct
{
CheckListQuestionId = otherQuestion.CheckListQuestionId,
Product = Builder<Product>.CreateNew().With(x => x.Description = RandomData.RandomString(5))
.With(x => x.ExternalId = Guid.NewGuid())
.Build()
}
});
_checkListRepositoryMock.Setup(
ch => ch.Insert(It.Is<CheckList>(c =>
c.ReleaseWindowId == releaseWindow.ReleaseWindowId &&
c.CheckListQuestionId == question.CheckListQuestionId)));
Sut.Create(releaseWindowId);
_checkListRepositoryMock.Verify(ch => ch.Insert(It.IsAny<CheckList>()), Times.Once);
}
[Test]
public void UpdateAnswer_ShouldUpdateTheAnswerCorrectly()
{
var checkList = new CheckList { ExternalId = Guid.NewGuid() };
var updatedCheckList = new CheckListItem
{
ExternalId = checkList.ExternalId,
Checked = true,
LastChangedBy = RandomData.RandomString(32)
};
_checkListRepositoryMock.SetupEntities(new List<CheckList> { checkList });
_checkListRepositoryMock.Setup(c => c.Update(It.Is<CheckList>(ch =>
ch.Checked == updatedCheckList.Checked
&& ch.ExternalId == checkList.ExternalId
&& ch.LastChangedBy == updatedCheckList.LastChangedBy)))
.Returns((ChangedFields<CheckList>)null);
Sut.UpdateAnswer(updatedCheckList);
_checkListRepositoryMock.Verify(c => c.Update(It.IsAny<CheckList>()), Times.Once);
}
[Test]
public void UpdateComment_ShouldUpdateTheAnswerCorrectly()
{
var checkList = new CheckList { ExternalId = Guid.NewGuid() };
var updatedCheckList = new CheckListItem
{
ExternalId = checkList.ExternalId,
Comment = RandomData.RandomString(34),
LastChangedBy = RandomData.RandomString(32)
};
_checkListRepositoryMock.SetupEntities(new List<CheckList> { checkList });
_checkListRepositoryMock.Setup(c => c.Update(It.Is<CheckList>(ch =>
ch.Comment == updatedCheckList.Comment
&& ch.ExternalId == checkList.ExternalId
&& ch.LastChangedBy == updatedCheckList.LastChangedBy)))
.Returns((ChangedFields<CheckList>)null);
Sut.UpdateComment(updatedCheckList);
_checkListRepositoryMock.Verify(c => c.Update(It.IsAny<CheckList>()), Times.Once);
}
[Test]
public void GetCheckListItem_ShouldReturnCorrectValue()
{
var checkList = new CheckList
{
ExternalId = Guid.NewGuid(),
Comment = RandomData.RandomString(89),
CheckListQuestion = new CheckListQuestion { Content = RandomData.RandomString(56, 99) },
Checked = RandomData.RandomBool(),
LastChangedBy = RandomData.RandomString(22, 44),
ReleaseWindow = new ReleaseWindow { ExternalId = Guid.NewGuid() }
};
_checkListRepositoryMock.SetupEntities(new List<CheckList>
{
checkList,
new CheckList
{
ReleaseWindow = new ReleaseWindow {ExternalId = Guid.NewGuid()},
ExternalId = Guid.NewGuid()
}
});
var result = Sut.GetCheckListItem(checkList.ExternalId);
Assert.AreEqual(checkList.ReleaseWindow.ExternalId, result.ReleaseWindowId, "Release window external id");
Assert.AreEqual(checkList.ExternalId, result.ExternalId, "check list external id");
Assert.AreEqual(checkList.Comment, result.Comment, "comment");
Assert.AreEqual(checkList.Checked, result.Checked, "checked");
Assert.AreEqual(checkList.LastChangedBy, result.LastChangedBy, "last changed by");
Assert.AreEqual(checkList.CheckListQuestion.Content, result.CheckListQuestion, "question");
}
[Test]
public void AddCheckListQuestions_ShouldDoNothing_WhenQuestionListIsEmptyOrNull()
{
Sut.AddCheckListQuestions(null, Guid.NewGuid());
Sut.AddCheckListQuestions(Enumerable.Empty<BusinessCheckListQuestion>(), Guid.NewGuid());
_checkListQuestionRepositoryMock.Verify(x => x.Insert(It.IsAny<IEnumerable<CheckListQuestion>>()), Times.Never);
}
[Test]
public void AddCheckListQuestions_ShouldInsertNewQuestions_WhenInvoked()
{
var questions = Builder<BusinessCheckListQuestion>.CreateListOfSize(5).Build();
var releaseWindow = Builder<ReleaseWindow>.CreateNew()
.With(x => x.ReleaseProducts,Enumerable.Empty<ReleaseProduct>())
.Build();
_checkListQuestionRepositoryMock.Setup(x => x.Insert(It.Is<IEnumerable<CheckListQuestion>>(c =>
c.Count() == 5
&& c.All(dq => questions.Any(bq => bq.ExternalId == dq.ExternalId))
&& c.All(dq => questions.Any(bq => bq.Question == dq.Content)))));
_releaseWindowRepositoryMock.SetupEntities(new[] { releaseWindow });
_checkListQuestionRepositoryMock.SetupEntities(Enumerable.Empty<CheckListQuestion>());
_checkListQuestionToProductRepositoryMock.Setup(x => x.Insert(It.IsAny<IEnumerable<CheckListQuestionToProduct>>()));
_checkListRepositoryMock.Setup(x => x.Insert(It.IsAny<IEnumerable<CheckList>>()));
Sut.AddCheckListQuestions(questions, releaseWindow.ExternalId);
_checkListQuestionRepositoryMock.Verify(x => x.Insert(It.IsAny<IEnumerable<CheckListQuestion>>()), Times.Once);
}
[Test]
public void AssociateCheckListQuestionWithPackage_ShouldDoNothing_WhenQuestionListIsEmptyOrNull()
{
Sut.AssociateCheckListQuestionWithPackage(null, Guid.NewGuid());
Sut.AssociateCheckListQuestionWithPackage(Enumerable.Empty<BusinessCheckListQuestion>(), Guid.NewGuid());
_checkListQuestionToProductRepositoryMock.Verify(x => x.Insert(It.IsAny<IEnumerable<CheckListQuestionToProduct>>()), Times.Never);
}
[Test]
public void AssociateCheckListQuestionWithPackage_ShouldThrowEntityNotFoundException_WhenReleaseWindowNotFound()
{
var questions = Builder<BusinessCheckListQuestion>.CreateListOfSize(5).Build();
var releaseWindow = Builder<ReleaseWindow>.CreateNew().Build();
_releaseWindowRepositoryMock.SetupEntities(Enumerable.Empty<ReleaseWindow>());
var ex = Assert.Throws<EntityNotFoundException>(() => Sut.AssociateCheckListQuestionWithPackage(questions, releaseWindow.ExternalId));
Assert.IsTrue(ex.Message.Contains(releaseWindow.ExternalId.ToString()), "Exception message should contain reference id");
_checkListQuestionToProductRepositoryMock.Verify(x => x.Insert(It.IsAny<IEnumerable<CheckListQuestionToProduct>>()), Times.Never);
}
[Test]
public void AssociateCheckListQuestionWithPackage_ShouldAssociateAllQuestionsWithReleaseWindowPackages_WhenQuestionsAreNotYetAssociated()
{
var dataQuestions = Builder<CheckListQuestion>.CreateListOfSize(5).Build();
var releaseWindow = Builder<ReleaseWindow>.CreateNew()
.With(x => x.ReleaseProducts, Builder<ReleaseProduct>.CreateListOfSize(2).Build())
.With(x => x.CheckList, Enumerable.Empty<CheckList>())
.Build();
var questions = dataQuestions.Select(x => new BusinessCheckListQuestion
{
ExternalId = x.ExternalId,
Question = x.Content,
CheckListId = Guid.NewGuid()
}).ToArray();
_releaseWindowRepositoryMock.SetupEntities(new[] { releaseWindow });
_checkListQuestionRepositoryMock.SetupEntities(dataQuestions);
_checkListQuestionToProductRepositoryMock.SetupEntities(Enumerable.Empty<CheckListQuestionToProduct>());
_checkListQuestionToProductRepositoryMock.Setup(x => x.Insert(It.Is<IEnumerable<CheckListQuestionToProduct>>(c =>
c.Count() == 10
&& c.Count(z => z.CheckListQuestionId == dataQuestions.First().CheckListQuestionId) == 2
&& c.Count(z => z.ProductId == releaseWindow.ReleaseProducts.First().ProductId) == 5)));
_checkListRepositoryMock.Setup(x => x.Insert(It.Is<IEnumerable<CheckList>>(c =>
c.Count() == 5
&& c.Count(y => y.CheckListQuestionId == dataQuestions.First().CheckListQuestionId) == 1
&& c.Count(y => y.ExternalId == questions.First().CheckListId) == 1
&& c.Count(y => y.ReleaseWindowId == releaseWindow.ReleaseWindowId) == 5)));
Sut.AssociateCheckListQuestionWithPackage(questions, releaseWindow.ExternalId);
_checkListQuestionToProductRepositoryMock.Verify(x => x.Insert(It.IsAny<IEnumerable<CheckListQuestionToProduct>>()), Times.Once);
_checkListRepositoryMock.Verify(x => x.Insert(It.IsAny<IEnumerable<CheckList>>()), Times.Once);
}
[Test]
public void AssociateCheckListQuestionWithPackage_ShouldAssociateNotAllQuestionsWithReleaseWindowPackages_WhenSomeQuestionsAreAssociatedAlready()
{
var dataQuestions = Builder<CheckListQuestion>.CreateListOfSize(5).Build();
var releaseWindow = Builder<ReleaseWindow>.CreateNew()
.With(x => x.ReleaseProducts, Builder<ReleaseProduct>.CreateListOfSize(2).Build())
.Build();
var questions = dataQuestions.Select(x => new BusinessCheckListQuestion
{
ExternalId = x.ExternalId,
Question = x.Content,
CheckListId = Guid.NewGuid()
}).ToArray();
_releaseWindowRepositoryMock.SetupEntities(new[] { releaseWindow });
_checkListQuestionRepositoryMock.SetupEntities(dataQuestions);
_checkListQuestionToProductRepositoryMock.SetupEntities(new[]{ new CheckListQuestionToProduct
{
ProductId = releaseWindow.ReleaseProducts.First().ProductId,
CheckListQuestionId = dataQuestions.First().CheckListQuestionId
} });
releaseWindow.CheckList = new[]{new CheckList
{
ReleaseWindowId = releaseWindow.ReleaseWindowId,
CheckListQuestionId = dataQuestions.First().CheckListQuestionId
} };
_checkListQuestionToProductRepositoryMock.Setup(x => x.Insert(It.Is<IEnumerable<CheckListQuestionToProduct>>(c =>
c.Count() == 9
&& c.Count(z => z.CheckListQuestionId == dataQuestions.First().CheckListQuestionId) == 1
&& c.Count(z => z.ProductId == releaseWindow.ReleaseProducts.First().ProductId) == 4)));
_checkListRepositoryMock.Setup(x => x.Insert(It.Is<IEnumerable<CheckList>>(c =>
c.Count() == 4
&& c.Count(y => y.CheckListQuestionId == dataQuestions.First().CheckListQuestionId) == 0
&& c.Count(y => y.ExternalId == questions.First().CheckListId) == 0
&& c.Count(y => y.CheckListQuestionId == dataQuestions.ElementAt(1).CheckListQuestionId) == 1
&& c.Count(y => y.ExternalId == questions.ElementAt(1).CheckListId) == 1
&& c.Count(y => y.ReleaseWindowId == releaseWindow.ReleaseWindowId) == 4)));
Sut.AssociateCheckListQuestionWithPackage(questions, releaseWindow.ExternalId);
_checkListQuestionToProductRepositoryMock.Verify(x => x.Insert(It.IsAny<IEnumerable<CheckListQuestionToProduct>>()), Times.Once);
_checkListRepositoryMock.Verify(x => x.Insert(It.IsAny<IEnumerable<CheckList>>()), Times.Once);
}
[Test]
public void RemoveCheckListQuestion_ShouldThrowEntityNotFoundException_WhenCheckListItemNotFound()
{
var checkListId = Guid.NewGuid();
_checkListRepositoryMock.SetupEntities(Enumerable.Empty<CheckList>());
var ex = Assert.Throws<EntityNotFoundException>(() => Sut.RemoveCheckListQuestion(checkListId));
Assert.IsTrue(ex.Message.Contains(checkListId.ToString()), "Exception message should contain reference id");
_checkListRepositoryMock.Verify(x => x.Delete(It.IsAny<CheckList>()), Times.Never);
}
[Test]
public void RemoveCheckListQuestion_ShouldRemoveQuestionFromReleaseWindow_WhenInvoked()
{
var checkListItem = Builder<CheckList>.CreateNew().Build();
_checkListRepositoryMock.SetupEntities(new[] { checkListItem });
_checkListRepositoryMock.Setup(x => x.Delete(checkListItem));
Sut.RemoveCheckListQuestion(checkListItem.ExternalId);
_checkListRepositoryMock.Verify(x => x.Delete(It.IsAny<CheckList>()), Times.Once);
}
[Test]
public void RemoveCheckListQuestionForPackage_ShouldThrowEntityNotFoundException_WhenCheckListItemNotFound()
{
var checkListId = Guid.NewGuid();
_checkListRepositoryMock.SetupEntities(Enumerable.Empty<CheckList>());
var ex = Assert.Throws<EntityNotFoundException>(() => Sut.RemoveCheckListQuestionForPackage(checkListId));
Assert.IsTrue(ex.Message.Contains(checkListId.ToString()), "Exception message should contain reference id");
_checkListRepositoryMock.Verify(x => x.Delete(It.IsAny<CheckList>()), Times.Never);
}
[Test]
public void RemoveCheckListQuestionForPackage_ShouldRemoveQuestionFromPackageAndFromReleaseWindow_WhenInvoked()
{
var releaseWindow = Builder<ReleaseWindow>.CreateNew()
.With(x => x.ReleaseProducts, Builder<ReleaseProduct>.CreateListOfSize(2).Build())
.Build();
var checkListItem = Builder<CheckList>.CreateNew()
.With(x => x.ReleaseWindow = releaseWindow)
.With(x => x.CheckListQuestion, Builder<CheckListQuestion>.CreateNew()
.With(q => q.CheckListQuestionsToProducts, Builder<CheckListQuestionToProduct>.CreateListOfSize(1)
.All()
.With(qp => qp.ProductId, releaseWindow.ReleaseProducts.First().ProductId)
.Build())
.Build())
.Build();
var checkListQuestionsToProducts =
checkListItem.CheckListQuestion.CheckListQuestionsToProducts.First();
_checkListRepositoryMock.SetupEntities(new[] { checkListItem });
_checkListQuestionToProductRepositoryMock.Setup(x => x.GetByPrimaryKey(checkListQuestionsToProducts.CheckListQuestionsToProductsId))
.Returns(checkListItem.CheckListQuestion.CheckListQuestionsToProducts.First());
_checkListQuestionToProductRepositoryMock.Setup(x => x.Delete(checkListQuestionsToProducts));
_checkListRepositoryMock.Setup(x => x.Delete(checkListItem));
Sut.RemoveCheckListQuestionForPackage(checkListItem.ExternalId);
_checkListQuestionToProductRepositoryMock.Verify(x => x.Delete(It.IsAny<CheckListQuestionToProduct>()), Times.Once);
_checkListRepositoryMock.Verify(x => x.Delete(It.IsAny<CheckList>()), Times.Once);
}
}
}
| |
#if FEATURE_CONCURRENTMERGESCHEDULER
using J2N.Threading;
using Lucene.Net.Diagnostics;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using System.Threading;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using CollectionUtil = Lucene.Net.Util.CollectionUtil;
using Directory = Lucene.Net.Store.Directory;
/// <summary>
/// A <see cref="MergeScheduler"/> that runs each merge using a
/// separate thread.
///
/// <para>Specify the max number of threads that may run at
/// once, and the maximum number of simultaneous merges
/// with <see cref="SetMaxMergesAndThreads"/>.</para>
///
/// <para>If the number of merges exceeds the max number of threads
/// then the largest merges are paused until one of the smaller
/// merges completes.</para>
///
/// <para>If more than <see cref="MaxMergeCount"/> merges are
/// requested then this class will forcefully throttle the
/// incoming threads by pausing until one more more merges
/// complete.</para>
/// </summary>
public class ConcurrentMergeScheduler : MergeScheduler, IConcurrentMergeScheduler
{
private int mergeThreadPriority = -1;
/// <summary>
/// List of currently active <see cref="MergeThread"/>s. </summary>
protected internal IList<MergeThread> m_mergeThreads = new List<MergeThread>();
/// <summary>
/// Default <see cref="MaxThreadCount"/>.
/// We default to 1: tests on spinning-magnet drives showed slower
/// indexing performance if more than one merge thread runs at
/// once (though on an SSD it was faster)
/// </summary>
public const int DEFAULT_MAX_THREAD_COUNT = 1;
/// <summary>
/// Default <see cref="MaxMergeCount"/>. </summary>
public const int DEFAULT_MAX_MERGE_COUNT = 2;
// Max number of merge threads allowed to be running at
// once. When there are more merges then this, we
// forcefully pause the larger ones, letting the smaller
// ones run, up until maxMergeCount merges at which point
// we forcefully pause incoming threads (that presumably
// are the ones causing so much merging).
private int maxThreadCount = DEFAULT_MAX_THREAD_COUNT;
// Max number of merges we accept before forcefully
// throttling the incoming threads
private int maxMergeCount = DEFAULT_MAX_MERGE_COUNT;
/// <summary>
/// <see cref="Directory"/> that holds the index. </summary>
protected internal Directory m_dir;
/// <summary>
/// <see cref="IndexWriter"/> that owns this instance. </summary>
protected internal IndexWriter m_writer;
/// <summary>
/// How many <see cref="MergeThread"/>s have kicked off (this is use
/// to name them).
/// </summary>
protected internal int m_mergeThreadCount;
/// <summary>
/// Sole constructor, with all settings set to default
/// values.
/// </summary>
public ConcurrentMergeScheduler()
{
}
/// <summary>
/// Sets the maximum number of merge threads and simultaneous merges allowed.
/// </summary>
/// <param name="maxMergeCount"> the max # simultaneous merges that are allowed.
/// If a merge is necessary yet we already have this many
/// threads running, the incoming thread (that is calling
/// add/updateDocument) will block until a merge thread
/// has completed. Note that we will only run the
/// smallest <paramref name="maxThreadCount"/> merges at a time. </param>
/// <param name="maxThreadCount"> The max # simultaneous merge threads that should
/// be running at once. This must be <= <paramref name="maxMergeCount"/> </param>
public virtual void SetMaxMergesAndThreads(int maxMergeCount, int maxThreadCount)
{
if (maxThreadCount < 1)
{
throw new ArgumentException("maxThreadCount should be at least 1");
}
if (maxMergeCount < 1)
{
throw new ArgumentException("maxMergeCount should be at least 1");
}
if (maxThreadCount > maxMergeCount)
{
throw new ArgumentException("maxThreadCount should be <= maxMergeCount (= " + maxMergeCount + ")");
}
this.maxThreadCount = maxThreadCount;
this.maxMergeCount = maxMergeCount;
}
/// <summary>
/// Returns <see cref="maxThreadCount"/>.
/// </summary>
/// <seealso cref="SetMaxMergesAndThreads(int, int)"/>
public virtual int MaxThreadCount => maxThreadCount;
/// <summary>
/// See <see cref="SetMaxMergesAndThreads(int, int)"/>. </summary>
public virtual int MaxMergeCount => maxMergeCount;
/// <summary>
/// Return the priority that merge threads run at. By
/// default the priority is 1 plus the priority of (ie,
/// slightly higher priority than) the first thread that
/// calls merge.
/// </summary>
public virtual int MergeThreadPriority
{
get
{
lock (this)
{
InitMergeThreadPriority();
return mergeThreadPriority;
}
}
}
/// <summary>
/// Set the base priority that merge threads run at.
/// Note that CMS may increase priority of some merge
/// threads beyond this base priority. It's best not to
/// set this any higher than
/// <see cref="ThreadPriority.Highest"/>(4)-maxThreadCount, so that CMS has
/// room to set relative priority among threads.
/// </summary>
public virtual void SetMergeThreadPriority(int priority)
{
lock (this)
{
if (priority > (int)ThreadPriority.Highest || priority < (int)ThreadPriority.Lowest)
{
throw new ArgumentException("priority must be in range " + (int)ThreadPriority.Highest + " .. " + (int)ThreadPriority.Lowest + " inclusive");
}
mergeThreadPriority = priority;
UpdateMergeThreads();
}
}
/// <summary>
/// Sorts <see cref="MergeThread"/>s; larger merges come first. </summary>
protected internal static readonly IComparer<MergeThread> compareByMergeDocCount = Comparer<MergeThread>.Create((t1, t2) =>
{
MergePolicy.OneMerge m1 = t1.CurrentMerge;
MergePolicy.OneMerge m2 = t2.CurrentMerge;
int c1 = m1 == null ? int.MaxValue : m1.TotalDocCount;
int c2 = m2 == null ? int.MaxValue : m2.TotalDocCount;
return c2 - c1;
});
/// <summary>
/// Called whenever the running merges have changed, to pause & unpause
/// threads. This method sorts the merge threads by their merge size in
/// descending order and then pauses/unpauses threads from first to last --
/// that way, smaller merges are guaranteed to run before larger ones.
/// </summary>
protected virtual void UpdateMergeThreads()
{
lock (this)
{
// Only look at threads that are alive & not in the
// process of stopping (ie have an active merge):
IList<MergeThread> activeMerges = new List<MergeThread>();
int threadIdx = 0;
while (threadIdx < m_mergeThreads.Count)
{
MergeThread mergeThread = m_mergeThreads[threadIdx];
if (!mergeThread.IsAlive)
{
// Prune any dead threads
m_mergeThreads.RemoveAt(threadIdx);
continue;
}
if (mergeThread.CurrentMerge != null)
{
activeMerges.Add(mergeThread);
}
threadIdx++;
}
// Sort the merge threads in descending order.
CollectionUtil.TimSort(activeMerges, compareByMergeDocCount);
int pri = mergeThreadPriority;
int activeMergeCount = activeMerges.Count;
for (threadIdx = 0; threadIdx < activeMergeCount; threadIdx++)
{
MergeThread mergeThread = activeMerges[threadIdx];
MergePolicy.OneMerge merge = mergeThread.CurrentMerge;
if (merge == null)
{
continue;
}
// pause the thread if maxThreadCount is smaller than the number of merge threads.
bool doPause = threadIdx < activeMergeCount - maxThreadCount;
if (IsVerbose)
{
if (doPause != merge.IsPaused)
{
if (doPause)
{
Message("pause thread " + mergeThread.Name);
}
else
{
Message("unpause thread " + mergeThread.Name);
}
}
}
if (doPause != merge.IsPaused)
{
merge.SetPause(doPause);
}
if (!doPause)
{
if (IsVerbose)
{
Message("set priority of merge thread " + mergeThread.Name + " to " + pri);
}
mergeThread.SetThreadPriority((ThreadPriority)pri);
pri = Math.Min((int)ThreadPriority.Highest, 1 + pri);
}
}
}
}
/// <summary>
/// Returns <c>true</c> if verbosing is enabled. This method is usually used in
/// conjunction with <see cref="Message(String)"/>, like that:
///
/// <code>
/// if (IsVerbose)
/// {
/// Message("your message");
/// }
/// </code>
/// </summary>
protected virtual bool IsVerbose => m_writer != null && m_writer.infoStream.IsEnabled("CMS");
/// <summary>
/// Outputs the given message - this method assumes <see cref="IsVerbose"/> was
/// called and returned <c>true</c>.
/// </summary>
protected internal virtual void Message(string message)
{
m_writer.infoStream.Message("CMS", message);
}
private void InitMergeThreadPriority()
{
lock (this)
{
if (mergeThreadPriority == -1)
{
// Default to slightly higher priority than our
// calling thread
mergeThreadPriority = 1 + (int)ThreadJob.CurrentThread.Priority;
if (mergeThreadPriority > (int)ThreadPriority.Highest)
{
mergeThreadPriority = (int)ThreadPriority.Highest;
}
}
}
}
protected override void Dispose(bool disposing)
{
Sync();
}
/// <summary>
/// Wait for any running merge threads to finish. This call is not interruptible as used by <see cref="Dispose(bool)"/>. </summary>
public virtual void Sync()
{
bool interrupted = false;
try
{
while (true)
{
MergeThread toSync = null;
lock (this)
{
foreach (MergeThread t in m_mergeThreads)
{
if (t != null && t.IsAlive)
{
toSync = t;
break;
}
}
}
if (toSync != null)
{
try
{
toSync.Join();
}
#pragma warning disable 168
catch (ThreadInterruptedException ie)
#pragma warning restore 168
{
// ignore this Exception, we will retry until all threads are dead
interrupted = true;
}
}
else
{
break;
}
}
}
finally
{
// finally, restore interrupt status:
if (interrupted)
{
Thread.CurrentThread.Interrupt();
}
}
}
/// <summary>
/// Returns the number of merge threads that are alive. Note that this number
/// is <= <see cref="m_mergeThreads"/> size.
/// </summary>
protected virtual int MergeThreadCount
{
get
{
lock (this)
{
int count = 0;
foreach (MergeThread mt in m_mergeThreads)
{
if (mt.IsAlive && mt.CurrentMerge != null)
{
count++;
}
}
return count;
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override void Merge(IndexWriter writer, MergeTrigger trigger, bool newMergesFound)
{
lock (this)
{
if (Debugging.AssertsEnabled) Debugging.Assert(!Monitor.IsEntered(writer));
this.m_writer = writer;
InitMergeThreadPriority();
m_dir = writer.Directory;
// First, quickly run through the newly proposed merges
// and add any orthogonal merges (ie a merge not
// involving segments already pending to be merged) to
// the queue. If we are way behind on merging, many of
// these newly proposed merges will likely already be
// registered.
if (IsVerbose)
{
Message("now merge");
Message(" index: " + writer.SegString());
}
// Iterate, pulling from the IndexWriter's queue of
// pending merges, until it's empty:
while (true)
{
long startStallTime = 0;
while (writer.HasPendingMerges() && MergeThreadCount >= maxMergeCount)
{
// this means merging has fallen too far behind: we
// have already created maxMergeCount threads, and
// now there's at least one more merge pending.
// Note that only maxThreadCount of
// those created merge threads will actually be
// running; the rest will be paused (see
// updateMergeThreads). We stall this producer
// thread to prevent creation of new segments,
// until merging has caught up:
startStallTime = Environment.TickCount;
if (IsVerbose)
{
Message(" too many merges; stalling...");
}
//try
//{
Monitor.Wait(this);
//}
//catch (ThreadInterruptedException ie) // LUCENENET NOTE: Senseless to catch and rethrow the same exception type
//{
// throw new ThreadInterruptedException(ie.ToString(), ie);
//}
}
if (IsVerbose)
{
if (startStallTime != 0)
{
Message(" stalled for " + (Environment.TickCount - startStallTime) + " msec");
}
}
MergePolicy.OneMerge merge = writer.NextMerge();
if (merge == null)
{
if (IsVerbose)
{
Message(" no more merges pending; now return");
}
return;
}
bool success = false;
try
{
if (IsVerbose)
{
Message(" consider merge " + writer.SegString(merge.Segments));
}
// OK to spawn a new merge thread to handle this
// merge:
MergeThread merger = GetMergeThread(writer, merge);
m_mergeThreads.Add(merger);
if (IsVerbose)
{
Message(" launch new thread [" + merger.Name + "]");
}
merger.Start();
// Must call this after starting the thread else
// the new thread is removed from mergeThreads
// (since it's not alive yet):
UpdateMergeThreads();
success = true;
}
finally
{
if (!success)
{
writer.MergeFinish(merge);
}
}
}
}
}
/// <summary>
/// Does the actual merge, by calling <see cref="IndexWriter.Merge(MergePolicy.OneMerge)"/> </summary>
[MethodImpl(MethodImplOptions.NoInlining)]
protected virtual void DoMerge(MergePolicy.OneMerge merge)
{
m_writer.Merge(merge);
}
/// <summary>
/// Create and return a new <see cref="MergeThread"/> </summary>
protected virtual MergeThread GetMergeThread(IndexWriter writer, MergePolicy.OneMerge merge)
{
lock (this)
{
MergeThread thread = new MergeThread(this, writer, merge);
thread.SetThreadPriority((ThreadPriority)mergeThreadPriority);
thread.IsBackground = true;
thread.Name = "Lucene Merge Thread #" + m_mergeThreadCount++;
return thread;
}
}
/// <summary>
/// Runs a merge thread, which may run one or more merges
/// in sequence.
/// </summary>
protected internal class MergeThread : ThreadJob
{
private readonly ConcurrentMergeScheduler outerInstance;
internal IndexWriter tWriter;
internal MergePolicy.OneMerge startMerge;
internal MergePolicy.OneMerge runningMerge;
private volatile bool done;
/// <summary>
/// Sole constructor. </summary>
public MergeThread(ConcurrentMergeScheduler outerInstance, IndexWriter writer, MergePolicy.OneMerge startMerge)
{
this.outerInstance = outerInstance;
this.tWriter = writer;
this.startMerge = startMerge;
}
/// <summary>
/// Record the currently running merge. </summary>
public virtual MergePolicy.OneMerge RunningMerge
{
set
{
lock (this)
{
runningMerge = value;
}
}
get
{
lock (this)
{
return runningMerge;
}
}
}
/// <summary>
/// Return the current merge, or <c>null</c> if this
/// <see cref="MergeThread"/> is done.
/// </summary>
public virtual MergePolicy.OneMerge CurrentMerge
{
get
{
lock (this)
{
if (done)
{
return null;
}
else if (runningMerge != null)
{
return runningMerge;
}
else
{
return startMerge;
}
}
}
}
/// <summary>
/// Set the priority of this thread. </summary>
public virtual void SetThreadPriority(ThreadPriority priority)
{
try
{
Priority = priority;
}
#pragma warning disable 168
catch (NullReferenceException npe)
{
// Strangely, Sun's JDK 1.5 on Linux sometimes
// throws NPE out of here...
}
catch (SecurityException se)
#pragma warning restore 168
{
// Ignore this because we will still run fine with
// normal thread priority
}
}
public override void Run()
{
// First time through the while loop we do the merge
// that we were started with:
MergePolicy.OneMerge merge = this.startMerge;
try
{
if (outerInstance.IsVerbose)
{
outerInstance.Message(" merge thread: start");
}
while (true)
{
RunningMerge = merge;
outerInstance.DoMerge(merge);
// Subsequent times through the loop we do any new
// merge that writer says is necessary:
merge = tWriter.NextMerge();
// Notify here in case any threads were stalled;
// they will notice that the pending merge has
// been pulled and possibly resume:
lock (outerInstance)
{
Monitor.PulseAll(outerInstance);
}
if (merge != null)
{
outerInstance.UpdateMergeThreads();
if (outerInstance.IsVerbose)
{
outerInstance.Message(" merge thread: do another merge " + tWriter.SegString(merge.Segments));
}
}
else
{
break;
}
}
if (outerInstance.IsVerbose)
{
outerInstance.Message(" merge thread: done");
}
}
catch (Exception exc)
{
// Ignore the exception if it was due to abort:
if (!(exc is MergePolicy.MergeAbortedException))
{
//System.out.println(Thread.currentThread().getName() + ": CMS: exc");
//exc.printStackTrace(System.out);
if (!outerInstance.suppressExceptions)
{
// suppressExceptions is normally only set during
// testing.
outerInstance.HandleMergeException(exc);
}
}
}
finally
{
done = true;
lock (outerInstance)
{
outerInstance.UpdateMergeThreads();
Monitor.PulseAll(outerInstance);
}
}
}
}
/// <summary>
/// Called when an exception is hit in a background merge
/// thread
/// </summary>
protected virtual void HandleMergeException(Exception exc)
{
//try
//{
// When an exception is hit during merge, IndexWriter
// removes any partial files and then allows another
// merge to run. If whatever caused the error is not
// transient then the exception will keep happening,
// so, we sleep here to avoid saturating CPU in such
// cases:
Thread.Sleep(250);
//}
//catch (ThreadInterruptedException ie) // LUCENENET NOTE: Senseless to catch and rethrow the same exception type
//{
// throw new ThreadInterruptedException("Thread Interrupted Exception", ie);
//}
throw new MergePolicy.MergeException(exc, m_dir);
}
private bool suppressExceptions;
/// <summary>
/// Used for testing </summary>
public virtual void SetSuppressExceptions()
{
suppressExceptions = true;
}
/// <summary>
/// Used for testing </summary>
public virtual void ClearSuppressExceptions()
{
suppressExceptions = false;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder(this.GetType().Name + ": ");
sb.Append("maxThreadCount=").Append(maxThreadCount).Append(", ");
sb.Append("maxMergeCount=").Append(maxMergeCount).Append(", ");
sb.Append("mergeThreadPriority=").Append(mergeThreadPriority);
return sb.ToString();
}
public override object Clone()
{
ConcurrentMergeScheduler clone = (ConcurrentMergeScheduler)base.Clone();
clone.m_writer = null;
clone.m_dir = null;
clone.m_mergeThreads = new List<MergeThread>();
return clone;
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;
namespace WebApplication.Data.Migrations
{
public partial class CreateIdentitySchema : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
ConcurrencyStamp = table.Column<string>(nullable: true),
Name = table.Column<string>(nullable: true),
NormalizedName = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
LoginProvider = table.Column<string>(nullable: false),
Name = table.Column<string>(nullable: false),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false),
ConcurrencyStamp = table.Column<string>(nullable: true),
Email = table.Column<string>(nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
LockoutEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
NormalizedEmail = table.Column<string>(nullable: true),
NormalizedUserName = table.Column<string>(nullable: true),
PasswordHash = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
SecurityStamp = table.Column<string>(nullable: true),
TwoFactorEnabled = table.Column<bool>(nullable: false),
UserName = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Autoincrement", true),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Autoincrement", true),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(nullable: false),
ProviderKey = table.Column<string>(nullable: false),
ProviderDisplayName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName");
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_UserId",
table: "AspNetUserRoles",
column: "UserId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
}
}
}
| |
// <copyright file="GPGSIOSSetupUI.cs" company="Google Inc.">
// Copyright (C) 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
namespace GooglePlayGames.Editor
{
using System;
using System.IO;
using System.Collections;
using UnityEngine;
using UnityEditor;
public class GPGSIOSSetupUI : EditorWindow
{
private string mBundleId = string.Empty;
private string mWebClientId = string.Empty;
private string mClassName = "GooglePlayGames.GPGSIds";
private string mClassDirectory = "Assets";
private string mConfigData = string.Empty;
private bool mRequiresGooglePlus = false;
private Vector2 scroll;
[MenuItem("Window/Google Play Games/Setup/iOS setup...", false, 2)]
public static void MenuItemGPGSIOSSetup()
{
EditorWindow window = EditorWindow.GetWindow(
typeof(GPGSIOSSetupUI), true, GPGSStrings.IOSSetup.Title);
window.minSize = new Vector2(500, 600);
}
[MenuItem("Window/Google Play Games/Setup/iOS setup...", true)]
public static bool EnableIOSMenu() {
#if UNITY_IPHONE
return true;
#else
return false;
#endif
}
public void OnEnable() {
mBundleId = GPGSProjectSettings.Instance.Get(GPGSUtil.IOSBUNDLEIDKEY);
mWebClientId = GPGSProjectSettings.Instance.Get(GPGSUtil.WEBCLIENTIDKEY);
mClassDirectory = GPGSProjectSettings.Instance.Get(GPGSUtil.CLASSDIRECTORYKEY, mClassDirectory);
mClassName = GPGSProjectSettings.Instance.Get(GPGSUtil.CLASSNAMEKEY);
mConfigData = GPGSProjectSettings.Instance.Get(GPGSUtil.IOSRESOURCEKEY);
if (mBundleId.Trim().Length == 0)
{
#if UNITY_5_6_OR_NEWER
mBundleId = PlayerSettings.GetApplicationIdentifier(
BuildTargetGroup.iOS);
#else
mBundleId = PlayerSettings.bundleIdentifier;
#endif
}
}
/// <summary>
/// Save the specified clientId and bundleId to properties file.
/// This maintains the configuration across instances of running Unity.
/// </summary>
/// <param name="clientId">Client identifier.</param>
/// <param name="bundleId">Bundle identifier.</param>
/// <param name="webClientId">web app clientId.</param>
/// <param name="requiresGooglePlus">App requires G+ access</param>
internal static void Save(string clientId,
string bundleId,
string webClientId,
bool requiresGooglePlus)
{
if (clientId != null)
{
clientId = clientId.Trim();
}
GPGSProjectSettings.Instance.Set(GPGSUtil.IOSCLIENTIDKEY, clientId);
if (bundleId != null)
{
bundleId = bundleId.Trim();
}
GPGSProjectSettings.Instance.Set(GPGSUtil.IOSBUNDLEIDKEY, bundleId);
if (webClientId != null)
{
webClientId = webClientId.Trim();
}
GPGSProjectSettings.Instance.Set(GPGSUtil.WEBCLIENTIDKEY, webClientId);
GPGSProjectSettings.Instance.Save();
}
public void OnGUI()
{
GUIStyle link = new GUIStyle(GUI.skin.label);
link.normal.textColor = new Color(.7f, .7f, 1f);
// Title
GUILayout.BeginVertical();
GUILayout.Space(10);
GUILayout.Label(GPGSStrings.IOSSetup.Blurb);
GUILayout.Space(10);
if (GUILayout.Button("Open Play Games Console", link, GUILayout.ExpandWidth(false)))
{
Application.OpenURL("https://play.google.com/apps/publish");
}
Rect last = GUILayoutUtility.GetLastRect();
last.y += last.height - 2;
last.x += 3;
last.width -= 6;
last.height = 2;
GUI.Box(last, string.Empty);
GUILayout.Space(15);
// Bundle ID field
GUILayout.Label(GPGSStrings.IOSSetup.BundleIdTitle, EditorStyles.boldLabel);
GUILayout.Label(GPGSStrings.IOSSetup.BundleIdBlurb, EditorStyles.wordWrappedLabel);
mBundleId = EditorGUILayout.TextField(GPGSStrings.IOSSetup.BundleId, mBundleId,
GUILayout.Width(450));
GUILayout.Space(30);
// Client ID field
GUILayout.Label(GPGSStrings.Setup.WebClientIdTitle, EditorStyles.boldLabel);
GUILayout.Label(GPGSStrings.AndroidSetup.WebClientIdBlurb, EditorStyles.wordWrappedLabel);
GUILayout.Space(10);
mWebClientId = EditorGUILayout.TextField(GPGSStrings.Setup.ClientId,
mWebClientId, GUILayout.Width(450));
GUILayout.Space(10);
GUILayout.FlexibleSpace();
GUILayout.Label("Constants class name", EditorStyles.boldLabel);
GUILayout.Label("Enter the fully qualified name of the class to create containing the constants");
GUILayout.Space(10);
mClassDirectory = EditorGUILayout.TextField("Directory to save constants",
mClassDirectory, GUILayout.Width(480));
mClassName = EditorGUILayout.TextField("Constants class name",
mClassName, GUILayout.Width(480));
GUILayout.Label("Resources Definition", EditorStyles.boldLabel);
GUILayout.Label("Paste in the Objective-C Resources from the Play Console");
GUILayout.Space(10);
scroll = GUILayout.BeginScrollView(scroll);
mConfigData = EditorGUILayout.TextArea(mConfigData,
GUILayout.Width(475), GUILayout.Height(Screen.height));
GUILayout.EndScrollView();
GUILayout.Space(10);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
// Setup button
if (GUILayout.Button(GPGSStrings.Setup.SetupButton))
{
// check that the classname entered is valid
try
{
if (GPGSUtil.LooksLikeValidPackageName(mClassName))
{
DoSetup();
}
}
catch (Exception e)
{
GPGSUtil.Alert(GPGSStrings.Error,
"Invalid classname: " + e.Message);
}
}
if (GUILayout.Button(GPGSStrings.Cancel))
{
this.Close();
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(20);
GUILayout.EndVertical();
}
/// <summary>
/// Called by the UI to process the configuration.
/// </summary>
internal void DoSetup()
{
if (PerformSetup(mClassDirectory, mClassName, mConfigData, mWebClientId, mBundleId, null, mRequiresGooglePlus))
{
GPGSUtil.Alert(GPGSStrings.Success, GPGSStrings.IOSSetup.SetupComplete);
Close();
}
else
{
GPGSUtil.Alert(GPGSStrings.Error,
"Missing or invalid resource data. Check that CLIENT_ID is defined.");
}
}
/// <summary>
/// Performs setup using the Android resources downloaded XML file
/// from the play console.
/// </summary>
/// <returns><c>true</c>, if setup was performed, <c>false</c> otherwise.</returns>
/// <param name="className">Fully qualified class name for the resource Ids.</param>
/// <param name="resourceXmlData">Resource xml data.</param>
/// <param name="webClientId">Client identifier.</param>
/// <param name="bundleId">Bundle identifier.</param>
/// <param name="nearbySvcId">Nearby svc identifier.</param>
/// <param name="requiresGooglePlus">App Requires Google Plus API.</param>
public static bool PerformSetup(
string classDirectory,
string className,
string resourceXmlData,
string webClientId,
string bundleId,
string nearbySvcId,
bool requiresGooglePlus)
{
if (ParseResources(classDirectory, className, resourceXmlData))
{
GPGSProjectSettings.Instance.Set(GPGSUtil.CLASSNAMEKEY, className);
GPGSProjectSettings.Instance.Set(GPGSUtil.IOSRESOURCEKEY, resourceXmlData);
GPGSProjectSettings.Instance.Set(GPGSUtil.WEBCLIENTIDKEY, webClientId);
if (string.IsNullOrEmpty(bundleId))
{
// get from settings
bundleId = GPGSProjectSettings.Instance.Get(GPGSUtil.IOSBUNDLEIDKEY);
#if UNITY_5_6_OR_NEWER
PlayerSettings.SetApplicationIdentifier(
BuildTargetGroup.iOS, bundleId);
#else
PlayerSettings.bundleIdentifier = bundleId;
#endif
}
return PerformSetup(GPGSProjectSettings.Instance.Get(GPGSUtil.IOSCLIENTIDKEY),
bundleId, webClientId, nearbySvcId, requiresGooglePlus);
}
Debug.LogError("Failed to parse resources, returing false.");
return false;
}
private static bool ParseResources(string classDirectory, string className, string res)
{
// parse the resources, they keys are in the form of
// #define <KEY> @"<VALUE>"
// transform the string to make it easier to parse
string input = res.Replace("#define ", string.Empty);
input = input.Replace("@\"", string.Empty);
input = input.Replace("\"", string.Empty);
// now input is name value, one per line
StringReader reader = new StringReader(input);
string line = reader.ReadLine();
string key;
string value;
string clientId = null;
Hashtable resourceKeys = new Hashtable();
while (line != null)
{
string[] parts = line.Split(' ');
key = parts[0];
if (parts.Length > 1)
{
value = parts[1];
}
else
{
value = null;
}
if (!string.IsNullOrEmpty(value))
{
if (key == "CLIENT_ID")
{
clientId = value;
GPGSProjectSettings.Instance.Set(GPGSUtil.IOSCLIENTIDKEY, clientId);
}
else if (key == "BUNDLE_ID")
{
GPGSProjectSettings.Instance.Set(GPGSUtil.IOSBUNDLEIDKEY, value);
}
else if (key.StartsWith("ACH_"))
{
string prop = "achievement_" + key.Substring(4).ToLower();
resourceKeys[prop] = value;
}
else if (key.StartsWith("LEAD_"))
{
string prop = "leaderboard_" + key.Substring(5).ToLower();
resourceKeys[prop] = value;
}
else if (key.StartsWith("EVENT_"))
{
string prop = "event_" + key.Substring(6).ToLower();
resourceKeys[prop] = value;
}
else if (key.StartsWith("QUEST_"))
{
string prop = "quest_" + key.Substring(6).ToLower();
resourceKeys[prop] = value;
}
else
{
resourceKeys[key] = value;
}
}
line = reader.ReadLine();
}
reader.Close();
if (resourceKeys.Count > 0)
{
GPGSUtil.WriteResourceIds(classDirectory, className, resourceKeys);
}
GPGSProjectSettings.Instance.Save();
return !string.IsNullOrEmpty(clientId);
}
/// <summary>
/// Performs the setup. This is called externally to facilitate
/// build automation.
/// </summary>
/// <param name="clientId">Client identifier.</param>
/// <param name="bundleId">Bundle identifier.</param>
/// <param name="webClientId">web app client id.</param>
/// <param name="nearbySvcId">Nearby connections service Id.</param>
/// <param name="requiresGooglePlus">App requires G+ access</param>
public static bool PerformSetup(string clientId, string bundleId,
string webClientId, string nearbySvcId, bool requiresGooglePlus)
{
if (!GPGSUtil.LooksLikeValidClientId(clientId))
{
GPGSUtil.Alert(GPGSStrings.Setup.ClientIdError);
return false;
}
if (!GPGSUtil.LooksLikeValidBundleId(bundleId))
{
GPGSUtil.Alert(GPGSStrings.IOSSetup.BundleIdError);
return false;
}
// nearby is optional - only set it up if present.
if (nearbySvcId != null) {
#if (UNITY_IPHONE && !NO_GPGS)
bool ok = NearbyConnectionUI.PerformSetup(nearbySvcId, false);
if (!ok)
{
Debug.LogError("NearbyConnection Setup failed, returing false.");
return false;
}
#endif
}
Save(clientId, bundleId, webClientId, requiresGooglePlus);
GPGSUtil.UpdateGameInfo();
// Finished!
GPGSProjectSettings.Instance.Set(GPGSUtil.IOSSETUPDONEKEY, true);
GPGSProjectSettings.Instance.Save();
AssetDatabase.Refresh();
return true;
}
}
}
| |
#if !NETFX_CORE && !IOS || NETSTANDARD
//-----------------------------------------------------------------------
// <copyright file="DataMapper.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>Map data from a source into a target object</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Csla.Properties;
using Csla.Reflection;
using System.Linq;
namespace Csla.Data
{
/// <summary>
/// Map data from a source into a target object
/// by copying public property values.
/// </summary>
/// <remarks></remarks>
public static class DataMapper
{
#region Map from IDictionary
/// <summary>
/// Copies values from the source into the
/// properties of the target.
/// </summary>
/// <param name="source">A name/value dictionary containing the source values.</param>
/// <param name="target">An object with properties to be set from the dictionary.</param>
/// <remarks>
/// The key names in the dictionary must match the property names on the target
/// object. Target properties may not be readonly or indexed.
/// </remarks>
public static void Map(System.Collections.IDictionary source, object target)
{
Map(source, target, false);
}
/// <summary>
/// Copies values from the source into the
/// properties of the target.
/// </summary>
/// <param name="source">A name/value dictionary containing the source values.</param>
/// <param name="target">An object with properties to be set from the dictionary.</param>
/// <param name="ignoreList">A list of property names to ignore.
/// These properties will not be set on the target object.</param>
/// <remarks>
/// The key names in the dictionary must match the property names on the target
/// object. Target properties may not be readonly or indexed.
/// </remarks>
public static void Map(System.Collections.IDictionary source, object target, params string[] ignoreList)
{
Map(source, target, false, ignoreList);
}
/// <summary>
/// Copies values from the source into the
/// properties of the target.
/// </summary>
/// <param name="source">A name/value dictionary containing the source values.</param>
/// <param name="target">An object with properties to be set from the dictionary.</param>
/// <param name="ignoreList">A list of property names to ignore.
/// These properties will not be set on the target object.</param>
/// <param name="suppressExceptions">If true, any exceptions will be supressed.</param>
/// <remarks>
/// The key names in the dictionary must match the property names on the target
/// object. Target properties may not be readonly or indexed.
/// </remarks>
public static void Map(
System.Collections.IDictionary source,
object target, bool suppressExceptions,
params string[] ignoreList)
{
List<string> ignore = new List<string>(ignoreList);
foreach (string propertyName in source.Keys)
{
if (!ignore.Contains(propertyName))
{
try
{
SetPropertyValue(target, propertyName, source[propertyName]);
}
catch (Exception ex)
{
if (!suppressExceptions)
throw new ArgumentException(
String.Format("{0} ({1})",
Resources.PropertyCopyFailed, propertyName), ex);
}
}
}
}
#endregion
#region Map to Dictionary
/// <summary>
/// Copies values from the source into the target.
/// </summary>
/// <param name="source">An object with properties to be loaded into the dictionary.</param>
/// <param name="target">A name/value dictionary containing the source values.</param>
public static void Map(object source, Dictionary<string, object> target)
{
Map(source, target, false);
}
/// <summary>
/// Copies values from the source into the target.
/// </summary>
/// <param name="source">An object with properties to be loaded into the dictionary.</param>
/// <param name="target">A name/value dictionary containing the source values.</param>
/// <param name="ignoreList">A list of property names to ignore.
/// These properties will not be set on the target object.</param>
public static void Map(object source, Dictionary<string, object> target, params string[] ignoreList)
{
Map(source, target, false, ignoreList);
}
/// <summary>
/// Copies values from the source into the target.
/// </summary>
/// <param name="source">An object with properties to be loaded into the dictionary.</param>
/// <param name="target">A name/value dictionary containing the source values.</param>
/// <param name="ignoreList">A list of property names to ignore.
/// These properties will not be set on the target object.</param>
/// <param name="suppressExceptions">If true, any exceptions will be supressed.</param>
public static void Map(
object source, Dictionary<string, object> target,
bool suppressExceptions,
params string[] ignoreList)
{
List<string> ignore = new List<string>(ignoreList);
foreach (var propertyName in GetPropertyNames(source.GetType()))
{
if (!ignore.Contains(propertyName))
{
try
{
target.Add(propertyName, MethodCaller.CallPropertyGetter(source, propertyName));
}
catch (Exception ex)
{
if (!suppressExceptions)
throw new ArgumentException(
String.Format("{0} ({1})",
Resources.PropertyCopyFailed, propertyName), ex);
}
}
}
}
#endregion
#region Map from Object
/// <summary>
/// Copies values from the source into the
/// properties of the target.
/// </summary>
/// <param name="source">An object containing the source values.</param>
/// <param name="target">An object with properties to be set from the dictionary.</param>
/// <remarks>
/// The property names and types of the source object must match the property names and types
/// on the target object. Source properties may not be indexed.
/// Target properties may not be readonly or indexed.
/// </remarks>
public static void Map(object source, object target)
{
Map(source, target, false);
}
/// <summary>
/// Copies values from the source into the
/// properties of the target.
/// </summary>
/// <param name="source">An object containing the source values.</param>
/// <param name="target">An object with properties to be set from the dictionary.</param>
/// <param name="ignoreList">A list of property names to ignore.
/// These properties will not be set on the target object.</param>
/// <remarks>
/// The property names and types of the source object must match the property names and types
/// on the target object. Source properties may not be indexed.
/// Target properties may not be readonly or indexed.
/// </remarks>
public static void Map(object source, object target, params string[] ignoreList)
{
Map(source, target, false, ignoreList);
}
/// <summary>
/// Copies values from the source into the
/// properties of the target.
/// </summary>
/// <param name="source">An object containing the source values.</param>
/// <param name="target">An object with properties to be set from the dictionary.</param>
/// <param name="ignoreList">A list of property names to ignore.
/// These properties will not be set on the target object.</param>
/// <param name="suppressExceptions">If true, any exceptions will be supressed.</param>
/// <remarks>
/// <para>
/// The property names and types of the source object must match the property names and types
/// on the target object. Source properties may not be indexed.
/// Target properties may not be readonly or indexed.
/// </para><para>
/// Properties to copy are determined based on the source object. Any properties
/// on the source object marked with the <see cref="BrowsableAttribute"/> equal
/// to false are ignored.
/// </para>
/// </remarks>
public static void Map(
object source, object target,
bool suppressExceptions,
params string[] ignoreList)
{
List<string> ignore = new List<string>(ignoreList);
foreach (var propertyName in GetPropertyNames(source.GetType()))
{
if (!ignore.Contains(propertyName))
{
try
{
object value = MethodCaller.CallPropertyGetter(source, propertyName);
SetPropertyValue(target, propertyName, value);
}
catch (Exception ex)
{
if (!suppressExceptions)
throw new ArgumentException(
String.Format("{0} ({1})",
Resources.PropertyCopyFailed, propertyName), ex);
}
}
}
}
/// <summary>
/// Copies values from the source into the
/// properties of the target.
/// </summary>
/// <param name="source">An object containing the source values.</param>
/// <param name="target">An object with properties to be set from the dictionary.</param>
/// <param name="map">A DataMap object containing the mappings to use during the copy process.</param>
/// <remarks>
/// The property names and types of the source object must match the property names and types
/// on the target object. Source properties may not be indexed.
/// Target properties may not be readonly or indexed.
/// </remarks>
public static void Map(object source, object target, DataMap map)
{
Map(source, target, map, false);
}
/// <summary>
/// Copies values from the source into the
/// properties of the target.
/// </summary>
/// <param name="source">An object containing the source values.</param>
/// <param name="target">An object with properties to be set from the dictionary.</param>
/// <param name="suppressExceptions">If true, any exceptions will be supressed.</param>
/// <param name="map">A DataMap object containing the mappings to use during the copy process.</param>
/// <remarks>
/// The property names and types of the source object must match the property names and types
/// on the target object. Source properties may not be indexed.
/// Target properties may not be readonly or indexed.
/// </remarks>
public static void Map(object source, object target, DataMap map, bool suppressExceptions)
{
foreach (DataMap.MemberMapping mapping in map.GetMap())
{
try
{
object value = mapping.FromMemberHandle.DynamicMemberGet(source);
SetValueWithCoercion(target, mapping.ToMemberHandle, value);
}
catch (Exception ex)
{
if (!suppressExceptions)
throw new ArgumentException(
String.Format("{0} ({1})",
Resources.PropertyCopyFailed, mapping.FromMemberHandle.MemberName), ex);
}
}
}
private static IList<string> GetPropertyNames(Type sourceType)
{
#if NETSTANDARD
var properties = sourceType.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
List<string> result = properties.Select(r => r.Name).ToList();
#else
List<string> result = new List<string>();
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(sourceType);
foreach (PropertyDescriptor item in props)
if (item.IsBrowsable)
result.Add(item.Name);
#endif
return result;
}
#endregion
#region Load from IDictionary
/// <summary>
/// Copies values from the source into the
/// target.
/// </summary>
/// <param name="source">
/// Dictionary containing the source values.
/// </param>
/// <param name="target">
/// Business object with managed fields that
/// will contain the copied values.
/// </param>
/// <param name="nameMapper">
/// A function that translates the target
/// property names into key values for the
/// source dictionary.
/// </param>
public static void Load(System.Collections.IDictionary source, object target, Func<string, object> nameMapper)
{
var validTarget = target as Core.IManageProperties;
if (validTarget == null)
throw new NotSupportedException();
var propertyList = validTarget.GetManagedProperties();
foreach (var p in propertyList)
validTarget.LoadProperty(p, source[nameMapper(p.Name)]);
}
#endregion
#region Load to IDictionary
/// <summary>
/// Copies values from the source into the
/// target.
/// </summary>
/// <param name="source">
/// Business object with managed fields that
/// contain the source values.
/// </param>
/// <param name="target">
/// Dictionary that will contain the resulting values.
/// </param>
/// <param name="nameMapper">
/// A function that translates the source
/// property names into key values for the
/// target dictionary.
/// </param>
public static void Load(object source, System.Collections.IDictionary target, Func<string, object> nameMapper)
{
var validSource = source as Core.IManageProperties;
if (validSource == null)
throw new NotSupportedException();
var propertyList = validSource.GetManagedProperties();
foreach (var p in propertyList)
target[nameMapper(p.Name)] = validSource.ReadProperty(p);
}
#endregion
#region SetValue
/// <summary>
/// Sets an object's property with the specified value,
/// coercing that value to the appropriate type if possible.
/// </summary>
/// <param name="target">Object containing the property to set.</param>
/// <param name="propertyName">Name of the property to set.</param>
/// <param name="value">Value to set into the property.</param>
public static void SetPropertyValue(
object target, string propertyName, object value)
{
DynamicMemberHandle handle = MethodCaller.GetCachedProperty(target.GetType(), propertyName);
SetValueWithCoercion(target, handle, value);
}
private static void SetValueWithCoercion(object target, DynamicMemberHandle handle, object value)
{
var oldValue = handle.DynamicMemberGet(target);
Type pType = handle.MemberType;
#if NETSTANDARD
var isGeneric = pType.IsGenericType();
var isPrimitive = pType.IsPrimitive();
var isValueType = pType.IsValueType();
#else
var isGeneric = pType.IsGenericType;
var isPrimitive = pType.IsPrimitive;
var isValueType = pType.IsValueType;
#endif
if (!isGeneric
|| (isGeneric && pType.GetGenericTypeDefinition() != typeof(Nullable<>)))
{
if (isValueType && (isPrimitive || pType == typeof(decimal)) && value == null)
{
value = 0;
}
}
if (value != null)
{
Type vType = Utilities.GetPropertyType(value.GetType());
value = Utilities.CoerceValue(pType, vType, oldValue, value);
}
handle.DynamicMemberSet(target, value);
}
/// <summary>
/// Sets an object's field with the specified value,
/// coercing that value to the appropriate type if possible.
/// </summary>
/// <param name="target">Object containing the field to set.</param>
/// <param name="fieldName">Name of the field (public or non-public) to set.</param>
/// <param name="value">Value to set into the field.</param>
public static void SetFieldValue(
object target, string fieldName, object value)
{
DynamicMemberHandle handle = MethodCaller.GetCachedField(target.GetType(), fieldName);
SetValueWithCoercion(target, handle, value);
}
/// <summary>
/// Gets an object's field value.
/// </summary>
/// <param name="target">Object whose field value to get.</param>
/// <param name="fieldName">The name of the field.</param>
/// <returns>The value of the field.</returns>
public static object GetFieldValue(
object target, string fieldName)
{
DynamicMemberHandle handle = MethodCaller.GetCachedField(target.GetType(), fieldName);
return handle.DynamicMemberGet.Invoke(target);
}
#endregion
}
}
#endif
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
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.
*/
//#define TRACE_SERIALIZATION
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Text;
using Orleans.Runtime;
using Orleans.CodeGeneration;
namespace Orleans.Serialization
{
/// <summary>
/// Reader for Orleans binary token streams
/// </summary>
public class BinaryTokenStreamReader
{
private readonly IList<ArraySegment<byte>> buffers;
private int currentSegmentIndex;
private ArraySegment<byte> currentSegment;
private byte[] currentBuffer;
private int currentOffset;
private int totalProcessedBytes;
private readonly int totalLength;
private static readonly ArraySegment<byte> emptySegment = new ArraySegment<byte>(new byte[0]);
/// <summary>
/// Create a new BinaryTokenStreamReader to read from the specified input byte array.
/// </summary>
/// <param name="input">Input binary data to be tokenized.</param>
public BinaryTokenStreamReader(byte[] input)
: this(new List<ArraySegment<byte>> { new ArraySegment<byte>(input) })
{
}
/// <summary>
/// Create a new BinaryTokenStreamReader to read from the specified input buffers.
/// </summary>
/// <param name="buffs">The list of ArraySegments to use for the data.</param>
public BinaryTokenStreamReader(IList<ArraySegment<byte>> buffs)
{
buffers = buffs;
totalProcessedBytes = 0;
currentSegmentIndex = 0;
currentSegment = buffs[0];
currentBuffer = currentSegment.Array;
currentOffset = currentSegment.Offset;
totalLength = buffs.Sum(b => b.Count);
Trace("Starting new stream reader");
}
/// <summary> Current read position in the stream. </summary>
public int CurrentPosition { get { return currentOffset + totalProcessedBytes - currentSegment.Offset; } }
private void StartNextSegment()
{
totalProcessedBytes += currentSegment.Count;
currentSegmentIndex++;
if (currentSegmentIndex < buffers.Count)
{
currentSegment = buffers[currentSegmentIndex];
currentBuffer = currentSegment.Array;
currentOffset = currentSegment.Offset;
}
else
{
currentSegment = emptySegment;
currentBuffer = null;
currentOffset = 0;
}
}
private ArraySegment<byte> CheckLength(int n)
{
bool ignore;
return CheckLength(n, out ignore);
}
private ArraySegment<byte> CheckLength(int n, out bool safeToUse)
{
safeToUse = false;
if (n == 0)
{
safeToUse = true;
return emptySegment;
}
if ((CurrentPosition + n > totalLength))
{
throw new SerializationException(
String.Format("Attempt to read past the end of the input stream: CurrentPosition={0}, n={1}, totalLength={2}",
CurrentPosition, n, totalLength));
}
if (currentSegmentIndex >= buffers.Count)
{
throw new SerializationException(
String.Format("Attempt to read past buffers.Count: currentSegmentIndex={0}, buffers.Count={1}.", currentSegmentIndex, buffers.Count));
}
if (currentOffset == currentSegment.Offset + currentSegment.Count)
{
StartNextSegment();
}
if (currentOffset + n <= currentSegment.Offset + currentSegment.Count)
{
var result = new ArraySegment<byte>(currentBuffer, currentOffset, n);
currentOffset += n;
if (currentOffset >= currentSegment.Offset + currentSegment.Count)
{
StartNextSegment();
}
return result;
}
var temp = new byte[n];
var i = 0;
while (i < n)
{
var bytesFromThisBuffer = Math.Min(currentSegment.Offset + currentSegment.Count - currentOffset,
n - i);
Buffer.BlockCopy(currentBuffer, currentOffset, temp, i, bytesFromThisBuffer);
i += bytesFromThisBuffer;
currentOffset += bytesFromThisBuffer;
if (currentOffset >= currentSegment.Offset + currentSegment.Count)
{
StartNextSegment();
}
}
safeToUse = true;
return new ArraySegment<byte>(temp);
}
/// <summary> Read an <c>Int32</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public int ReadInt()
{
var buff = CheckLength(sizeof(int));
var val = BitConverter.ToInt32(buff.Array, buff.Offset);
Trace("--Read int {0}", val);
return val;
}
/// <summary> Read an <c>UInt32</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public uint ReadUInt()
{
var buff = CheckLength(sizeof(uint));
var val = BitConverter.ToUInt32(buff.Array, buff.Offset);
Trace("--Read uint {0}", val);
return val;
}
/// <summary> Read an <c>Int16</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public short ReadShort()
{
var buff = CheckLength(sizeof(short));
var val = BitConverter.ToInt16(buff.Array, buff.Offset);
Trace("--Read short {0}", val);
return val;
}
/// <summary> Read an <c>UInt16</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public ushort ReadUShort()
{
var buff = CheckLength(sizeof(ushort));
var val = BitConverter.ToUInt16(buff.Array, buff.Offset);
Trace("--Read ushort {0}", val);
return val;
}
/// <summary> Read an <c>Int64</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public long ReadLong()
{
var buff = CheckLength(sizeof(long));
var val = BitConverter.ToInt64(buff.Array, buff.Offset);
Trace("--Read long {0}", val);
return val;
}
/// <summary> Read an <c>UInt64</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public ulong ReadULong()
{
var buff = CheckLength(sizeof(ulong));
var val = BitConverter.ToUInt64(buff.Array, buff.Offset);
Trace("--Read ulong {0}", val);
return val;
}
/// <summary> Read an <c>float</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public float ReadFloat()
{
var buff = CheckLength(sizeof(float));
var val = BitConverter.ToSingle(buff.Array, buff.Offset);
Trace("--Read float {0}", val);
return val;
}
/// <summary> Read an <c>double</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public double ReadDouble()
{
var buff = CheckLength(sizeof(double));
var val = BitConverter.ToDouble(buff.Array, buff.Offset);
Trace("--Read double {0}", val);
return val;
}
/// <summary> Read an <c>decimal</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public decimal ReadDecimal()
{
var buff = CheckLength(4 * sizeof(int));
var raw = new int[4];
Trace("--Read decimal");
var n = buff.Offset;
for (var i = 0; i < 4; i++)
{
raw[i] = BitConverter.ToInt32(buff.Array, n);
n += sizeof(int);
}
return new decimal(raw);
}
/// <summary> Read an <c>string</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public string ReadString()
{
var n = ReadInt();
if (n == 0)
{
Trace("--Read empty string");
return String.Empty;
}
string s = null;
// a length of -1 indicates that the string is null.
if (-1 != n)
{
var buff = CheckLength(n);
s = Encoding.UTF8.GetString(buff.Array, buff.Offset, n);
}
Trace("--Read string '{0}'", s);
return s;
}
/// <summary> Read the next bytes from the stream. </summary>
/// <param name="count">Number of bytes to read.</param>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public byte[] ReadBytes(int count)
{
if (count == 0)
{
return new byte[0];
}
bool safeToUse;
var buff = CheckLength(count, out safeToUse);
Trace("--Read byte array of length {0}", count);
if (!safeToUse)
{
var result = new byte[count];
Array.Copy(buff.Array, buff.Offset, result, 0, count);
return result;
}
else
{
return buff.Array;
}
}
/// <summary> Read the next bytes from the stream. </summary>
/// <param name="destination">Output array to store the returned data in.</param>
/// <param name="offset">Offset into the destination array to write to.</param>
/// <param name="count">Number of bytes to read.</param>
public void ReadByteArray(byte[] destination, int offset, int count)
{
if (offset + count > destination.Length)
{
throw new ArgumentOutOfRangeException("count", "Reading into an array that is too small");
}
var buff = CheckLength(count);
Buffer.BlockCopy(buff.Array, buff.Offset, destination, offset, count);
}
/// <summary> Read an <c>char</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public char ReadChar()
{
Trace("--Read char");
return Convert.ToChar(ReadShort());
}
/// <summary> Read an <c>byte</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public byte ReadByte()
{
var buff = CheckLength(1);
Trace("--Read byte");
return buff.Array[buff.Offset];
}
/// <summary> Read an <c>sbyte</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public sbyte ReadSByte()
{
var buff = CheckLength(1);
Trace("--Read sbyte");
return unchecked((sbyte)(buff.Array[buff.Offset]));
}
/// <summary> Read an <c>IPAddress</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public IPAddress ReadIPAddress()
{
var buff = CheckLength(16);
bool v4 = true;
for (var i = 0; i < 12; i++)
{
if (buff.Array[buff.Offset + i] != 0)
{
v4 = false;
break;
}
}
if (v4)
{
var v4Bytes = new byte[4];
for (var i = 0; i < 4; i++)
{
v4Bytes[i] = buff.Array[buff.Offset + 12 + i];
}
return new IPAddress(v4Bytes);
}
else
{
var v6Bytes = new byte[16];
for (var i = 0; i < 16; i++)
{
v6Bytes[i] = buff.Array[buff.Offset + i];
}
return new IPAddress(v6Bytes);
}
}
/// <summary> Read an <c>IPEndPoint</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public IPEndPoint ReadIPEndPoint()
{
var addr = ReadIPAddress();
var port = ReadInt();
return new IPEndPoint(addr, port);
}
/// <summary> Read an <c>SiloAddress</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public SiloAddress ReadSiloAddress()
{
var ep = ReadIPEndPoint();
var gen = ReadInt();
return SiloAddress.New(ep, gen);
}
/// <summary> Read an <c>GrainId</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
internal GrainId ReadGrainId()
{
UniqueKey key = ReadUniqueKey();
return GrainId.GetGrainId(key);
}
/// <summary> Read an <c>ActivationId</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
internal ActivationId ReadActivationId()
{
UniqueKey key = ReadUniqueKey();
return ActivationId.GetActivationId(key);
}
internal UniqueKey ReadUniqueKey()
{
ulong n0 = ReadULong();
ulong n1 = ReadULong();
ulong typeCodeData = ReadULong();
string keyExt = ReadString();
return UniqueKey.NewKey(n0, n1, typeCodeData, keyExt);
}
internal Guid ReadGuid()
{
byte[] bytes = ReadBytes(16);
return new Guid(bytes);
}
/// <summary> Read an <c>ActivationAddress</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
internal ActivationAddress ReadActivationAddress()
{
var silo = ReadSiloAddress();
var grain = ReadGrainId();
var act = ReadActivationId();
if (silo.Equals(SiloAddress.Zero))
silo = null;
if (act.Equals(ActivationId.Zero))
act = null;
return ActivationAddress.GetAddress(silo, grain, act);
}
/// <summary>
/// Read a block of data into the specified output <c>Array</c>.
/// </summary>
/// <param name="array">Array to output the data to.</param>
/// <param name="n">Number of bytes to read.</param>
public void ReadBlockInto(Array array, int n)
{
var buff = CheckLength(n);
Buffer.BlockCopy(buff.Array, buff.Offset, array, 0, n);
Trace("--Read block of {0} bytes", n);
}
/// <summary>
/// Peek at the next token in this input stream.
/// </summary>
/// <returns>Next token thatr will be read from the stream.</returns>
internal SerializationTokenType PeekToken()
{
if (currentOffset == currentSegment.Count + currentSegment.Offset)
StartNextSegment();
return (SerializationTokenType)currentBuffer[currentOffset];
}
/// <summary> Read a <c>SerializationTokenType</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
internal SerializationTokenType ReadToken()
{
var buff = CheckLength(1);
Trace("--Read token {0}", (SerializationTokenType)buff.Array[buff.Offset]);
return (SerializationTokenType)buff.Array[buff.Offset];
}
internal bool TryReadSimpleType(out object result, out SerializationTokenType token)
{
token = ReadToken();
byte[] bytes;
switch (token)
{
case SerializationTokenType.True:
result = true;
break;
case SerializationTokenType.False:
result = false;
break;
case SerializationTokenType.Null:
result = null;
break;
case SerializationTokenType.Object:
result = new object();
break;
case SerializationTokenType.Int:
result = ReadInt();
break;
case SerializationTokenType.Uint:
result = ReadUInt();
break;
case SerializationTokenType.Short:
result = ReadShort();
break;
case SerializationTokenType.Ushort:
result = ReadUShort();
break;
case SerializationTokenType.Long:
result = ReadLong();
break;
case SerializationTokenType.Ulong:
result = ReadULong();
break;
case SerializationTokenType.Byte:
result = ReadByte();
break;
case SerializationTokenType.Sbyte:
result = ReadSByte();
break;
case SerializationTokenType.Float:
result = ReadFloat();
break;
case SerializationTokenType.Double:
result = ReadDouble();
break;
case SerializationTokenType.Decimal:
result = ReadDecimal();
break;
case SerializationTokenType.String:
result = ReadString();
break;
case SerializationTokenType.Character:
result = ReadChar();
break;
case SerializationTokenType.Guid:
bytes = ReadBytes(16);
result = new Guid(bytes);
break;
case SerializationTokenType.Date:
result = DateTime.FromBinary(ReadLong());
break;
case SerializationTokenType.TimeSpan:
result = new TimeSpan(ReadLong());
break;
case SerializationTokenType.GrainId:
result = ReadGrainId();
break;
case SerializationTokenType.ActivationId:
result = ReadActivationId();
break;
case SerializationTokenType.SiloAddress:
result = ReadSiloAddress();
break;
case SerializationTokenType.ActivationAddress:
result = ReadActivationAddress();
break;
case SerializationTokenType.IpAddress:
result = ReadIPAddress();
break;
case SerializationTokenType.IpEndPoint:
result = ReadIPEndPoint();
break;
case SerializationTokenType.CorrelationId:
result = new CorrelationId(ReadBytes(CorrelationId.SIZE_BYTES));
break;
default:
result = null;
return false;
}
return true;
}
/// <summary> Read a <c>Type</c> value from the stream. </summary>
/// <param name="expected">Expected Type, if known.</param>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public Type ReadFullTypeHeader(Type expected = null)
{
var token = ReadToken();
if (token == SerializationTokenType.ExpectedType)
{
return expected;
}
var t = CheckSpecialTypeCode(token);
if (t != null)
{
return t;
}
if (token == SerializationTokenType.SpecifiedType)
{
#if TRACE_SERIALIZATION
var tt = ReadSpecifiedTypeHeader();
Trace("--Read specified type header for type {0}", tt);
return tt;
#else
return ReadSpecifiedTypeHeader();
#endif
}
throw new SerializationException("Invalid '" + token + "'token in input stream where full type header is expected");
}
internal static Type CheckSpecialTypeCode(SerializationTokenType token)
{
switch (token)
{
case SerializationTokenType.Boolean:
return typeof(bool);
case SerializationTokenType.Int:
return typeof(int);
case SerializationTokenType.Short:
return typeof(short);
case SerializationTokenType.Long:
return typeof(long);
case SerializationTokenType.Sbyte:
return typeof(sbyte);
case SerializationTokenType.Uint:
return typeof(uint);
case SerializationTokenType.Ushort:
return typeof(ushort);
case SerializationTokenType.Ulong:
return typeof(ulong);
case SerializationTokenType.Byte:
return typeof(byte);
case SerializationTokenType.Float:
return typeof(float);
case SerializationTokenType.Double:
return typeof(double);
case SerializationTokenType.Decimal:
return typeof(decimal);
case SerializationTokenType.String:
return typeof(string);
case SerializationTokenType.Character:
return typeof(char);
case SerializationTokenType.Guid:
return typeof(Guid);
case SerializationTokenType.Date:
return typeof(DateTime);
case SerializationTokenType.TimeSpan:
return typeof(TimeSpan);
case SerializationTokenType.IpAddress:
return typeof(IPAddress);
case SerializationTokenType.IpEndPoint:
return typeof(IPEndPoint);
case SerializationTokenType.GrainId:
return typeof(GrainId);
case SerializationTokenType.ActivationId:
return typeof(ActivationId);
case SerializationTokenType.SiloAddress:
return typeof(SiloAddress);
case SerializationTokenType.ActivationAddress:
return typeof(ActivationAddress);
case SerializationTokenType.CorrelationId:
return typeof(CorrelationId);
#if false // Note: not yet implemented as simple types on the Writer side
case SerializationTokenType.Object:
return typeof(Object);
case SerializationTokenType.ByteArray:
return typeof(byte[]);
case SerializationTokenType.ShortArray:
return typeof(short[]);
case SerializationTokenType.IntArray:
return typeof(int[]);
case SerializationTokenType.LongArray:
return typeof(long[]);
case SerializationTokenType.UShortArray:
return typeof(ushort[]);
case SerializationTokenType.UIntArray:
return typeof(uint[]);
case SerializationTokenType.ULongArray:
return typeof(ulong[]);
case SerializationTokenType.FloatArray:
return typeof(float[]);
case SerializationTokenType.DoubleArray:
return typeof(double[]);
case SerializationTokenType.CharArray:
return typeof(char[]);
case SerializationTokenType.BoolArray:
return typeof(bool[]);
#endif
default:
break;
}
return null;
}
/// <summary> Read a <c>Type</c> value from the stream. </summary>
internal Type ReadSpecifiedTypeHeader()
{
// Assumes that the SpecifiedType token has already been read
var token = ReadToken();
switch (token)
{
case SerializationTokenType.Boolean:
return typeof(bool);
case SerializationTokenType.Int:
return typeof(int);
case SerializationTokenType.Short:
return typeof(short);
case SerializationTokenType.Long:
return typeof(long);
case SerializationTokenType.Sbyte:
return typeof(sbyte);
case SerializationTokenType.Uint:
return typeof(uint);
case SerializationTokenType.Ushort:
return typeof(ushort);
case SerializationTokenType.Ulong:
return typeof(ulong);
case SerializationTokenType.Byte:
return typeof(byte);
case SerializationTokenType.Float:
return typeof(float);
case SerializationTokenType.Double:
return typeof(double);
case SerializationTokenType.Decimal:
return typeof(decimal);
case SerializationTokenType.String:
return typeof(string);
case SerializationTokenType.Character:
return typeof(char);
case SerializationTokenType.Guid:
return typeof(Guid);
case SerializationTokenType.Date:
return typeof(DateTime);
case SerializationTokenType.TimeSpan:
return typeof(TimeSpan);
case SerializationTokenType.IpAddress:
return typeof(IPAddress);
case SerializationTokenType.IpEndPoint:
return typeof(IPEndPoint);
case SerializationTokenType.GrainId:
return typeof(GrainId);
case SerializationTokenType.ActivationId:
return typeof(ActivationId);
case SerializationTokenType.SiloAddress:
return typeof(SiloAddress);
case SerializationTokenType.ActivationAddress:
return typeof(ActivationAddress);
case SerializationTokenType.CorrelationId:
return typeof(CorrelationId);
case SerializationTokenType.Request:
return typeof(InvokeMethodRequest);
case SerializationTokenType.Response:
return typeof(Response);
case SerializationTokenType.StringObjDict:
return typeof(Dictionary<string, object>);
case SerializationTokenType.Object:
return typeof(Object);
case SerializationTokenType.Tuple + 1:
Trace("----Reading type info for a Tuple'1");
return typeof(Tuple<>).MakeGenericType(ReadGenericArguments(1));
case SerializationTokenType.Tuple + 2:
Trace("----Reading type info for a Tuple'2");
return typeof(Tuple<,>).MakeGenericType(ReadGenericArguments(2));
case SerializationTokenType.Tuple + 3:
Trace("----Reading type info for a Tuple'3");
return typeof(Tuple<,,>).MakeGenericType(ReadGenericArguments(3));
case SerializationTokenType.Tuple + 4:
Trace("----Reading type info for a Tuple'4");
return typeof(Tuple<,,,>).MakeGenericType(ReadGenericArguments(4));
case SerializationTokenType.Tuple + 5:
Trace("----Reading type info for a Tuple'5");
return typeof(Tuple<,,,,>).MakeGenericType(ReadGenericArguments(5));
case SerializationTokenType.Tuple + 6:
Trace("----Reading type info for a Tuple'6");
return typeof(Tuple<,,,,,>).MakeGenericType(ReadGenericArguments(6));
case SerializationTokenType.Tuple + 7:
Trace("----Reading type info for a Tuple'7");
return typeof(Tuple<,,,,,,>).MakeGenericType(ReadGenericArguments(7));
case SerializationTokenType.Array + 1:
var et1 = ReadFullTypeHeader();
return et1.MakeArrayType();
case SerializationTokenType.Array + 2:
var et2 = ReadFullTypeHeader();
return et2.MakeArrayType(2);
case SerializationTokenType.Array + 3:
var et3 = ReadFullTypeHeader();
return et3.MakeArrayType(3);
case SerializationTokenType.Array + 4:
var et4 = ReadFullTypeHeader();
return et4.MakeArrayType(4);
case SerializationTokenType.Array + 5:
var et5 = ReadFullTypeHeader();
return et5.MakeArrayType(5);
case SerializationTokenType.Array + 6:
var et6 = ReadFullTypeHeader();
return et6.MakeArrayType(6);
case SerializationTokenType.Array + 7:
var et7 = ReadFullTypeHeader();
return et7.MakeArrayType(7);
case SerializationTokenType.Array + 8:
var et8 = ReadFullTypeHeader();
return et8.MakeArrayType(8);
case SerializationTokenType.List:
return typeof(List<>).MakeGenericType(ReadGenericArguments(1));
case SerializationTokenType.Dictionary:
return typeof(Dictionary<,>).MakeGenericType(ReadGenericArguments(2));
case SerializationTokenType.KeyValuePair:
return typeof(KeyValuePair<,>).MakeGenericType(ReadGenericArguments(2));
case SerializationTokenType.Set:
return typeof(HashSet<>).MakeGenericType(ReadGenericArguments(1));
case SerializationTokenType.SortedList:
return typeof(SortedList<,>).MakeGenericType(ReadGenericArguments(2));
case SerializationTokenType.SortedSet:
return typeof(SortedSet<>).MakeGenericType(ReadGenericArguments(1));
case SerializationTokenType.Stack:
return typeof(Stack<>).MakeGenericType(ReadGenericArguments(1));
case SerializationTokenType.Queue:
return typeof(Queue<>).MakeGenericType(ReadGenericArguments(1));
case SerializationTokenType.LinkedList:
return typeof(LinkedList<>).MakeGenericType(ReadGenericArguments(1));
case SerializationTokenType.Nullable:
return typeof(Nullable<>).MakeGenericType(ReadGenericArguments(1));
case SerializationTokenType.ByteArray:
return typeof(byte[]);
case SerializationTokenType.ShortArray:
return typeof(short[]);
case SerializationTokenType.IntArray:
return typeof(int[]);
case SerializationTokenType.LongArray:
return typeof(long[]);
case SerializationTokenType.UShortArray:
return typeof(ushort[]);
case SerializationTokenType.UIntArray:
return typeof(uint[]);
case SerializationTokenType.ULongArray:
return typeof(ulong[]);
case SerializationTokenType.FloatArray:
return typeof(float[]);
case SerializationTokenType.DoubleArray:
return typeof(double[]);
case SerializationTokenType.CharArray:
return typeof(char[]);
case SerializationTokenType.BoolArray:
return typeof(bool[]);
case SerializationTokenType.NamedType:
var typeName = ReadString();
try
{
return SerializationManager.ResolveTypeName(typeName);
}
catch (TypeAccessException ex)
{
throw new TypeAccessException("Named type \"" + typeName + "\" is invalid: " + ex.Message);
}
default:
break;
}
throw new SerializationException("Unexpected '" + token + "' found when expecting a type reference");
}
private Type[] ReadGenericArguments(int n)
{
Trace("About to read {0} generic arguments", n);
var args = new Type[n];
for (var i = 0; i < n; i++)
{
args[i] = ReadFullTypeHeader();
}
Trace("Finished reading {0} generic arguments", n);
return args;
}
private StreamWriter trace;
[Conditional("TRACE_SERIALIZATION")]
private void Trace(string format, params object[] args)
{
if (trace == null)
{
var path = String.Format("d:\\Trace-{0}.{1}.{2}.txt", DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, DateTime.UtcNow.Ticks);
Console.WriteLine("Opening trace file at '{0}'", path);
trace = File.CreateText(path);
}
trace.Write(format, args);
trace.WriteLine(" at offset {0}", CurrentPosition);
trace.Flush();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace HTTPOptions.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// 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.Diagnostics;
using System.Globalization;
using System.Text;
using Roslyn.Utilities;
using Microsoft.Build.Framework;
using Microsoft.Build.Tasks.Hosting;
using Microsoft.Build.Utilities;
using Microsoft.CodeAnalysis.CommandLine;
namespace Microsoft.CodeAnalysis.BuildTasks
{
/// <summary>
/// This class defines the "Csc" XMake task, which enables building assemblies from C#
/// source files by invoking the C# compiler. This is the new Roslyn XMake task,
/// meaning that the code is compiled by using the Roslyn compiler server, rather
/// than csc.exe. The two should be functionally identical, but the compiler server
/// should be significantly faster with larger projects and have a smaller memory
/// footprint.
/// </summary>
public class Csc : ManagedCompiler
{
#region Properties
// Please keep these alphabetized. These are the parameters specific to Csc. The
// ones shared between Vbc and Csc are defined in ManagedCompiler.cs, which is
// the base class.
public bool AllowUnsafeBlocks
{
set { _store[nameof(AllowUnsafeBlocks)] = value; }
get { return _store.GetOrDefault(nameof(AllowUnsafeBlocks), false); }
}
public string ApplicationConfiguration
{
set { _store[nameof(ApplicationConfiguration)] = value; }
get { return (string)_store[nameof(ApplicationConfiguration)]; }
}
public string BaseAddress
{
set { _store[nameof(BaseAddress)] = value; }
get { return (string)_store[nameof(BaseAddress)]; }
}
public bool CheckForOverflowUnderflow
{
set { _store[nameof(CheckForOverflowUnderflow)] = value; }
get { return _store.GetOrDefault(nameof(CheckForOverflowUnderflow), false); }
}
public string DocumentationFile
{
set { _store[nameof(DocumentationFile)] = value; }
get { return (string)_store[nameof(DocumentationFile)]; }
}
public string DisabledWarnings
{
set { _store[nameof(DisabledWarnings)] = value; }
get { return (string)_store[nameof(DisabledWarnings)]; }
}
public bool ErrorEndLocation
{
set { _store[nameof(ErrorEndLocation)] = value; }
get { return _store.GetOrDefault(nameof(ErrorEndLocation), false); }
}
public string ErrorReport
{
set { _store[nameof(ErrorReport)] = value; }
get { return (string)_store[nameof(ErrorReport)]; }
}
public bool GenerateFullPaths
{
set { _store[nameof(GenerateFullPaths)] = value; }
get { return _store.GetOrDefault(nameof(GenerateFullPaths), false); }
}
public string LangVersion
{
set { _store[nameof(LangVersion)] = value; }
get { return (string)_store[nameof(LangVersion)]; }
}
public string ModuleAssemblyName
{
set { _store[nameof(ModuleAssemblyName)] = value; }
get { return (string)_store[nameof(ModuleAssemblyName)]; }
}
public bool NoStandardLib
{
set { _store[nameof(NoStandardLib)] = value; }
get { return _store.GetOrDefault(nameof(NoStandardLib), false); }
}
public string PdbFile
{
set { _store[nameof(PdbFile)] = value; }
get { return (string)_store[nameof(PdbFile)]; }
}
/// <summary>
/// Name of the language passed to "/preferreduilang" compiler option.
/// </summary>
/// <remarks>
/// If set to null, "/preferreduilang" option is omitted, and csc.exe uses its default setting.
/// Otherwise, the value is passed to "/preferreduilang" as is.
/// </remarks>
public string PreferredUILang
{
set { _store[nameof(PreferredUILang)] = value; }
get { return (string)_store[nameof(PreferredUILang)]; }
}
public string VsSessionGuid
{
set { _store[nameof(VsSessionGuid)] = value; }
get { return (string)_store[nameof(VsSessionGuid)]; }
}
public bool UseHostCompilerIfAvailable
{
set { _store[nameof(UseHostCompilerIfAvailable)] = value; }
get { return _store.GetOrDefault(nameof(UseHostCompilerIfAvailable), false); }
}
public int WarningLevel
{
set { _store[nameof(WarningLevel)] = value; }
get { return _store.GetOrDefault(nameof(WarningLevel), 4); }
}
public string WarningsAsErrors
{
set { _store[nameof(WarningsAsErrors)] = value; }
get { return (string)_store[nameof(WarningsAsErrors)]; }
}
public string WarningsNotAsErrors
{
set { _store[nameof(WarningsNotAsErrors)] = value; }
get { return (string)_store[nameof(WarningsNotAsErrors)]; }
}
#endregion
#region Tool Members
private static readonly string[] s_separators = { "\r\n" };
internal override void LogMessages(string output, MessageImportance messageImportance)
{
var lines = output.Split(s_separators, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
string trimmedMessage = line.Trim();
if (trimmedMessage != "")
{
Log.LogMessageFromText(trimmedMessage, messageImportance);
}
}
}
/// <summary>
/// Return the name of the tool to execute.
/// </summary>
override protected string ToolName
{
get
{
return "csc.exe";
}
}
/// <summary>
/// Return the path to the tool to execute.
/// </summary>
protected override string GenerateFullPathToTool()
{
string pathToTool = ToolLocationHelper.GetPathToBuildToolsFile(ToolName, ToolLocationHelper.CurrentToolsVersion);
if (null == pathToTool)
{
pathToTool = ToolLocationHelper.GetPathToDotNetFrameworkFile(ToolName, TargetDotNetFrameworkVersion.VersionLatest);
if (null == pathToTool)
{
Log.LogErrorWithCodeFromResources("General_FrameworksFileNotFound", ToolName, ToolLocationHelper.GetDotNetFrameworkVersionFolderPrefix(TargetDotNetFrameworkVersion.VersionLatest));
}
}
return pathToTool;
}
/// <summary>
/// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file.
/// </summary>
protected internal override void AddResponseFileCommands(CommandLineBuilderExtension commandLine)
{
commandLine.AppendSwitchIfNotNull("/lib:", AdditionalLibPaths, ",");
commandLine.AppendPlusOrMinusSwitch("/unsafe", _store, nameof(AllowUnsafeBlocks));
commandLine.AppendPlusOrMinusSwitch("/checked", _store, nameof(CheckForOverflowUnderflow));
commandLine.AppendSwitchWithSplitting("/nowarn:", DisabledWarnings, ",", ';', ',');
commandLine.AppendWhenTrue("/fullpaths", _store, nameof(GenerateFullPaths));
commandLine.AppendSwitchIfNotNull("/langversion:", LangVersion);
commandLine.AppendSwitchIfNotNull("/moduleassemblyname:", ModuleAssemblyName);
commandLine.AppendSwitchIfNotNull("/pdb:", PdbFile);
commandLine.AppendPlusOrMinusSwitch("/nostdlib", _store, nameof(NoStandardLib));
commandLine.AppendSwitchIfNotNull("/platform:", PlatformWith32BitPreference);
commandLine.AppendSwitchIfNotNull("/errorreport:", ErrorReport);
commandLine.AppendSwitchWithInteger("/warn:", _store, nameof(WarningLevel));
commandLine.AppendSwitchIfNotNull("/doc:", DocumentationFile);
commandLine.AppendSwitchIfNotNull("/baseaddress:", BaseAddress);
commandLine.AppendSwitchUnquotedIfNotNull("/define:", GetDefineConstantsSwitch(DefineConstants, Log));
commandLine.AppendSwitchIfNotNull("/win32res:", Win32Resource);
commandLine.AppendSwitchIfNotNull("/main:", MainEntryPoint);
commandLine.AppendSwitchIfNotNull("/appconfig:", ApplicationConfiguration);
commandLine.AppendWhenTrue("/errorendlocation", _store, nameof(ErrorEndLocation));
commandLine.AppendSwitchIfNotNull("/preferreduilang:", PreferredUILang);
commandLine.AppendPlusOrMinusSwitch("/highentropyva", _store, nameof(HighEntropyVA));
// If not design time build and the globalSessionGuid property was set then add a -globalsessionguid:<guid>
bool designTime = false;
if (HostObject != null)
{
var csHost = HostObject as ICscHostObject;
designTime = csHost.IsDesignTime();
}
if (!designTime)
{
if (!string.IsNullOrWhiteSpace(VsSessionGuid))
{
commandLine.AppendSwitchIfNotNull("/sqmsessionguid:", VsSessionGuid);
}
}
AddReferencesToCommandLine(commandLine, References);
base.AddResponseFileCommands(commandLine);
// This should come after the "TreatWarningsAsErrors" flag is processed (in managedcompiler.cs).
// Because if TreatWarningsAsErrors=false, then we'll have a /warnaserror- on the command-line,
// and then any specific warnings that should be treated as errors should be specified with
// /warnaserror+:<list> after the /warnaserror- switch. The order of the switches on the command-line
// does matter.
//
// Note that
// /warnaserror+
// is just shorthand for:
// /warnaserror+:<all possible warnings>
//
// Similarly,
// /warnaserror-
// is just shorthand for:
// /warnaserror-:<all possible warnings>
commandLine.AppendSwitchWithSplitting("/warnaserror+:", WarningsAsErrors, ",", ';', ',');
commandLine.AppendSwitchWithSplitting("/warnaserror-:", WarningsNotAsErrors, ",", ';', ',');
// It's a good idea for the response file to be the very last switch passed, just
// from a predictability perspective. It also solves the problem that a dogfooder
// ran into, which is described in an email thread attached to bug VSWhidbey 146883.
// See also bugs 177762 and 118307 for additional bugs related to response file position.
if (ResponseFiles != null)
{
foreach (ITaskItem response in ResponseFiles)
{
commandLine.AppendSwitchIfNotNull("@", response.ItemSpec);
}
}
}
#endregion
internal override RequestLanguage Language => RequestLanguage.CSharpCompile;
/// <summary>
/// The C# compiler (starting with Whidbey) supports assembly aliasing for references.
/// See spec at http://devdiv/spectool/Documents/Whidbey/VCSharp/Design%20Time/M3%20DCRs/DCR%20Assembly%20aliases.doc.
/// This method handles the necessary work of looking at the "Aliases" attribute on
/// the incoming "References" items, and making sure to generate the correct
/// command-line on csc.exe. The syntax for aliasing a reference is:
/// csc.exe /reference:Foo=System.Xml.dll
///
/// The "Aliases" attribute on the "References" items is actually a comma-separated
/// list of aliases, and if any of the aliases specified is the string "global",
/// then we add that reference to the command-line without an alias.
/// </summary>
internal static void AddReferencesToCommandLine(
CommandLineBuilderExtension commandLine,
ITaskItem[] references,
bool isInteractive = false)
{
// If there were no references passed in, don't add any /reference: switches
// on the command-line.
if (references == null)
{
return;
}
// Loop through all the references passed in. We'll be adding separate
// /reference: switches for each reference, and in some cases even multiple
// /reference: switches per reference.
foreach (ITaskItem reference in references)
{
// See if there was an "Alias" attribute on the reference.
string aliasString = reference.GetMetadata("Aliases");
string switchName = "/reference:";
if (!isInteractive)
{
bool embed = Utilities.TryConvertItemMetadataToBool(reference,
"EmbedInteropTypes");
if (embed)
{
switchName = "/link:";
}
}
if (string.IsNullOrEmpty(aliasString))
{
// If there was no "Alias" attribute, just add this as a global reference.
commandLine.AppendSwitchIfNotNull(switchName, reference.ItemSpec);
}
else
{
// If there was an "Alias" attribute, it contains a comma-separated list
// of aliases to use for this reference. For each one of those aliases,
// we're going to add a separate /reference: switch to the csc.exe
// command-line
string[] aliases = aliasString.Split(',');
foreach (string alias in aliases)
{
// Trim whitespace.
string trimmedAlias = alias.Trim();
if (alias.Length == 0)
{
continue;
}
// The alias should be a valid C# identifier. Therefore it cannot
// contain comma, space, semicolon, or double-quote. Let's check for
// the existence of those characters right here, and bail immediately
// if any are present. There are a whole bunch of other characters
// that are not allowed in a C# identifier, but we'll just let csc.exe
// error out on those. The ones we're checking for here are the ones
// that could seriously screw up the command-line parsing or could
// allow parameter injection.
if (trimmedAlias.IndexOfAny(new char[] { ',', ' ', ';', '"' }) != -1)
{
throw Utilities.GetLocalizedArgumentException(
ErrorString.Csc_AssemblyAliasContainsIllegalCharacters,
reference.ItemSpec,
trimmedAlias);
}
// The alias called "global" is special. It means that we don't
// give it an alias on the command-line.
if (string.Compare("global", trimmedAlias, StringComparison.OrdinalIgnoreCase) == 0)
{
commandLine.AppendSwitchIfNotNull(switchName, reference.ItemSpec);
}
else
{
// We have a valid (and explicit) alias for this reference. Add
// it to the command-line using the syntax:
// /reference:Foo=System.Xml.dll
commandLine.AppendSwitchAliased(switchName, trimmedAlias, reference.ItemSpec);
}
}
}
}
}
/// <summary>
/// Old VS projects had some pretty messed-up looking values for the
/// "DefineConstants" property. It worked fine in the IDE, because it
/// effectively munged up the string so that it ended up being valid for
/// the compiler. We do the equivalent munging here now.
///
/// Basically, we take the incoming string, and split it on comma/semicolon/space.
/// Then we look at the resulting list of strings, and remove any that are
/// illegal identifiers, and pass the remaining ones through to the compiler.
///
/// Note that CSharp does support assigning a value to the constants ... in
/// other words, a constant is either defined or not defined ... it can't have
/// an actual value.
/// </summary>
internal static string GetDefineConstantsSwitch(string originalDefineConstants, TaskLoggingHelper log)
{
if (originalDefineConstants == null)
{
return null;
}
StringBuilder finalDefineConstants = new StringBuilder();
// Split the incoming string on comma/semicolon/space.
string[] allIdentifiers = originalDefineConstants.Split(new char[] { ',', ';', ' ' });
// Loop through all the parts, and for the ones that are legal C# identifiers,
// add them to the outgoing string.
foreach (string singleIdentifier in allIdentifiers)
{
if (UnicodeCharacterUtilities.IsValidIdentifier(singleIdentifier))
{
// Separate them with a semicolon if there's something already in
// the outgoing string.
if (finalDefineConstants.Length > 0)
{
finalDefineConstants.Append(";");
}
finalDefineConstants.Append(singleIdentifier);
}
else if (singleIdentifier.Length > 0)
{
log.LogWarningWithCodeFromResources("Csc_InvalidParameterWarning", "/define:", singleIdentifier);
}
}
if (finalDefineConstants.Length > 0)
{
return finalDefineConstants.ToString();
}
else
{
// We wouldn't want to pass in an empty /define: switch on the csc.exe command-line.
return null;
}
}
/// <summary>
/// This method will initialize the host compiler object with all the switches,
/// parameters, resources, references, sources, etc.
///
/// It returns true if everything went according to plan. It returns false if the
/// host compiler had a problem with one of the parameters that was passed in.
///
/// This method also sets the "this.HostCompilerSupportsAllParameters" property
/// accordingly.
///
/// Example:
/// If we attempted to pass in WarningLevel="9876", then this method would
/// set HostCompilerSupportsAllParameters=true, but it would give a
/// return value of "false". This is because the host compiler fully supports
/// the WarningLevel parameter, but 9876 happens to be an illegal value.
///
/// Example:
/// If we attempted to pass in NoConfig=false, then this method would set
/// HostCompilerSupportsAllParameters=false, because while this is a legal
/// thing for csc.exe, the IDE compiler cannot support it. In this situation
/// the return value will also be false.
/// </summary>
/// <owner>RGoel</owner>
private bool InitializeHostCompiler(ICscHostObject cscHostObject)
{
bool success;
HostCompilerSupportsAllParameters = UseHostCompilerIfAvailable;
string param = "Unknown";
try
{
// Need to set these separately, because they don't require a CommitChanges to the C# compiler in the IDE.
CheckHostObjectSupport(param = nameof(LinkResources), cscHostObject.SetLinkResources(LinkResources));
CheckHostObjectSupport(param = nameof(References), cscHostObject.SetReferences(References));
CheckHostObjectSupport(param = nameof(Resources), cscHostObject.SetResources(Resources));
CheckHostObjectSupport(param = nameof(Sources), cscHostObject.SetSources(Sources));
// For host objects which support it, pass the list of analyzers.
IAnalyzerHostObject analyzerHostObject = cscHostObject as IAnalyzerHostObject;
if (analyzerHostObject != null)
{
CheckHostObjectSupport(param = nameof(Analyzers), analyzerHostObject.SetAnalyzers(Analyzers));
}
}
catch (Exception e)
{
Log.LogErrorWithCodeFromResources("General_CouldNotSetHostObjectParameter", param, e.Message);
return false;
}
try
{
param = nameof(cscHostObject.BeginInitialization);
cscHostObject.BeginInitialization();
CheckHostObjectSupport(param = nameof(AdditionalLibPaths), cscHostObject.SetAdditionalLibPaths(AdditionalLibPaths));
CheckHostObjectSupport(param = nameof(AddModules), cscHostObject.SetAddModules(AddModules));
CheckHostObjectSupport(param = nameof(AllowUnsafeBlocks), cscHostObject.SetAllowUnsafeBlocks(AllowUnsafeBlocks));
CheckHostObjectSupport(param = nameof(BaseAddress), cscHostObject.SetBaseAddress(BaseAddress));
CheckHostObjectSupport(param = nameof(CheckForOverflowUnderflow), cscHostObject.SetCheckForOverflowUnderflow(CheckForOverflowUnderflow));
CheckHostObjectSupport(param = nameof(CodePage), cscHostObject.SetCodePage(CodePage));
// These two -- EmitDebugInformation and DebugType -- must go together, with DebugType
// getting set last, because it is more specific.
CheckHostObjectSupport(param = nameof(EmitDebugInformation), cscHostObject.SetEmitDebugInformation(EmitDebugInformation));
CheckHostObjectSupport(param = nameof(DebugType), cscHostObject.SetDebugType(DebugType));
CheckHostObjectSupport(param = nameof(DefineConstants), cscHostObject.SetDefineConstants(GetDefineConstantsSwitch(DefineConstants, Log)));
CheckHostObjectSupport(param = nameof(DelaySign), cscHostObject.SetDelaySign((_store["DelaySign"] != null), DelaySign));
CheckHostObjectSupport(param = nameof(DisabledWarnings), cscHostObject.SetDisabledWarnings(DisabledWarnings));
CheckHostObjectSupport(param = nameof(DocumentationFile), cscHostObject.SetDocumentationFile(DocumentationFile));
CheckHostObjectSupport(param = nameof(ErrorReport), cscHostObject.SetErrorReport(ErrorReport));
CheckHostObjectSupport(param = nameof(FileAlignment), cscHostObject.SetFileAlignment(FileAlignment));
CheckHostObjectSupport(param = nameof(GenerateFullPaths), cscHostObject.SetGenerateFullPaths(GenerateFullPaths));
CheckHostObjectSupport(param = nameof(KeyContainer), cscHostObject.SetKeyContainer(KeyContainer));
CheckHostObjectSupport(param = nameof(KeyFile), cscHostObject.SetKeyFile(KeyFile));
CheckHostObjectSupport(param = nameof(LangVersion), cscHostObject.SetLangVersion(LangVersion));
CheckHostObjectSupport(param = nameof(MainEntryPoint), cscHostObject.SetMainEntryPoint(TargetType, MainEntryPoint));
CheckHostObjectSupport(param = nameof(ModuleAssemblyName), cscHostObject.SetModuleAssemblyName(ModuleAssemblyName));
CheckHostObjectSupport(param = nameof(NoConfig), cscHostObject.SetNoConfig(NoConfig));
CheckHostObjectSupport(param = nameof(NoStandardLib), cscHostObject.SetNoStandardLib(NoStandardLib));
CheckHostObjectSupport(param = nameof(Optimize), cscHostObject.SetOptimize(Optimize));
CheckHostObjectSupport(param = nameof(OutputAssembly), cscHostObject.SetOutputAssembly(OutputAssembly?.ItemSpec));
CheckHostObjectSupport(param = nameof(PdbFile), cscHostObject.SetPdbFile(PdbFile));
// For host objects which support it, set platform with 32BitPreference, HighEntropyVA, and SubsystemVersion
ICscHostObject4 cscHostObject4 = cscHostObject as ICscHostObject4;
if (cscHostObject4 != null)
{
CheckHostObjectSupport(param = nameof(PlatformWith32BitPreference), cscHostObject4.SetPlatformWith32BitPreference(PlatformWith32BitPreference));
CheckHostObjectSupport(param = nameof(HighEntropyVA), cscHostObject4.SetHighEntropyVA(HighEntropyVA));
CheckHostObjectSupport(param = nameof(SubsystemVersion), cscHostObject4.SetSubsystemVersion(SubsystemVersion));
}
else
{
CheckHostObjectSupport(param = nameof(Platform), cscHostObject.SetPlatform(Platform));
}
// For host objects which support it, set the analyzer ruleset and additional files.
IAnalyzerHostObject analyzerHostObject = cscHostObject as IAnalyzerHostObject;
if (analyzerHostObject != null)
{
CheckHostObjectSupport(param = nameof(CodeAnalysisRuleSet), analyzerHostObject.SetRuleSet(CodeAnalysisRuleSet));
CheckHostObjectSupport(param = nameof(AdditionalFiles), analyzerHostObject.SetAdditionalFiles(AdditionalFiles));
}
ICscHostObject5 cscHostObject5 = cscHostObject as ICscHostObject5;
if (cscHostObject5 != null)
{
CheckHostObjectSupport(param = nameof(ErrorLog), cscHostObject5.SetErrorLog(ErrorLog));
CheckHostObjectSupport(param = nameof(ReportAnalyzer), cscHostObject5.SetReportAnalyzer(ReportAnalyzer));
}
CheckHostObjectSupport(param = nameof(ResponseFiles), cscHostObject.SetResponseFiles(ResponseFiles));
CheckHostObjectSupport(param = nameof(TargetType), cscHostObject.SetTargetType(TargetType));
CheckHostObjectSupport(param = nameof(TreatWarningsAsErrors), cscHostObject.SetTreatWarningsAsErrors(TreatWarningsAsErrors));
CheckHostObjectSupport(param = nameof(WarningLevel), cscHostObject.SetWarningLevel(WarningLevel));
// This must come after TreatWarningsAsErrors.
CheckHostObjectSupport(param = nameof(WarningsAsErrors), cscHostObject.SetWarningsAsErrors(WarningsAsErrors));
// This must come after TreatWarningsAsErrors.
CheckHostObjectSupport(param = nameof(WarningsNotAsErrors), cscHostObject.SetWarningsNotAsErrors(WarningsNotAsErrors));
CheckHostObjectSupport(param = nameof(Win32Icon), cscHostObject.SetWin32Icon(Win32Icon));
// In order to maintain compatibility with previous host compilers, we must
// light-up for ICscHostObject2/ICscHostObject3
if (cscHostObject is ICscHostObject2)
{
ICscHostObject2 cscHostObject2 = (ICscHostObject2)cscHostObject;
CheckHostObjectSupport(param = nameof(Win32Manifest), cscHostObject2.SetWin32Manifest(GetWin32ManifestSwitch(NoWin32Manifest, Win32Manifest)));
}
else
{
// If we have been given a property that the host compiler doesn't support
// then we need to state that we are falling back to the command line compiler
if (!string.IsNullOrEmpty(Win32Manifest))
{
CheckHostObjectSupport(param = nameof(Win32Manifest), resultFromHostObjectSetOperation: false);
}
}
// This must come after Win32Manifest
CheckHostObjectSupport(param = nameof(Win32Resource), cscHostObject.SetWin32Resource(Win32Resource));
if (cscHostObject is ICscHostObject3)
{
ICscHostObject3 cscHostObject3 = (ICscHostObject3)cscHostObject;
CheckHostObjectSupport(param = nameof(ApplicationConfiguration), cscHostObject3.SetApplicationConfiguration(ApplicationConfiguration));
}
else
{
// If we have been given a property that the host compiler doesn't support
// then we need to state that we are falling back to the command line compiler
if (!string.IsNullOrEmpty(ApplicationConfiguration))
{
CheckHostObjectSupport(nameof(ApplicationConfiguration), resultFromHostObjectSetOperation: false);
}
}
InitializeHostObjectSupportForNewSwitches(cscHostObject, ref param);
// If we have been given a property value that the host compiler doesn't support
// then we need to state that we are falling back to the command line compiler.
// Null is supported because it means that option should be omitted, and compiler default used - obviously always valid.
// Explicitly specified name of current locale is also supported, since it is effectively a no-op.
// Other options are not supported since in-proc compiler always uses current locale.
if (!string.IsNullOrEmpty(PreferredUILang) && !string.Equals(PreferredUILang, System.Globalization.CultureInfo.CurrentUICulture.Name, StringComparison.OrdinalIgnoreCase))
{
CheckHostObjectSupport(nameof(PreferredUILang), resultFromHostObjectSetOperation: false);
}
}
catch (Exception e)
{
Log.LogErrorWithCodeFromResources("General_CouldNotSetHostObjectParameter", param, e.Message);
return false;
}
finally
{
int errorCode;
string errorMessage;
success = cscHostObject.EndInitialization(out errorMessage, out errorCode);
if (HostCompilerSupportsAllParameters)
{
// If the host compiler doesn't support everything we need, we're going to end up
// shelling out to the command-line compiler anyway. That means the command-line
// compiler will log the error. So here, we only log the error if we would've
// tried to use the host compiler.
// If EndInitialization returns false, then there was an error. If EndInitialization was
// successful, but there is a valid 'errorMessage,' interpret it as a warning.
if (!success)
{
Log.LogError(null, "CS" + errorCode.ToString("D4", CultureInfo.InvariantCulture), null, null, 0, 0, 0, 0, errorMessage);
}
else if (errorMessage != null && errorMessage.Length > 0)
{
Log.LogWarning(null, "CS" + errorCode.ToString("D4", CultureInfo.InvariantCulture), null, null, 0, 0, 0, 0, errorMessage);
}
}
}
return (success);
}
/// <summary>
/// This method will get called during Execute() if a host object has been passed into the Csc
/// task. Returns one of the following values to indicate what the next action should be:
/// UseHostObjectToExecute Host compiler exists and was initialized.
/// UseAlternateToolToExecute Host compiler doesn't exist or was not appropriate.
/// NoActionReturnSuccess Host compiler was already up-to-date, and we're done.
/// NoActionReturnFailure Bad parameters were passed into the task.
/// </summary>
/// <owner>RGoel</owner>
protected override HostObjectInitializationStatus InitializeHostObject()
{
if (HostObject != null)
{
// When the host object was passed into the task, it was passed in as a generic
// "Object" (because ITask interface obviously can't have any Csc-specific stuff
// in it, and each task is going to want to communicate with its host in a unique
// way). Now we cast it to the specific type that the Csc task expects. If the
// host object does not match this type, the host passed in an invalid host object
// to Csc, and we error out.
// NOTE: For compat reasons this must remain ICscHostObject
// we can dynamically test for smarter interfaces later..
using (RCWForCurrentContext<ICscHostObject> hostObject = new RCWForCurrentContext<ICscHostObject>(HostObject as ICscHostObject))
{
ICscHostObject cscHostObject = hostObject.RCW;
if (cscHostObject != null)
{
bool hostObjectSuccessfullyInitialized = InitializeHostCompiler(cscHostObject);
// If we're currently only in design-time (as opposed to build-time),
// then we're done. We've initialized the host compiler as best we
// can, and we certainly don't want to actually do the final compile.
// So return true, saying we're done and successful.
if (cscHostObject.IsDesignTime())
{
// If we are design-time then we do not want to continue the build at
// this time.
return hostObjectSuccessfullyInitialized ?
HostObjectInitializationStatus.NoActionReturnSuccess :
HostObjectInitializationStatus.NoActionReturnFailure;
}
if (!this.HostCompilerSupportsAllParameters)
{
// Since the host compiler has refused to take on the responsibility for this compilation,
// we're about to shell out to the command-line compiler to handle it. If some of the
// references don't exist on disk, we know the command-line compiler will fail, so save
// the trouble, and just throw a consistent error ourselves. This allows us to give
// more information than the compiler would, and also make things consistent across
// Vbc / Csc / etc. Actually, the real reason is bug 275726 (ddsuites\src\vs\env\vsproject\refs\ptp3).
// This suite behaves differently in localized builds than on English builds because
// VBC.EXE doesn't localize the word "error" when they emit errors and so we can't scan for it.
if (!CheckAllReferencesExistOnDisk())
{
return HostObjectInitializationStatus.NoActionReturnFailure;
}
// The host compiler doesn't support some of the switches/parameters
// being passed to it. Therefore, we resort to using the command-line compiler
// in this case.
UsedCommandLineTool = true;
return HostObjectInitializationStatus.UseAlternateToolToExecute;
}
// Ok, by now we validated that the host object supports the necessary switches
// and parameters. Last thing to check is whether the host object is up to date,
// and in that case, we will inform the caller that no further action is necessary.
if (hostObjectSuccessfullyInitialized)
{
return cscHostObject.IsUpToDate() ?
HostObjectInitializationStatus.NoActionReturnSuccess :
HostObjectInitializationStatus.UseHostObjectToExecute;
}
else
{
return HostObjectInitializationStatus.NoActionReturnFailure;
}
}
else
{
Log.LogErrorWithCodeFromResources("General_IncorrectHostObject", "Csc", "ICscHostObject");
}
}
}
// No appropriate host object was found.
UsedCommandLineTool = true;
return HostObjectInitializationStatus.UseAlternateToolToExecute;
}
/// <summary>
/// This method will get called during Execute() if a host object has been passed into the Csc
/// task. Returns true if the compilation succeeded, otherwise false.
/// </summary>
/// <owner>RGoel</owner>
protected override bool CallHostObjectToExecute()
{
Debug.Assert(HostObject != null, "We should not be here if the host object has not been set.");
ICscHostObject cscHostObject = HostObject as ICscHostObject;
Debug.Assert(cscHostObject != null, "Wrong kind of host object passed in!");
return cscHostObject.Compile();
}
}
}
| |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <[email protected]>
//
// 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.Reflection;
using System.Collections.Generic;
using FluentMigrator.Exceptions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Runner;
using FluentMigrator.Tests.Integration.Migrations;
using FluentMigrator.Tests.Unit.TaggingTestFakes;
using Moq;
using NUnit.Framework;
using NUnit.Should;
using System.Linq;
namespace FluentMigrator.Tests.Unit
{
[TestFixture]
public class DefaultMigrationInformationLoaderTests
{
[Test]
public void CanFindMigrationsInAssembly()
{
var conventions = new MigrationConventions();
var asm = Assembly.GetExecutingAssembly();
var loader = new DefaultMigrationInformationLoader( conventions, asm, "FluentMigrator.Tests.Integration.Migrations.Interleaved.Pass1", null);
SortedList<string, IMigrationInfo> migrationList = loader.LoadMigrations();
//if this works, there will be at least one migration class because i've included on in this code file
var en = migrationList.GetEnumerator();
int count = 0;
while (en.MoveNext())
count++;
count.ShouldBeGreaterThan(0);
}
[Test]
public void CanFindMigrationsInNamespace()
{
var conventions = new MigrationConventions();
var asm = Assembly.GetExecutingAssembly();
var loader = new DefaultMigrationInformationLoader(conventions, asm, "FluentMigrator.Tests.Integration.Migrations.Interleaved.Pass1", null);
var migrationList = loader.LoadMigrations();
migrationList.Select(x => x.Value.Migration.GetType()).ShouldNotContain(typeof(VersionedMigration));
migrationList.Count().ShouldBeGreaterThan(0);
}
[Test]
public void DefaultBehaviorIsToNotLoadNestedNamespaces()
{
var conventions = new MigrationConventions();
var asm = Assembly.GetExecutingAssembly();
var loader = new DefaultMigrationInformationLoader(conventions, asm, "FluentMigrator.Tests.Integration.Migrations.Nested", null);
loader.LoadNestedNamespaces.ShouldBe(false);
}
[Test]
public void FindsMigrationsInNestedNamespaceWhenLoadNestedNamespacesEnabled()
{
var conventions = new MigrationConventions();
var asm = Assembly.GetExecutingAssembly();
var loader = new DefaultMigrationInformationLoader(conventions, asm, "FluentMigrator.Tests.Integration.Migrations.Nested", true, null);
List<Type> expected = new List<Type>
{
typeof(Integration.Migrations.Nested.NotGrouped),
typeof(Integration.Migrations.Nested.Group1.FromGroup1),
typeof(Integration.Migrations.Nested.Group1.AnotherFromGroup1),
typeof(Integration.Migrations.Nested.Group2.FromGroup2),
};
var migrationList = loader.LoadMigrations();
List<Type> actual = migrationList.Select(m => m.Value.Migration.GetType()).ToList();
CollectionAssert.AreEquivalent(expected, actual);
}
[Test]
public void DoesNotFindsMigrationsInNestedNamespaceWhenLoadNestedNamespacesDisabled()
{
var conventions = new MigrationConventions();
var asm = Assembly.GetExecutingAssembly();
var loader = new DefaultMigrationInformationLoader(conventions, asm, "FluentMigrator.Tests.Integration.Migrations.Nested", false, null);
List<Type> expected = new List<Type>
{
typeof(Integration.Migrations.Nested.NotGrouped),
};
var migrationList = loader.LoadMigrations();
List<Type> actual = migrationList.Select(m => m.Value.Migration.GetType()).ToList();
CollectionAssert.AreEquivalent(expected, actual);
}
[Test]
public void DoesFindMigrationsThatHaveMatchingTags()
{
var asm = Assembly.GetExecutingAssembly();
var migrationType = typeof(TaggedMigraion);
var tagsToMatch = new[] { "UK", "Production" };
var conventionsMock = new Mock<IMigrationConventions>();
conventionsMock.SetupGet(m => m.GetMigrationInfo).Returns(DefaultMigrationConventions.GetMigrationInfoFor);
conventionsMock.SetupGet(m => m.TypeIsMigration).Returns(t => true);
conventionsMock.SetupGet(m => m.TypeHasTags).Returns(t => migrationType == t);
conventionsMock.SetupGet(m => m.TypeHasMatchingTags).Returns((type, tags) => (migrationType == type && tagsToMatch == tags));
var loader = new DefaultMigrationInformationLoader(conventionsMock.Object, asm, migrationType.Namespace, tagsToMatch);
var expected = new List<Type> { typeof(UntaggedMigration), migrationType };
var actual = loader.LoadMigrations().Select(m => m.Value.Migration.GetType()).ToList();
CollectionAssert.AreEquivalent(expected, actual);
}
[Test]
public void DoesNotFindMigrationsThatDoNotHaveMatchingTags()
{
var asm = Assembly.GetExecutingAssembly();
var migrationType = typeof(TaggedMigraion);
var tagsToMatch = new[] { "UK", "Production" };
var conventionsMock = new Mock<IMigrationConventions>();
conventionsMock.SetupGet(m => m.GetMigrationInfo).Returns(DefaultMigrationConventions.GetMigrationInfoFor);
conventionsMock.SetupGet(m => m.TypeIsMigration).Returns(t => true);
conventionsMock.SetupGet(m => m.TypeHasTags).Returns(t => migrationType == t);
conventionsMock.SetupGet(m => m.TypeHasMatchingTags).Returns((type, tags) => false);
var loader = new DefaultMigrationInformationLoader(conventionsMock.Object, asm, migrationType.Namespace, tagsToMatch);
var expected = new List<Type> { typeof(UntaggedMigration) };
var actual = loader.LoadMigrations().Select(m => m.Value.Migration.GetType()).ToList();
CollectionAssert.AreEquivalent(expected, actual);
}
public void HandlesNotFindingMigrations()
{
var conventions = new MigrationConventions();
var asm = Assembly.GetExecutingAssembly();
var loader = new DefaultMigrationInformationLoader(conventions, asm, "FluentMigrator.Tests.Unit.EmptyNamespace", null);
var list = loader.LoadMigrations();
Assert.That(list, Is.Not.Null);
Assert.That(list.Count(), Is.EqualTo(0));
}
[Test]
public void ShouldThrowExceptionIfDuplicateVersionNumbersAreLoaded()
{
var conventions = new MigrationConventions();
var asm = Assembly.GetExecutingAssembly();
var migrationLoader = new DefaultMigrationInformationLoader(conventions, asm, "FluentMigrator.Tests.Unit.DuplicateVersionNumbers", null);
Assert.Throws<DuplicateMigrationException>(() => migrationLoader.LoadMigrations());
}
[Test]
public void HandlesMigrationThatDoesNotInheritFromMigrationBaseClass()
{
var conventions = new MigrationConventions();
var asm = Assembly.GetExecutingAssembly();
var loader = new DefaultMigrationInformationLoader(conventions, asm, "FluentMigrator.Tests.Unit.DoesNotInheritFromBaseClass", null);
Assert.That(loader.LoadMigrations().Count(), Is.EqualTo(1));
}
[Test]
public void ShouldHandleTransactionlessMigrations()
{
var conventions = new MigrationConventions();
var asm = Assembly.GetExecutingAssembly();
var loader = new DefaultMigrationInformationLoader(conventions, asm, "FluentMigrator.Tests.Unit.DoesHandleTransactionLessMigrations", null);
var list = loader.LoadMigrations().ToList();
list.Count().ShouldBe(2);
list[0].Value.Migration.GetType().ShouldBe(typeof(DoesHandleTransactionLessMigrations.MigrationThatIsTransactionLess));
list[0].Value.TransactionBehavior.ShouldBe(TransactionBehavior.None);
list[0].Value.Version.ShouldBe(1);
list[1].Value.Migration.GetType().ShouldBe(typeof(DoesHandleTransactionLessMigrations.MigrationThatIsNotTransactionLess));
list[1].Value.TransactionBehavior.ShouldBe(TransactionBehavior.Default);
list[1].Value.Version.ShouldBe(2);
}
}
namespace EmptyNamespace
{
}
namespace DoesHandleTransactionLessMigrations
{
[Migration(1, TransactionBehavior.None)]
public class MigrationThatIsTransactionLess : Migration
{
public override void Up()
{
throw new NotImplementedException();
}
public override void Down()
{
throw new NotImplementedException();
}
}
[Migration(2)]
public class MigrationThatIsNotTransactionLess : Migration
{
public override void Up()
{
throw new NotImplementedException();
}
public override void Down()
{
throw new NotImplementedException();
}
}
}
namespace DoesNotInheritFromBaseClass
{
[Migration(1)]
public class MigrationThatDoesNotInheritFromMigrationBaseClass : IMigration
{
/// <summary>The arbitrary application context passed to the task runner.</summary>
public object ApplicationContext
{
get { throw new NotImplementedException(); }
}
public void GetUpExpressions(IMigrationContext context)
{
throw new NotImplementedException();
}
public void GetDownExpressions(IMigrationContext context)
{
throw new NotImplementedException();
}
}
}
namespace DuplicateVersionNumbers
{
[Migration(1)]
public class Duplicate1 : Migration
{
public override void Up() { }
public override void Down() { }
}
[Migration(1)]
public class Duplicate2 : Migration
{
public override void Up() { }
public override void Down() { }
}
}
namespace TaggingTestFakes
{
[Tags("UK", "IE", "QA", "Production")]
[Migration(123)]
public class TaggedMigraion : Migration
{
public override void Up() { }
public override void Down() { }
}
[Migration(567)]
public class UntaggedMigration : Migration
{
public override void Up() { }
public override void Down() { }
}
}
}
| |
/**
* Couchbase Lite for .NET
*
* Original iOS version by Jens Alfke
* Android Port by Marty Schoch, Traun Leyden
* C# Port by Zack Gramana
*
* Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved.
* Portions (c) 2013, 2014 Xamarin, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using Couchbase.Lite;
using Couchbase.Lite.Internal;
using Couchbase.Lite.Replicator;
using Couchbase.Lite.Router;
using Couchbase.Lite.Support;
using Couchbase.Lite.Util;
using NUnit.Framework;
using Sharpen;
namespace Couchbase.Lite
{
public abstract class LiteTestCase : TestCase
{
public const string Tag = "LiteTestCase";
private static bool initializedUrlHandler = false;
protected internal ObjectWriter mapper = new ObjectWriter();
protected internal Manager manager = null;
protected internal Database database = null;
protected internal string DefaultTestDb = "cblite-test";
/// <exception cref="System.Exception"></exception>
protected override void SetUp()
{
Log.V(Tag, "setUp");
base.SetUp();
//for some reason a traditional static initializer causes junit to die
if (!initializedUrlHandler)
{
URLStreamHandlerFactory.RegisterSelfIgnoreError();
initializedUrlHandler = true;
}
LoadCustomProperties();
StartCBLite();
StartDatabase();
}
protected internal virtual InputStream GetAsset(string name)
{
return this.GetType().GetResourceAsStream("/assets/" + name);
}
protected internal virtual FilePath GetRootDirectory()
{
string rootDirectoryPath = Runtime.GetProperty("user.dir");
FilePath rootDirectory = new FilePath(rootDirectoryPath);
rootDirectory = new FilePath(rootDirectory, "data/data/com.couchbase.cblite.test/files"
);
return rootDirectory;
}
protected internal virtual string GetServerPath()
{
string filesDir = GetRootDirectory().GetAbsolutePath();
return filesDir;
}
/// <exception cref="System.IO.IOException"></exception>
protected internal virtual void StartCBLite()
{
string serverPath = GetServerPath();
FilePath serverPathFile = new FilePath(serverPath);
FileDirUtils.DeleteRecursive(serverPathFile);
serverPathFile.Mkdir();
manager = new Manager(new FilePath(GetRootDirectory(), "test"), Manager.DefaultOptions
);
}
protected internal virtual void StopCBLite()
{
if (manager != null)
{
manager.Close();
}
}
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
protected internal virtual Database StartDatabase()
{
database = EnsureEmptyDatabase(DefaultTestDb);
return database;
}
protected internal virtual void StopDatabse()
{
if (database != null)
{
database.Close();
}
}
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
protected internal virtual Database EnsureEmptyDatabase(string dbName)
{
Database db = manager.GetExistingDatabase(dbName);
if (db != null)
{
db.Delete();
}
db = manager.GetDatabase(dbName);
return db;
}
/// <exception cref="System.IO.IOException"></exception>
protected internal virtual void LoadCustomProperties()
{
Properties systemProperties = Runtime.GetProperties();
InputStream mainProperties = GetAsset("test.properties");
if (mainProperties != null)
{
systemProperties.Load(mainProperties);
}
try
{
InputStream localProperties = GetAsset("local-test.properties");
if (localProperties != null)
{
systemProperties.Load(localProperties);
}
}
catch (IOException)
{
Log.W(Tag, "Error trying to read from local-test.properties, does this file exist?"
);
}
}
protected internal virtual string GetReplicationProtocol()
{
return Runtime.GetProperty("replicationProtocol");
}
protected internal virtual string GetReplicationServer()
{
return Runtime.GetProperty("replicationServer");
}
protected internal virtual int GetReplicationPort()
{
return System.Convert.ToInt32(Runtime.GetProperty("replicationPort"));
}
protected internal virtual string GetReplicationAdminUser()
{
return Runtime.GetProperty("replicationAdminUser");
}
protected internal virtual string GetReplicationAdminPassword()
{
return Runtime.GetProperty("replicationAdminPassword");
}
protected internal virtual string GetReplicationDatabase()
{
return Runtime.GetProperty("replicationDatabase");
}
protected internal virtual Uri GetReplicationURL()
{
try
{
if (GetReplicationAdminUser() != null && GetReplicationAdminUser().Trim().Length
> 0)
{
return new Uri(string.Format("%s://%s:%s@%s:%d/%s", GetReplicationProtocol(), GetReplicationAdminUser
(), GetReplicationAdminPassword(), GetReplicationServer(), GetReplicationPort(),
GetReplicationDatabase()));
}
else
{
return new Uri(string.Format("%s://%s:%d/%s", GetReplicationProtocol(), GetReplicationServer
(), GetReplicationPort(), GetReplicationDatabase()));
}
}
catch (UriFormatException e)
{
throw new ArgumentException(e);
}
}
/// <exception cref="System.UriFormatException"></exception>
protected internal virtual Uri GetReplicationURLWithoutCredentials()
{
return new Uri(string.Format("%s://%s:%d/%s", GetReplicationProtocol(), GetReplicationServer
(), GetReplicationPort(), GetReplicationDatabase()));
}
/// <exception cref="System.Exception"></exception>
protected override void TearDown()
{
Log.V(Tag, "tearDown");
base.TearDown();
StopDatabse();
StopCBLite();
}
protected internal virtual IDictionary<string, object> UserProperties(IDictionary
<string, object> properties)
{
IDictionary<string, object> result = new Dictionary<string, object>();
foreach (string key in properties.Keys)
{
if (!key.StartsWith("_"))
{
result.Put(key, properties.Get(key));
}
}
return result;
}
/// <exception cref="System.IO.IOException"></exception>
public virtual IDictionary<string, object> GetReplicationAuthParsedJson()
{
string authJson = "{\n" + " \"facebook\" : {\n" + " \"email\" : \"[email protected]\"\n"
+ " }\n" + " }\n";
ObjectWriter mapper = new ObjectWriter();
IDictionary<string, object> authProperties = mapper.ReadValue(authJson, new _TypeReference_194
());
return authProperties;
}
private sealed class _TypeReference_194 : TypeReference<Dictionary<string, object
>>
{
public _TypeReference_194()
{
}
}
/// <exception cref="System.IO.IOException"></exception>
public virtual IDictionary<string, object> GetPushReplicationParsedJson()
{
IDictionary<string, object> authProperties = GetReplicationAuthParsedJson();
IDictionary<string, object> targetProperties = new Dictionary<string, object>();
targetProperties.Put("url", GetReplicationURL().ToExternalForm());
targetProperties.Put("auth", authProperties);
IDictionary<string, object> properties = new Dictionary<string, object>();
properties.Put("source", DefaultTestDb);
properties.Put("target", targetProperties);
return properties;
}
/// <exception cref="System.IO.IOException"></exception>
public virtual IDictionary<string, object> GetPullReplicationParsedJson()
{
IDictionary<string, object> authProperties = GetReplicationAuthParsedJson();
IDictionary<string, object> sourceProperties = new Dictionary<string, object>();
sourceProperties.Put("url", GetReplicationURL().ToExternalForm());
sourceProperties.Put("auth", authProperties);
IDictionary<string, object> properties = new Dictionary<string, object>();
properties.Put("source", sourceProperties);
properties.Put("target", DefaultTestDb);
return properties;
}
protected internal virtual URLConnection SendRequest(string method, string path,
IDictionary<string, string> headers, object bodyObj)
{
try
{
Uri url = new Uri("cblite://" + path);
URLConnection conn = (URLConnection)url.OpenConnection();
conn.SetDoOutput(true);
conn.SetRequestMethod(method);
if (headers != null)
{
foreach (string header in headers.Keys)
{
conn.SetRequestProperty(header, headers.Get(header));
}
}
IDictionary<string, IList<string>> allProperties = conn.GetRequestProperties();
if (bodyObj != null)
{
conn.SetDoInput(true);
ByteArrayInputStream bais = new ByteArrayInputStream(mapper.WriteValueAsBytes(bodyObj
));
conn.SetRequestInputStream(bais);
}
Couchbase.Lite.Router.Router router = new Couchbase.Lite.Router.Router(manager, conn
);
router.Start();
return conn;
}
catch (UriFormatException)
{
Fail();
}
catch (IOException)
{
Fail();
}
return null;
}
protected internal virtual object ParseJSONResponse(URLConnection conn)
{
object result = null;
Body responseBody = conn.GetResponseBody();
if (responseBody != null)
{
byte[] json = responseBody.GetJson();
string jsonString = null;
if (json != null)
{
jsonString = Sharpen.Runtime.GetStringForBytes(json);
try
{
result = mapper.ReadValue<object>(jsonString);
}
catch (Exception)
{
Fail();
}
}
}
return result;
}
protected internal virtual object SendBody(string method, string path, object bodyObj
, int expectedStatus, object expectedResult)
{
URLConnection conn = SendRequest(method, path, null, bodyObj);
object result = ParseJSONResponse(conn);
Log.V(Tag, string.Format("%s %s --> %d", method, path, conn.GetResponseCode()));
NUnit.Framework.Assert.AreEqual(expectedStatus, conn.GetResponseCode());
if (expectedResult != null)
{
NUnit.Framework.Assert.AreEqual(expectedResult, result);
}
return result;
}
protected internal virtual object Send(string method, string path, int expectedStatus
, object expectedResult)
{
return SendBody(method, path, null, expectedStatus, expectedResult);
}
public static void CreateDocuments(Database db, int n)
{
//TODO should be changed to use db.runInTransaction
for (int i = 0; i < n; i++)
{
IDictionary<string, object> properties = new Dictionary<string, object>();
properties.Put("testName", "testDatabase");
properties.Put("sequence", i);
CreateDocumentWithProperties(db, properties);
}
}
internal static void CreateDocumentsAsync(Database db, int n)
{
db.RunAsync(new _AsyncTask_301(db, n));
}
private sealed class _AsyncTask_301 : AsyncTask
{
public _AsyncTask_301(Database db, int n)
{
this.db = db;
this.n = n;
}
public void Run(Database database)
{
db.BeginTransaction();
LiteTestCase.CreateDocuments(db, n);
db.EndTransaction(true);
}
private readonly Database db;
private readonly int n;
}
public static Document CreateDocumentWithProperties(Database db, IDictionary<string
, object> properties)
{
Document doc = db.CreateDocument();
NUnit.Framework.Assert.IsNotNull(doc);
NUnit.Framework.Assert.IsNull(doc.GetCurrentRevisionId());
NUnit.Framework.Assert.IsNull(doc.GetCurrentRevision());
NUnit.Framework.Assert.IsNotNull("Document has no ID", doc.GetId());
// 'untitled' docs are no longer untitled (8/10/12)
try
{
doc.PutProperties(properties);
}
catch (Exception e)
{
Log.E(Tag, "Error creating document", e);
NUnit.Framework.Assert.IsTrue("can't create new document in db:" + db.GetName() +
" with properties:" + properties.ToString(), false);
}
NUnit.Framework.Assert.IsNotNull(doc.GetId());
NUnit.Framework.Assert.IsNotNull(doc.GetCurrentRevisionId());
NUnit.Framework.Assert.IsNotNull(doc.GetUserProperties());
// this won't work until the weakref hashmap is implemented which stores all docs
// Assert.assertEquals(db.getDocument(doc.getId()), doc);
NUnit.Framework.Assert.AreEqual(db.GetDocument(doc.GetId()).GetId(), doc.GetId());
return doc;
}
public virtual void RunReplication(Replication replication)
{
CountDownLatch replicationDoneSignal = new CountDownLatch(1);
LiteTestCase.ReplicationFinishedObserver replicationFinishedObserver = new LiteTestCase.ReplicationFinishedObserver
(replicationDoneSignal);
replication.AddChangeListener(replicationFinishedObserver);
replication.Start();
CountDownLatch replicationDoneSignalPolling = ReplicationWatcherThread(replication
);
Log.D(Tag, "Waiting for replicator to finish");
try
{
bool success = replicationDoneSignal.Await(300, TimeUnit.Seconds);
NUnit.Framework.Assert.IsTrue(success);
success = replicationDoneSignalPolling.Await(300, TimeUnit.Seconds);
NUnit.Framework.Assert.IsTrue(success);
Log.D(Tag, "replicator finished");
}
catch (Exception e)
{
Sharpen.Runtime.PrintStackTrace(e);
}
replication.RemoveChangeListener(replicationFinishedObserver);
}
public virtual CountDownLatch ReplicationWatcherThread(Replication replication)
{
CountDownLatch doneSignal = new CountDownLatch(1);
new Sharpen.Thread(new _Runnable_372(replication, doneSignal)).Start();
return doneSignal;
}
private sealed class _Runnable_372 : Runnable
{
public _Runnable_372(Replication replication, CountDownLatch doneSignal)
{
this.replication = replication;
this.doneSignal = doneSignal;
}
public void Run()
{
bool started = false;
bool done = false;
while (!done)
{
if (replication.IsRunning())
{
started = true;
}
bool statusIsDone = (replication.GetStatus() == Replication.ReplicationStatus.ReplicationStopped
|| replication.GetStatus() == Replication.ReplicationStatus.ReplicationIdle);
if (started && statusIsDone)
{
done = true;
}
try
{
Sharpen.Thread.Sleep(500);
}
catch (Exception e)
{
Sharpen.Runtime.PrintStackTrace(e);
}
}
doneSignal.CountDown();
}
private readonly Replication replication;
private readonly CountDownLatch doneSignal;
}
public class ReplicationFinishedObserver : Replication.ChangeListener
{
public bool replicationFinished = false;
private CountDownLatch doneSignal;
public ReplicationFinishedObserver(CountDownLatch doneSignal)
{
this.doneSignal = doneSignal;
}
public virtual void Changed(Replication.ChangeEvent @event)
{
Replication replicator = @event.GetSource();
Log.D(Tag, replicator + " changed. " + replicator.GetCompletedChangesCount() + " / "
+ replicator.GetChangesCount());
NUnit.Framework.Assert.IsTrue(replicator.GetCompletedChangesCount() <= replicator
.GetChangesCount());
if (replicator.GetCompletedChangesCount() > replicator.GetChangesCount())
{
throw new RuntimeException("replicator.getCompletedChangesCount() > replicator.getChangesCount()"
);
}
if (!replicator.IsRunning())
{
replicationFinished = true;
string msg = string.Format("ReplicationFinishedObserver.changed called, set replicationFinished to: %b"
, replicationFinished);
Log.D(Tag, msg);
doneSignal.CountDown();
}
else
{
string msg = string.Format("ReplicationFinishedObserver.changed called, but replicator still running, so ignore it"
);
Log.D(Tag, msg);
}
}
internal virtual bool IsReplicationFinished()
{
return replicationFinished;
}
}
public class ReplicationRunningObserver : Replication.ChangeListener
{
private CountDownLatch doneSignal;
public ReplicationRunningObserver(CountDownLatch doneSignal)
{
this.doneSignal = doneSignal;
}
public virtual void Changed(Replication.ChangeEvent @event)
{
Replication replicator = @event.GetSource();
if (replicator.IsRunning())
{
doneSignal.CountDown();
}
}
}
public class ReplicationIdleObserver : Replication.ChangeListener
{
private CountDownLatch doneSignal;
public ReplicationIdleObserver(CountDownLatch doneSignal)
{
this.doneSignal = doneSignal;
}
public virtual void Changed(Replication.ChangeEvent @event)
{
Replication replicator = @event.GetSource();
if (replicator.GetStatus() == Replication.ReplicationStatus.ReplicationIdle)
{
doneSignal.CountDown();
}
}
}
public class ReplicationErrorObserver : Replication.ChangeListener
{
private CountDownLatch doneSignal;
public ReplicationErrorObserver(CountDownLatch doneSignal)
{
this.doneSignal = doneSignal;
}
public virtual void Changed(Replication.ChangeEvent @event)
{
Replication replicator = @event.GetSource();
if (replicator.GetLastError() != null)
{
doneSignal.CountDown();
}
}
}
}
}
| |
namespace StripeTests
{
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using Moq.Protected;
using Newtonsoft.Json.Linq;
using Stripe;
using Xunit;
public class TelemetryTest : BaseStripeTest
{
public TelemetryTest(MockHttpClientFixture mockHttpClientFixture)
: base(mockHttpClientFixture)
{
}
[Fact]
public void TelemetryWorks()
{
this.MockHttpClientFixture.Reset();
var fakeServer = FakeServer.ForMockHandler(this.MockHttpClientFixture.MockHandler);
fakeServer.Delay = TimeSpan.FromMilliseconds(20);
var service = new BalanceService(this.StripeClient);
service.Get();
fakeServer.Delay = TimeSpan.FromMilliseconds(40);
service.Get();
service.Get();
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
!m.Headers.Contains("X-Stripe-Client-Telemetry")),
ItExpr.IsAny<CancellationToken>());
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
TelemetryHeaderMatcher(
m.Headers,
(s) => s == "req_1",
(d) => d >= 15)),
ItExpr.IsAny<CancellationToken>());
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
TelemetryHeaderMatcher(
m.Headers,
(s) => s == "req_2",
(d) => d >= 30)),
ItExpr.IsAny<CancellationToken>());
}
[Fact]
public async Task TelemetryWorksWithConcurrentRequests()
{
this.MockHttpClientFixture.Reset();
var fakeServer = FakeServer.ForMockHandler(this.MockHttpClientFixture.MockHandler);
fakeServer.Delay = TimeSpan.FromMilliseconds(20);
var service = new BalanceService(this.StripeClient);
// the first 2 requests will not contain telemetry
await Task.WhenAll(service.GetAsync(), service.GetAsync());
// the following 2 requests will contain telemetry
await Task.WhenAll(service.GetAsync(), service.GetAsync());
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Exactly(2),
ItExpr.Is<HttpRequestMessage>(m =>
!m.Headers.Contains("X-Stripe-Client-Telemetry")),
ItExpr.IsAny<CancellationToken>());
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
TelemetryHeaderMatcher(
m.Headers,
(s) => s == "req_1",
(d) => d >= 15)),
ItExpr.IsAny<CancellationToken>());
this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m =>
TelemetryHeaderMatcher(
m.Headers,
(s) => s == "req_2",
(d) => d >= 15)),
ItExpr.IsAny<CancellationToken>());
}
[Fact]
public void NoTelemetryWhenDisabled()
{
var mockHandler = new Mock<HttpClientHandler> { CallBase = true };
var httpClient = new SystemNetHttpClient(
new System.Net.Http.HttpClient(mockHandler.Object),
enableTelemetry: false);
var stripeClient = new StripeClient("sk_test_123", httpClient: httpClient);
mockHandler.Reset();
var fakeServer = FakeServer.ForMockHandler(mockHandler);
fakeServer.Delay = TimeSpan.FromMilliseconds(20);
var service = new BalanceService(stripeClient);
service.Get();
fakeServer.Delay = TimeSpan.FromMilliseconds(40);
service.Get();
service.Get();
mockHandler.Protected()
.Verify(
"SendAsync",
Times.Exactly(3),
ItExpr.Is<HttpRequestMessage>(m =>
!m.Headers.Contains("X-Stripe-Client-Telemetry")),
ItExpr.IsAny<CancellationToken>());
}
private static bool TelemetryHeaderMatcher(
HttpHeaders headers,
Func<string, bool> requestIdMatcher,
Func<long, bool> durationMatcher)
{
if (!headers.Contains("X-Stripe-Client-Telemetry"))
{
return false;
}
var payload = headers.GetValues("X-Stripe-Client-Telemetry").First();
var deserialized = JToken.Parse(payload);
var requestId = (string)deserialized["last_request_metrics"]["request_id"];
var duration = (long)deserialized["last_request_metrics"]["request_duration_ms"];
return requestIdMatcher(requestId) && durationMatcher(duration);
}
private class FakeServer
{
private readonly object lockObject = new object();
public TimeSpan Delay { get; set; } = TimeSpan.Zero;
public int RequestCount { get; protected set; }
public static FakeServer ForMockHandler(Mock<HttpClientHandler> mockHandler)
{
var fakeServer = new FakeServer();
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.Returns(fakeServer.NextResponse);
return fakeServer;
}
public async Task<HttpResponseMessage> NextResponse()
{
string requestId;
lock (this.lockObject)
{
this.RequestCount += 1;
requestId = $"req_{this.RequestCount}";
}
await Task.Delay(this.Delay).ConfigureAwait(false);
return new HttpResponseMessage(HttpStatusCode.OK)
{
Headers = { { "Request-Id", requestId } },
Content = new StringContent("{}", Encoding.UTF8),
};
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using ALinq;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml.Linq;
namespace ALinq.SqlClient
{
internal static partial class SqlTypeSystem
{
// Fields
private const int defaultDecimalPrecision = 0x1d;
private const int defaultDecimalScale = 4;
internal const short LargeTypeSizeIndicator = -1;
private static readonly SqlType theBigInt = new SqlType(System.Data.SqlDbType.BigInt);
private static readonly SqlType theBit = new SqlType(System.Data.SqlDbType.Bit);
private static readonly SqlType theChar = new SqlType(System.Data.SqlDbType.Char);
private static readonly SqlType theDateTime = new SqlType(System.Data.SqlDbType.DateTime);
private static readonly SqlType theDefaultDecimal = new SqlType(System.Data.SqlDbType.Decimal, 0x1d, 4);
private static readonly SqlType theFloat = new SqlType(System.Data.SqlDbType.Float);
private static readonly SqlType theImage = new SqlType(System.Data.SqlDbType.Image, -1);
internal static readonly SqlType theInt = new SqlType(System.Data.SqlDbType.Int);
private static readonly SqlType theMoney = new SqlType(System.Data.SqlDbType.Money, 0x13, 4);
internal static readonly SqlType theNText = new SqlType(System.Data.SqlDbType.NText, -1);
private static readonly SqlType theReal = new SqlType(System.Data.SqlDbType.Real);
private static readonly SqlType theSmallDateTime = new SqlType(System.Data.SqlDbType.SmallDateTime);
private static readonly SqlType theSmallInt = new SqlType(System.Data.SqlDbType.SmallInt);
private static readonly SqlType theSmallMoney = new SqlType(System.Data.SqlDbType.SmallMoney, 10, 4);
private static readonly SqlType theText = new SqlType(System.Data.SqlDbType.Text, -1);
private static readonly SqlType theTimestamp = new SqlType(System.Data.SqlDbType.Timestamp);
private static readonly SqlType theTinyInt = new SqlType(System.Data.SqlDbType.TinyInt);
private static readonly SqlType theUniqueIdentifier = new SqlType(System.Data.SqlDbType.UniqueIdentifier);
internal static readonly SqlType theXml = new SqlType(System.Data.SqlDbType.Xml, -1);
// Methods
internal static IProviderType Create(SqlDbType type)
{
switch (type)
{
case System.Data.SqlDbType.BigInt:
return theBigInt;
case System.Data.SqlDbType.Bit:
return theBit;
case System.Data.SqlDbType.Char:
return theChar;
case System.Data.SqlDbType.DateTime:
return theDateTime;
case System.Data.SqlDbType.Decimal:
return theDefaultDecimal;
case System.Data.SqlDbType.Float:
return theFloat;
case System.Data.SqlDbType.Image:
return theImage;
case System.Data.SqlDbType.Int:
return theInt;
case System.Data.SqlDbType.Money:
return theMoney;
case System.Data.SqlDbType.NText:
return theNText;
case System.Data.SqlDbType.Real:
return theReal;
case System.Data.SqlDbType.UniqueIdentifier:
return theUniqueIdentifier;
case System.Data.SqlDbType.SmallDateTime:
return theSmallDateTime;
case System.Data.SqlDbType.SmallInt:
return theSmallInt;
case System.Data.SqlDbType.SmallMoney:
return theSmallMoney;
case System.Data.SqlDbType.Text:
return theText;
case System.Data.SqlDbType.Timestamp:
return theTimestamp;
case System.Data.SqlDbType.TinyInt:
return theTinyInt;
case System.Data.SqlDbType.Xml:
return theXml;
}
return new SqlType(type);
}
internal static IProviderType Create(SqlDbType type, int size)
{
return new SqlType(type, size);
}
internal static IProviderType Create(SqlDbType type, int precision, int scale)
{
if (((type != System.Data.SqlDbType.Decimal) && (precision == 0)) && (scale == 0))
{
return Create(type);
}
if (((type == System.Data.SqlDbType.Decimal) && (precision == 0x1d)) && (scale == 4))
{
return Create(type);
}
return new SqlType(type, precision, scale);
}
internal static Type GetClosestRuntimeType(SqlDbType sqlDbType)
{
switch (sqlDbType)
{
case System.Data.SqlDbType.BigInt:
return typeof(long);
case System.Data.SqlDbType.Binary:
case System.Data.SqlDbType.Image:
case System.Data.SqlDbType.Timestamp:
case System.Data.SqlDbType.VarBinary:
return typeof(byte[]);
case System.Data.SqlDbType.Bit:
return typeof(bool);
case System.Data.SqlDbType.Char:
case System.Data.SqlDbType.NChar:
case System.Data.SqlDbType.NText:
case System.Data.SqlDbType.NVarChar:
case System.Data.SqlDbType.Text:
case System.Data.SqlDbType.VarChar:
case System.Data.SqlDbType.Xml:
return typeof(string);
case System.Data.SqlDbType.DateTime:
case System.Data.SqlDbType.SmallDateTime:
return typeof(DateTime);
case System.Data.SqlDbType.Decimal:
case System.Data.SqlDbType.Money:
case System.Data.SqlDbType.SmallMoney:
return typeof(decimal);
case System.Data.SqlDbType.Float:
return typeof(double);
case System.Data.SqlDbType.Int:
return typeof(int);
case System.Data.SqlDbType.Real:
return typeof(float);
case System.Data.SqlDbType.UniqueIdentifier:
return typeof(Guid);
case System.Data.SqlDbType.SmallInt:
return typeof(short);
case System.Data.SqlDbType.TinyInt:
return typeof(byte);
case System.Data.SqlDbType.Udt:
throw Error.UnexpectedTypeCode(System.Data.SqlDbType.Udt);
}
return typeof(object);
}
#region ProviderBase
// Nested Types
internal abstract class ProviderBase : TypeSystemProvider
{
// Fields
protected Dictionary<int, SqlType> applicationTypes = new Dictionary<int, SqlType>();
// Methods
public override IProviderType ChangeTypeFamilyTo(IProviderType type, IProviderType toType)
{
if (type.IsSameTypeFamily(toType))
{
return type;
}
if (type.IsApplicationType || toType.IsApplicationType)
{
return toType;
}
var type2 = (SqlType)toType;
var type3 = (SqlType)type;
if ((type2.Category != SqlType.TypeCategory.Numeric) || (type3.Category != SqlType.TypeCategory.Char))
{
return toType;
}
var sqlDbType = (SqlDbType)type3.SqlDbType;
if (sqlDbType != System.Data.SqlDbType.Char)
{
if (sqlDbType == System.Data.SqlDbType.NChar)
{
return Create(System.Data.SqlDbType.Int);
}
return toType;
}
return Create(System.Data.SqlDbType.SmallInt);
}
public override IProviderType From(object o)
{
Type type = (o != null) ? o.GetType() : typeof(object);
if (type == typeof(string))
{
var str = (string)o;
return this.From(type, new int?(str.Length));
}
if (type == typeof(bool))
{
return this.From(typeof(int));
}
if (type.IsArray)
{
var array = (Array)o;
return From(type, new int?(array.Length));
}
if (type == typeof(decimal))
{
var d = (decimal)o;
int num2 = (decimal.GetBits(d)[3] & 0xff0000) >> 0x10;
return From(type, num2);
}
return this.From(type);
}
public override IProviderType From(Type type)
{
return this.From(type, null);
}
public override IProviderType From(Type type, int? size)
{
return this.From(type, size);
}
public override IProviderType GetApplicationType(int index)
{
if (index < 0)
{
throw Error.ArgumentOutOfRange("index");
}
SqlTypeSystem.SqlType type = null;
if (!this.applicationTypes.TryGetValue(index, out type))
{
type = new SqlTypeSystem.SqlType(index);
this.applicationTypes.Add(index, type);
}
return type;
}
private IProviderType[] GetArgumentTypes(SqlFunctionCall fc)
{
var typeArray = new IProviderType[fc.Arguments.Count];
int index = 0;
int length = typeArray.Length;
while (index < length)
{
typeArray[index] = fc.Arguments[index].SqlType;
index++;
}
return typeArray;
}
public override IProviderType GetBestType(IProviderType typeA, IProviderType typeB)
{
SqlTypeSystem.SqlType type = (typeA.ComparePrecedenceTo(typeB) > 0) ? ((SqlTypeSystem.SqlType)typeA) : ((SqlTypeSystem.SqlType)typeB);
if (typeA.IsApplicationType || typeA.IsRuntimeOnlyType)
{
return typeA;
}
if (typeB.IsApplicationType || typeB.IsRuntimeOnlyType)
{
return typeB;
}
var type2 = (SqlType)typeA;
var type3 = (SqlType)typeB;
if ((type2.HasPrecisionAndScale && type3.HasPrecisionAndScale) && ((SqlDbType)type.SqlDbType == System.Data.SqlDbType.Decimal))
{
int precision = type2.Precision;
int scale = type2.Scale;
int num3 = type3.Precision;
int num4 = type3.Scale;
if (((precision == 0) && (scale == 0)) && ((num3 == 0) && (num4 == 0)))
{
return Create((SqlDbType)type.SqlDbType);
}
if ((precision == 0) && (scale == 0))
{
return Create((SqlDbType)type.SqlDbType, num3, num4);
}
if ((num3 == 0) && (num4 == 0))
{
return Create((SqlDbType)type.SqlDbType, precision, scale);
}
int num5 = Math.Max((int)(precision - scale), (int)(num3 - num4));
int num6 = Math.Max(scale, num4);
Math.Min(num5 + num6, 0x25);
return Create((SqlDbType)type.SqlDbType, num5 + num6, num6);
}
int? size = null;
if (type2.Size.HasValue && type3.Size.HasValue)
{
var nullable4 = type3.Size;
var nullable5 = type2.Size;
size = ((nullable4.GetValueOrDefault() > nullable5.GetValueOrDefault()) && (nullable4.HasValue & nullable5.HasValue)) ? type3.Size : type2.Size;
}
if ((type3.Size.HasValue && (type3.Size.Value == -1)) || (type2.Size.HasValue && (type2.Size.Value == -1)))
{
size = -1;
}
return new SqlType((SqlDbType)type.SqlDbType, size);
}
protected IProviderType GetBestType(SqlDbType targetType, int? size)
{
int num = 0;
switch (targetType)
{
case System.Data.SqlDbType.Binary:
case System.Data.SqlDbType.Char:
case System.Data.SqlDbType.VarBinary:
case System.Data.SqlDbType.VarChar:
num = 0x1f40;
break;
case System.Data.SqlDbType.NChar:
case System.Data.SqlDbType.NVarChar:
num = 0xfa0;
break;
}
if (!size.HasValue)
{
return SqlTypeSystem.Create(targetType, this.SupportsMaxSize ? -1 : num);
}
if (size.Value <= num)
{
return SqlTypeSystem.Create(targetType, size.Value);
}
return this.GetBestLargeType(SqlTypeSystem.Create(targetType));
}
protected virtual object GetParameterValue(SqlType type, object value)
{
if (value == null)
return DBNull.Value;
var type2 = value.GetType();
var closestRuntimeType = type.GetClosestRuntimeType();
return closestRuntimeType == type2 ? value : DBConvert.ChangeType(value, closestRuntimeType);
}
public override void InitializeParameter(IProviderType type, DbParameter parameter, object value)
{
var type2 = (SqlType)type;
if (type2.IsRuntimeOnlyType)
{
throw Error.BadParameterType(type2.GetClosestRuntimeType());
}
var parameter2 = parameter as System.Data.SqlClient.SqlParameter;
if (parameter2 != null)
{
parameter2.SqlDbType = (SqlDbType)type2.SqlDbType;
if (type2.HasPrecisionAndScale)
{
parameter2.Precision = (byte)type2.Precision;
parameter2.Scale = (byte)type2.Scale;
}
}
else
{
PropertyInfo property = parameter.GetType().GetProperty("SqlDbType");
if (property != null)
{
property.SetValue(parameter, type2.SqlDbType, null);
}
if (type2.HasPrecisionAndScale)
{
PropertyInfo info2 = parameter.GetType().GetProperty("Precision");
if (info2 != null)
{
info2.SetValue(parameter, Convert.ChangeType(type2.Precision, info2.PropertyType, CultureInfo.InvariantCulture), null);
}
PropertyInfo info3 = parameter.GetType().GetProperty("Scale");
if (info3 != null)
{
info3.SetValue(parameter, Convert.ChangeType(type2.Scale, info3.PropertyType, CultureInfo.InvariantCulture), null);
}
}
}
parameter.Value = GetParameterValue(type2, value);
if (!((parameter.Direction == ParameterDirection.Input) && type2.IsFixedSize) && (parameter.Direction == ParameterDirection.Input))
{
return;
}
if (type2.Size.HasValue)
{
if (parameter.Size < type2.Size)
{
goto Label_016B;
}
}
if (!type2.IsLargeType)
{
return;
}
Label_016B:
parameter.Size = type2.Size.Value;
}
public override IProviderType MostPreciseTypeInFamily(IProviderType type)
{
var type2 = (SqlType)type;
switch ((SqlDbType)type2.SqlDbType)
{
case System.Data.SqlDbType.DateTime:
case System.Data.SqlDbType.SmallDateTime:
return this.From(typeof(DateTime));
case System.Data.SqlDbType.Decimal:
case System.Data.SqlDbType.Image:
case System.Data.SqlDbType.NChar:
case System.Data.SqlDbType.NText:
case System.Data.SqlDbType.NVarChar:
case System.Data.SqlDbType.UniqueIdentifier:
case System.Data.SqlDbType.Text:
case System.Data.SqlDbType.Timestamp:
return type;
case System.Data.SqlDbType.Float:
case System.Data.SqlDbType.Real:
return this.From(typeof(double));
case System.Data.SqlDbType.Int:
case System.Data.SqlDbType.SmallInt:
case System.Data.SqlDbType.TinyInt:
return this.From(typeof(int));
case System.Data.SqlDbType.Money:
case System.Data.SqlDbType.SmallMoney:
return SqlTypeSystem.Create(System.Data.SqlDbType.Money);
}
return type;
}
public override IProviderType Parse(string stype)
{
string strA = null;
string s = null;
string str3 = null;
int index = stype.IndexOf('(');
int num2 = stype.IndexOf(' ');
int length = ((index != -1) && (num2 != -1)) ? Math.Min(num2, index) : ((index != -1) ? index : ((num2 != -1) ? num2 : -1));
if (length == -1)
{
strA = stype;
length = stype.Length;
}
else
{
strA = stype.Substring(0, length);
}
int startIndex = length;
if ((startIndex < stype.Length) && (stype[startIndex] == '('))
{
startIndex++;
length = stype.IndexOf(',', startIndex);
if (length > 0)
{
s = stype.Substring(startIndex, length - startIndex);
startIndex = length + 1;
length = stype.IndexOf(')', startIndex);
str3 = stype.Substring(startIndex, length - startIndex);
}
else
{
length = stype.IndexOf(')', startIndex);
s = stype.Substring(startIndex, length - startIndex);
}
startIndex = length++;
}
if (string.Compare(strA, "rowversion", StringComparison.OrdinalIgnoreCase) == 0)
{
strA = "Timestamp";
}
if (string.Compare(strA, "numeric", StringComparison.OrdinalIgnoreCase) == 0)
{
strA = "Decimal";
}
if (string.Compare(strA, "sql_variant", StringComparison.OrdinalIgnoreCase) == 0)
{
strA = "Variant";
}
if (!Enum.GetNames(typeof(SqlDbType)).Select<string, string>(delegate(string n)
{
return n.ToUpperInvariant();
}).Contains<string>(strA.ToUpperInvariant()))
{
throw Error.InvalidProviderType(strA);
}
int size = 0;
int scale = 0;
var type = (SqlDbType)Enum.Parse(typeof(SqlDbType), strA, true);
if (s != null)
{
if (string.Compare(s.Trim(), "max", StringComparison.OrdinalIgnoreCase) == 0)
{
size = -1;
}
else
{
size = int.Parse(s, CultureInfo.InvariantCulture);
if (size == 0x7fffffff)
{
size = -1;
}
}
}
if (str3 != null)
{
if (string.Compare(str3.Trim(), "max", StringComparison.OrdinalIgnoreCase) == 0)
{
scale = -1;
}
else
{
scale = int.Parse(str3, CultureInfo.InvariantCulture);
if (scale == 0x7fffffff)
{
scale = -1;
}
}
}
switch (type)
{
case System.Data.SqlDbType.Binary:
case System.Data.SqlDbType.Char:
case System.Data.SqlDbType.NChar:
case System.Data.SqlDbType.NVarChar:
case System.Data.SqlDbType.VarBinary:
case System.Data.SqlDbType.VarChar:
return SqlTypeSystem.Create(type, size);
case System.Data.SqlDbType.Decimal:
case System.Data.SqlDbType.Float:
case System.Data.SqlDbType.Real:
return SqlTypeSystem.Create(type, size, scale);
}
return SqlTypeSystem.Create(type);
}
public override IProviderType PredictTypeForBinary(SqlNodeType binaryOp, IProviderType leftType, IProviderType rightType)
{
IProviderType bestType;
if (leftType.IsSameTypeFamily(this.From(typeof(string))) && rightType.IsSameTypeFamily(this.From(typeof(string))))
{
bestType = this.GetBestType(leftType, rightType);
}
else
{
bestType = (leftType.ComparePrecedenceTo(rightType) > 0) ? ((SqlTypeSystem.SqlType)leftType) : ((SqlTypeSystem.SqlType)rightType);
}
switch (binaryOp)
{
case SqlNodeType.BitAnd:
case SqlNodeType.BitOr:
case SqlNodeType.BitXor:
return bestType;
case SqlNodeType.And:
case SqlNodeType.EQ:
case SqlNodeType.EQ2V:
case SqlNodeType.LE:
case SqlNodeType.LT:
case SqlNodeType.GE:
case SqlNodeType.GT:
case SqlNodeType.NE:
case SqlNodeType.NE2V:
case SqlNodeType.Or:
return theInt;
case SqlNodeType.Add:
return bestType;
case SqlNodeType.Coalesce:
return bestType;
case SqlNodeType.Concat:
{
if (!bestType.HasSizeOrIsLarge)
{
return bestType;
}
IProviderType type2 = GetBestType((SqlDbType)bestType.SqlDbType, null);
if ((leftType.IsLargeType || !leftType.Size.HasValue) || (rightType.IsLargeType || !rightType.Size.HasValue))
{
return type2;
}
int num2 = leftType.Size.Value + rightType.Size.Value;
int num3 = num2;
if ((num3 >= type2.Size) && !type2.IsLargeType)
{
return type2;
}
return this.GetBestType((SqlDbType)(bestType).SqlDbType, new int?(num2));
}
case SqlNodeType.Div:
return bestType;
case SqlNodeType.Mod:
case SqlNodeType.Mul:
return bestType;
case SqlNodeType.Sub:
return bestType;
}
throw Error.UnexpectedNode(binaryOp);
}
public override IProviderType PredictTypeForUnary(SqlNodeType unaryOp, IProviderType operandType)
{
switch (unaryOp)
{
case SqlNodeType.Avg:
case SqlNodeType.Covar:
case SqlNodeType.Stddev:
case SqlNodeType.Sum:
return this.MostPreciseTypeInFamily(operandType);
case SqlNodeType.BitNot:
return operandType;
case SqlNodeType.ClrLength:
if (operandType.IsLargeType)
{
return this.From(typeof(long));
}
return this.From(typeof(int));
case SqlNodeType.LongCount:
return this.From(typeof(long));
case SqlNodeType.Max:
return operandType;
case SqlNodeType.Count:
return this.From(typeof(int));
case SqlNodeType.IsNotNull:
case SqlNodeType.IsNull:
case SqlNodeType.Not:
case SqlNodeType.Not2V:
return SqlTypeSystem.theBit;
case SqlNodeType.Negate:
return operandType;
case SqlNodeType.OuterJoinedValue:
return operandType;
case SqlNodeType.Min:
return operandType;
case SqlNodeType.Treat:
case SqlNodeType.ValueOf:
return operandType;
}
throw Error.UnexpectedNode(unaryOp);
}
public override IProviderType ReturnTypeOfFunction(SqlFunctionCall functionCall)
{
IProviderType[] argumentTypes = this.GetArgumentTypes(functionCall);
var type = (SqlTypeSystem.SqlType)argumentTypes[0];
SqlTypeSystem.SqlType type2 = (argumentTypes.Length > 1) ? ((SqlTypeSystem.SqlType)argumentTypes[1]) : null;
switch (functionCall.Name)
{
case "LEN":
case "DATALENGTH":
switch ((SqlDbType)type.SqlDbType)
{
case SqlDbType.VarBinary:
case SqlDbType.VarChar:
case SqlDbType.NVarChar:
if (type.IsLargeType)
{
return SqlTypeSystem.Create(SqlDbType.BigInt);
}
return SqlTypeSystem.Create(SqlDbType.Int);
}
return SqlTypeSystem.Create(SqlDbType.Int);
case "ABS":
case "SIGN":
case "ROUND":
case "CEILING":
case "FLOOR":
case "POWER":
{
var sqlDbType = (SqlDbType)type.SqlDbType;
//if (sqlDbType > SqlDbType.Real)
//{
//if ((sqlDbType == SqlDbType.SmallInt) || (sqlDbType == SqlDbType.TinyInt))
//{
// //break;
// return Create(SqlDbType.Int);
//}
// return type;
//}
switch (sqlDbType)
{
case SqlDbType.Float:
case SqlDbType.Real:
return SqlTypeSystem.Create(SqlDbType.Float);
case SqlDbType.Image:
return type;
case SqlDbType.SmallInt:
case SqlDbType.TinyInt:
return Create(SqlDbType.Int);
}
return type;
}
case "PATINDEX":
case "CHARINDEX":
if (!type2.IsLargeType)
{
return SqlTypeSystem.Create(SqlDbType.Int);
}
return SqlTypeSystem.Create(SqlDbType.BigInt);
case "SUBSTRING":
{
if (functionCall.Arguments[2].NodeType == SqlNodeType.Value)
{
var value2 = (SqlValue)functionCall.Arguments[2];
if ((value2.Value is int))
{
switch ((SqlDbType)type.SqlDbType)
{
case SqlDbType.NChar:
case SqlDbType.NVarChar:
case SqlDbType.VarChar:
case SqlDbType.Char:
return SqlTypeSystem.Create((SqlDbType)type.SqlDbType, (int)value2.Value);
case SqlDbType.NText:
//goto Label_02D8;
return null;
}
//goto Label_02D8;
return null;
}
//goto Label_02DA;
}
//goto Label_02DA;
switch ((SqlDbType)type.SqlDbType)
{
case SqlDbType.NChar:
case SqlDbType.NVarChar:
return SqlTypeSystem.Create(SqlDbType.NVarChar);
case SqlDbType.VarChar:
case SqlDbType.Char:
return SqlTypeSystem.Create(SqlDbType.VarChar);
default:
return null;
}
}
case "STUFF":
{
var value3 = functionCall.Arguments[2] as SqlValue;
if ((functionCall.Arguments.Count != 4) ||
((value3 == null) || (((int)value3.Value) != 0)))
{
//goto Label_0375;
return null;
}
//if ((value3 == null) || (((int)value3.Value) != 0))
//{
// //goto Label_0375;
// return null;
//}
return this.PredictTypeForBinary(SqlNodeType.Concat, functionCall.Arguments[0].SqlType, functionCall.Arguments[3].SqlType);
}
case "LOWER":
case "UPPER":
case "RTRIM":
case "LTRIM":
case "INSERT":
case "REPLACE":
case "LEFT":
case "RIGHT":
case "REVERSE":
return type;
default:
return null;
}
return SqlTypeSystem.Create(SqlDbType.Int);
Label_02D8:
return null;
Label_02DA:
switch ((SqlDbType)type.SqlDbType)
{
case SqlDbType.NChar:
case SqlDbType.NVarChar:
return SqlTypeSystem.Create(SqlDbType.NVarChar);
case SqlDbType.VarChar:
case SqlDbType.Char:
return SqlTypeSystem.Create(SqlDbType.VarChar);
default:
return null;
}
Label_0375:
return null;
}
// Properties
protected abstract bool SupportsMaxSize { get; }
}
#endregion
internal class Sql2000Provider : SqlTypeSystem.ProviderBase
{
// Methods
public override IProviderType From(Type type, int? size)
{
if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
type = type.GetGenericArguments()[0];
}
TypeCode typeCode = Type.GetTypeCode(type);
switch (typeCode)
{
case TypeCode.Object:
if (type != typeof(Guid))
{
if ((type == typeof(byte[])) || (type == typeof(Binary)))
{
return base.GetBestType(System.Data.SqlDbType.VarBinary, size);
}
if (type == typeof(char[]))
{
return base.GetBestType(System.Data.SqlDbType.NVarChar, size);
}
if (type == typeof(TimeSpan))
{
return SqlTypeSystem.Create(System.Data.SqlDbType.BigInt);
}
if ((type != typeof(XDocument)) && (type != typeof(XElement)))
{
return new SqlTypeSystem.SqlType(type);
}
return SqlTypeSystem.theNText;
}
return SqlTypeSystem.Create(System.Data.SqlDbType.UniqueIdentifier);
case TypeCode.Boolean:
return SqlTypeSystem.Create(System.Data.SqlDbType.Bit);
case TypeCode.Char:
return SqlTypeSystem.Create(System.Data.SqlDbType.NChar, 1);
case TypeCode.SByte:
case TypeCode.Int16:
return SqlTypeSystem.Create(System.Data.SqlDbType.SmallInt);
case TypeCode.Byte:
return SqlTypeSystem.Create(System.Data.SqlDbType.TinyInt);
case TypeCode.UInt16:
case TypeCode.Int32:
return SqlTypeSystem.Create(System.Data.SqlDbType.Int);
case TypeCode.UInt32:
case TypeCode.Int64:
return SqlTypeSystem.Create(System.Data.SqlDbType.BigInt);
case TypeCode.UInt64:
return SqlTypeSystem.Create(System.Data.SqlDbType.Decimal, 20, 0);
case TypeCode.Single:
return SqlTypeSystem.Create(System.Data.SqlDbType.Real);
case TypeCode.Double:
return SqlTypeSystem.Create(System.Data.SqlDbType.Float);
case TypeCode.Decimal:
{
int? nullable = size;
return SqlTypeSystem.Create(System.Data.SqlDbType.Decimal, 0x1d, nullable.HasValue ? nullable.GetValueOrDefault() : 4);
}
case TypeCode.DateTime:
return SqlTypeSystem.Create(System.Data.SqlDbType.DateTime);
case TypeCode.String:
return base.GetBestType(System.Data.SqlDbType.NVarChar, size);
}
throw Error.UnexpectedTypeCode(typeCode);
}
public override IProviderType GetBestLargeType(IProviderType type)
{
var type2 = (SqlTypeSystem.SqlType)type;
switch ((SqlDbType)type2.SqlDbType)
{
case System.Data.SqlDbType.Binary:
case System.Data.SqlDbType.VarBinary:
return SqlTypeSystem.Create(System.Data.SqlDbType.Image);
case System.Data.SqlDbType.Bit:
return type;
case System.Data.SqlDbType.Char:
case System.Data.SqlDbType.VarChar:
return SqlTypeSystem.Create(System.Data.SqlDbType.Text);
case System.Data.SqlDbType.NChar:
case System.Data.SqlDbType.NVarChar:
return SqlTypeSystem.Create(System.Data.SqlDbType.NText);
case System.Data.SqlDbType.NText:
return type;
}
return type;
}
// Properties
protected override bool SupportsMaxSize
{
get
{
return false;
}
}
}
internal class Sql2005Provider : SqlTypeSystem.ProviderBase
{
// Methods
public override IProviderType From(Type type, int? size)
{
if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
type = type.GetGenericArguments()[0];
}
TypeCode typeCode = Type.GetTypeCode(type);
switch (typeCode)
{
case TypeCode.Object:
if (type != typeof(Guid))
{
if ((type == typeof(byte[])) || (type == typeof(Binary)))
{
return base.GetBestType(System.Data.SqlDbType.VarBinary, size);
}
if (type == typeof(char[]))
{
return base.GetBestType(System.Data.SqlDbType.NVarChar, size);
}
if (type == typeof(TimeSpan))
{
return SqlTypeSystem.Create(System.Data.SqlDbType.BigInt);
}
if ((type != typeof(XDocument)) && (type != typeof(XElement)))
{
return new SqlTypeSystem.SqlType(type);
}
return SqlTypeSystem.theChar;
//return SqlTypeSystem.theXml;
}
return SqlTypeSystem.Create(System.Data.SqlDbType.UniqueIdentifier);
case TypeCode.Boolean:
return SqlTypeSystem.Create(System.Data.SqlDbType.Bit);
case TypeCode.Char:
return SqlTypeSystem.Create(System.Data.SqlDbType.NChar, 1);
case TypeCode.SByte:
case TypeCode.Int16:
return SqlTypeSystem.Create(System.Data.SqlDbType.SmallInt);
case TypeCode.Byte:
return SqlTypeSystem.Create(System.Data.SqlDbType.TinyInt);
case TypeCode.UInt16:
case TypeCode.Int32:
return SqlTypeSystem.Create(System.Data.SqlDbType.Int);
case TypeCode.UInt32:
case TypeCode.Int64:
return SqlTypeSystem.Create(System.Data.SqlDbType.BigInt);
case TypeCode.UInt64:
return SqlTypeSystem.Create(System.Data.SqlDbType.Decimal, 20, 0);
case TypeCode.Single:
return SqlTypeSystem.Create(System.Data.SqlDbType.Real);
case TypeCode.Double:
return SqlTypeSystem.Create(System.Data.SqlDbType.Float);
case TypeCode.Decimal:
{
int? nullable = size;
return SqlTypeSystem.Create(System.Data.SqlDbType.Decimal, 0x1d, nullable.HasValue ? nullable.GetValueOrDefault() : 4);
}
case TypeCode.DateTime:
return SqlTypeSystem.Create(System.Data.SqlDbType.DateTime);
case TypeCode.String:
return base.GetBestType(System.Data.SqlDbType.NVarChar, size);
}
throw Error.UnexpectedTypeCode(typeCode);
}
public override IProviderType GetBestLargeType(IProviderType type)
{
var type2 = (SqlTypeSystem.SqlType)type;
switch ((SqlDbType)type2.SqlDbType)
{
case System.Data.SqlDbType.Binary:
case System.Data.SqlDbType.Image:
case System.Data.SqlDbType.VarBinary:
return SqlTypeSystem.Create(System.Data.SqlDbType.VarBinary, -1);
case System.Data.SqlDbType.Bit:
return type;
case System.Data.SqlDbType.Char:
case System.Data.SqlDbType.Text:
case System.Data.SqlDbType.VarChar:
return SqlTypeSystem.Create(System.Data.SqlDbType.VarChar, -1);
case System.Data.SqlDbType.Int:
case System.Data.SqlDbType.Money:
return type;
case System.Data.SqlDbType.NChar:
case System.Data.SqlDbType.NText:
case System.Data.SqlDbType.NVarChar:
return SqlTypeSystem.Create(System.Data.SqlDbType.NVarChar, -1);
case System.Data.SqlDbType.Timestamp:
case System.Data.SqlDbType.TinyInt:
return type;
}
return type;
}
// Properties
protected override bool SupportsMaxSize
{
get
{
return true;
}
}
}
internal class SqlCEProvider : Sql2000Provider
{
// Methods
public override void InitializeParameter(IProviderType type, DbParameter parameter, object value)
{
var type2 = (SqlType)type;
parameter.GetType().GetProperty("SqlDbType").SetValue(parameter, type2.SqlDbType, null);
if (type2.HasPrecisionAndScale)
{
PropertyInfo property = parameter.GetType().GetProperty("Precision");
if (property != null)
{
property.SetValue(parameter, Convert.ChangeType(type2.Precision, property.PropertyType, CultureInfo.InvariantCulture), null);
}
PropertyInfo info3 = parameter.GetType().GetProperty("Scale");
if (info3 != null)
{
info3.SetValue(parameter, Convert.ChangeType(type2.Scale, info3.PropertyType, CultureInfo.InvariantCulture), null);
}
}
parameter.Value = GetParameterValue(type2, value);
if (((parameter.Direction == ParameterDirection.Input) && type2.IsFixedSize) || (parameter.Direction != ParameterDirection.Input))
{
int size = parameter.Size;
if ((size < type2.Size) || type2.IsLargeType)
{
int? nullable2 = type2.Size;
parameter.Size = nullable2.HasValue ? nullable2.GetValueOrDefault() : 0;
}
}
}
}
internal class SqlType : ProviderType<SqlDbType>
{
// Fields
private int? applicationTypeIndex;
protected int precision;
private Type runtimeOnlyType;
protected int scale;
protected int? size;
//protected SqlDbType sqlDbType;
// Methods
internal SqlType(SqlDbType type)
{
applicationTypeIndex = null;
SqlDbType = type;
}
internal SqlType(int applicationTypeIndex)
{
this.applicationTypeIndex = applicationTypeIndex;
}
internal SqlType(Type type)
{
this.applicationTypeIndex = null;
this.runtimeOnlyType = type;
}
internal SqlType(SqlDbType type, int? size)
{
this.applicationTypeIndex = null;
this.SqlDbType = type;// as Enum;//(int)type;
this.size = size;
}
internal SqlType(SqlDbType type, int precision, int scale)
{
this.applicationTypeIndex = null;
this.SqlDbType = type;//(int)type;
this.precision = precision;
this.scale = scale;
}
public override bool AreValuesEqual(object o1, object o2)
{
string str;
if ((o1 == null) || (o2 == null))
{
return false;
}
SqlDbType sqlDbType = (SqlDbType)this.SqlDbType;
if (sqlDbType <= System.Data.SqlDbType.NVarChar)
{
switch (sqlDbType)
{
case System.Data.SqlDbType.NChar:
case System.Data.SqlDbType.NVarChar:
case System.Data.SqlDbType.Char:
goto Label_0039;
case System.Data.SqlDbType.NText:
goto Label_007D;
}
goto Label_007D;
}
if ((sqlDbType != System.Data.SqlDbType.Text) && (sqlDbType != System.Data.SqlDbType.VarChar))
{
goto Label_007D;
}
Label_0039:
str = o1 as string;
if (str != null)
{
string str2 = o2 as string;
if (str2 != null)
{
return str.TrimEnd(new char[] { ' ' }).Equals(str2.TrimEnd(new char[] { ' ' }), StringComparison.Ordinal);
}
}
Label_007D:
return o1.Equals(o2);
}
//public override int ComparePrecedenceTo(IProviderType type)
public override int ComparePrecedenceTo(ProviderType<SqlDbType> type)
{
var type2 = (SqlType)type;
int num = this.IsTypeKnownByProvider ? GetTypeCoercionPrecedence((SqlDbType)this.SqlDbType) : -2147483648;
int num2 = type2.IsTypeKnownByProvider ? GetTypeCoercionPrecedence((SqlDbType)type2.SqlDbType) : -2147483648;
return num.CompareTo(num2);
}
public override bool Equals(object obj)
{
//if (this == obj)
if (ReferenceEquals(this, obj))
{
return true;
}
var type = obj as SqlType;
return (((type != null) && (((runtimeOnlyType == type.runtimeOnlyType) &&
((applicationTypeIndex == type.applicationTypeIndex) && (SqlDbType == type.SqlDbType))) &&
((Size == type.Size) && (precision == type.precision)))) && (scale == type.scale));
}
public override Type GetClosestRuntimeType()
{
if (this.runtimeOnlyType != null)
{
return this.runtimeOnlyType;
}
return SqlTypeSystem.GetClosestRuntimeType((SqlDbType)this.SqlDbType);
}
public override int GetHashCode()
{
int hashCode = 0;
if (this.runtimeOnlyType != null)
{
hashCode = this.runtimeOnlyType.GetHashCode();
}
else if (this.applicationTypeIndex.HasValue)
{
hashCode = this.applicationTypeIndex.Value;
}
int? size = this.size;
return ((((hashCode ^ this.SqlDbType.GetHashCode()) ^ (size.HasValue ? size.GetValueOrDefault() : 0)) ^ this.precision) ^ (this.scale << 8));
}
//public override IProviderType GetNonUnicodeEquivalent()
public override ProviderType<SqlDbType> GetNonUnicodeEquivalent()
{
if (this.IsUnicodeType)
{
switch ((SqlDbType)this.SqlDbType)
{
case System.Data.SqlDbType.NChar:
return new SqlTypeSystem.SqlType(System.Data.SqlDbType.Char, this.Size);
case System.Data.SqlDbType.NText:
return new SqlTypeSystem.SqlType(System.Data.SqlDbType.Text);
case System.Data.SqlDbType.NVarChar:
return new SqlTypeSystem.SqlType(System.Data.SqlDbType.VarChar, this.Size);
}
}
return this;
}
private static int GetTypeCoercionPrecedence(SqlDbType type)
{
switch (type)
{
case System.Data.SqlDbType.BigInt:
return 15;
case System.Data.SqlDbType.Binary:
return 0;
case System.Data.SqlDbType.Bit:
return 11;
case System.Data.SqlDbType.Char:
return 3;
case System.Data.SqlDbType.DateTime:
return 0x16;
case System.Data.SqlDbType.Decimal:
return 0x12;
case System.Data.SqlDbType.Float:
return 20;
case System.Data.SqlDbType.Image:
return 8;
case System.Data.SqlDbType.Int:
return 14;
case System.Data.SqlDbType.Money:
return 0x11;
case System.Data.SqlDbType.NChar:
return 4;
case System.Data.SqlDbType.NText:
return 10;
case System.Data.SqlDbType.NVarChar:
return 5;
case System.Data.SqlDbType.Real:
return 0x13;
case System.Data.SqlDbType.UniqueIdentifier:
return 6;
case System.Data.SqlDbType.SmallDateTime:
return 0x15;
case System.Data.SqlDbType.SmallInt:
return 13;
case System.Data.SqlDbType.SmallMoney:
return 0x10;
case System.Data.SqlDbType.Text:
return 9;
case System.Data.SqlDbType.Timestamp:
return 7;
case System.Data.SqlDbType.TinyInt:
return 12;
case System.Data.SqlDbType.VarBinary:
return 1;
case System.Data.SqlDbType.VarChar:
return 2;
case System.Data.SqlDbType.Variant:
return 0x18;
case System.Data.SqlDbType.Xml:
return 0x17;
case System.Data.SqlDbType.Udt:
return 0x19;
}
throw Error.UnexpectedTypeCode(type);
}
public override bool IsApplicationTypeOf(int index)
{
if (!this.IsApplicationType)
{
return false;
}
int? applicationTypeIndex = this.applicationTypeIndex;
int num = index;
return ((applicationTypeIndex.GetValueOrDefault() == num) && applicationTypeIndex.HasValue);
}
public override bool IsSameTypeFamily(IProviderType type)
{
Debug.Assert(type is SqlType);
var type2 = (SqlType)type;
if (IsApplicationType)
{
return false;
}
if (type2.IsApplicationType)
{
return false;
}
if (Category == type2.Category)
return true;
if (Category == TypeCategory.Text && (type2.Category == TypeCategory.Char || type2.Category == TypeCategory.Xml))
return true;
if (Category == TypeCategory.Image && type2.Category == TypeCategory.Binary)
return true;
return false;
}
protected static string KeyValue<T>(string key, T value)
{
if (value != null)
{
return (key + "=" + value.ToString() + " ");
}
return string.Empty;
}
protected static string SingleValue<T>(T value)
{
if (value != null)
{
return (value.ToString() + " ");
}
return string.Empty;
}
public override string ToQueryString()
{
return ToQueryString(QueryFormatOptions.None);
}
public override string ToQueryString(QueryFormatOptions formatFlags)
{
Debug.Assert(formatFlags == QueryFormatOptions.None ||
formatFlags == QueryFormatOptions.SuppressSize);
if (runtimeOnlyType != null)
{
return runtimeOnlyType.ToString();
}
var builder = new StringBuilder();
switch ((SqlDbType)SqlDbType)
{
case System.Data.SqlDbType.BigInt:
case System.Data.SqlDbType.Bit:
case System.Data.SqlDbType.DateTime:
case System.Data.SqlDbType.Image:
case System.Data.SqlDbType.Int:
case System.Data.SqlDbType.Money:
case System.Data.SqlDbType.NText:
case System.Data.SqlDbType.UniqueIdentifier:
case System.Data.SqlDbType.SmallDateTime:
case System.Data.SqlDbType.SmallInt:
case System.Data.SqlDbType.SmallMoney:
case System.Data.SqlDbType.Text:
case System.Data.SqlDbType.Timestamp:
case System.Data.SqlDbType.TinyInt:
case System.Data.SqlDbType.Xml:
case System.Data.SqlDbType.Udt:
builder.Append(SqlDbType.ToString());
return builder.ToString();
case System.Data.SqlDbType.Binary:
case System.Data.SqlDbType.Char:
case System.Data.SqlDbType.NChar:
builder.Append(SqlDbType);
//if ((formatFlags & QueryFormatOptions.SuppressSize) == QueryFormatOptions.None)
if (formatFlags == QueryFormatOptions.None)
{
builder.Append("(");
builder.Append(size);
builder.Append(")");
}
return builder.ToString();
case System.Data.SqlDbType.Decimal:
case System.Data.SqlDbType.Float:
case System.Data.SqlDbType.Real:
builder.Append(this.SqlDbType);
if (this.precision != 0)
{
builder.Append("(");
builder.Append(precision);
if (this.scale != 0)
{
builder.Append(",");
builder.Append(this.scale);
}
builder.Append(")");
}
return builder.ToString();
case System.Data.SqlDbType.NVarChar:
case System.Data.SqlDbType.VarBinary:
case System.Data.SqlDbType.VarChar:
builder.Append(SqlDbType);
if (!size.HasValue ||
//((size == 0) || ((formatFlags & QueryFormatOptions.SuppressSize) != QueryFormatOptions.None)))
((size == 0) || (formatFlags == QueryFormatOptions.SuppressSize)))
{
return builder.ToString();
}
builder.Append("(");
if (size != -1)
builder.Append(size);
else
builder.Append("MAX");
builder.Append(")");
return builder.ToString();
case System.Data.SqlDbType.Variant:
builder.Append("sql_variant");
return builder.ToString();
default:
return builder.ToString();
}
}
public override string ToString()
{
return (SingleValue(GetClosestRuntimeType()) + SingleValue(ToQueryString()) + KeyValue("IsApplicationType", IsApplicationType) + KeyValue<bool>("IsUnicodeType", this.IsUnicodeType) + KeyValue<bool>("IsRuntimeOnlyType", this.IsRuntimeOnlyType) + KeyValue<bool>("SupportsComparison", this.SupportsComparison) + KeyValue<bool>("SupportsLength", this.SupportsLength) + KeyValue<bool>("IsLargeType", this.IsLargeType) + KeyValue<bool>("IsFixedSize", this.IsFixedSize) + KeyValue<bool>("IsOrderable", this.IsOrderable) + KeyValue<bool>("IsGroupable", this.IsGroupable) + KeyValue<bool>("IsNumeric", this.IsNumeric) + KeyValue<bool>("IsChar", this.IsChar) + KeyValue<bool>("IsString", this.IsString));
}
// Properties
public override bool CanBeColumn
{
get
{
return (!this.IsApplicationType && !this.IsRuntimeOnlyType);
}
}
public override bool CanBeParameter
{
get
{
return (!this.IsApplicationType && !this.IsRuntimeOnlyType);
}
}
public override bool CanSuppressSizeForConversionToString
{
get
{
int num = 30;
if (!this.IsLargeType)
{
if (((!this.IsChar && !this.IsString) && this.IsFixedSize) && (this.Size > 0))
{
int? size = this.Size;
int num2 = num;
return ((size.GetValueOrDefault() < num2) && size.HasValue);
}
switch ((SqlDbType)this.SqlDbType)
{
case System.Data.SqlDbType.Real:
case System.Data.SqlDbType.SmallInt:
case System.Data.SqlDbType.SmallMoney:
case System.Data.SqlDbType.TinyInt:
case System.Data.SqlDbType.BigInt:
case System.Data.SqlDbType.Bit:
case System.Data.SqlDbType.Float:
case System.Data.SqlDbType.Int:
case System.Data.SqlDbType.Money:
return true;
}
}
return false;
}
}
internal TypeCategory Category
{
get
{
switch ((SqlDbType)this.SqlDbType)
{
case System.Data.SqlDbType.BigInt:
case System.Data.SqlDbType.Bit:
case System.Data.SqlDbType.Decimal:
case System.Data.SqlDbType.Float:
case System.Data.SqlDbType.Int:
case System.Data.SqlDbType.Money:
case System.Data.SqlDbType.Real:
case System.Data.SqlDbType.SmallInt:
case System.Data.SqlDbType.SmallMoney:
case System.Data.SqlDbType.TinyInt:
return TypeCategory.Numeric;
case System.Data.SqlDbType.Binary:
case System.Data.SqlDbType.Timestamp:
case System.Data.SqlDbType.VarBinary:
return TypeCategory.Binary;
case System.Data.SqlDbType.Char:
case System.Data.SqlDbType.NChar:
case System.Data.SqlDbType.NVarChar:
case System.Data.SqlDbType.VarChar:
return TypeCategory.Char;
case System.Data.SqlDbType.Date:
case System.Data.SqlDbType.DateTime:
case System.Data.SqlDbType.SmallDateTime:
return TypeCategory.DateTime;
case System.Data.SqlDbType.Image:
return TypeCategory.Image;
case System.Data.SqlDbType.NText:
case System.Data.SqlDbType.Text:
return TypeCategory.Text;
case System.Data.SqlDbType.UniqueIdentifier:
return TypeCategory.UniqueIdentifier;
case System.Data.SqlDbType.Variant:
return TypeCategory.Variant;
case System.Data.SqlDbType.Xml:
return TypeCategory.Xml;
case System.Data.SqlDbType.Udt:
return TypeCategory.Udt;
}
throw Error.UnexpectedTypeCode(this);
}
}
public override bool HasPrecisionAndScale
{
get
{
switch ((SqlDbType)this.SqlDbType)
{
case System.Data.SqlDbType.Decimal:
case System.Data.SqlDbType.Float:
case System.Data.SqlDbType.Money:
case System.Data.SqlDbType.Real:
case System.Data.SqlDbType.SmallMoney:
return true;
}
return false;
}
}
public override bool HasSizeOrIsLarge
{
get
{
if (!this.size.HasValue)
{
return this.IsLargeType;
}
return true;
}
}
public override bool IsApplicationType
{
get
{
return this.applicationTypeIndex.HasValue;
}
}
public override bool IsChar
{
get
{
if (!this.IsApplicationType && !this.IsRuntimeOnlyType)
{
switch ((SqlDbType)this.SqlDbType)
{
case System.Data.SqlDbType.NChar:
case System.Data.SqlDbType.NVarChar:
case System.Data.SqlDbType.VarChar:
case System.Data.SqlDbType.Char:
return (this.Size == 1);
}
}
return false;
}
}
public override bool IsFixedSize
{
get
{
switch ((SqlDbType)this.SqlDbType)
{
case System.Data.SqlDbType.Text:
case System.Data.SqlDbType.VarBinary:
case System.Data.SqlDbType.VarChar:
case System.Data.SqlDbType.Xml:
case System.Data.SqlDbType.NText:
case System.Data.SqlDbType.NVarChar:
case System.Data.SqlDbType.Image:
return false;
}
return true;
}
}
public override bool IsGroupable
{
get
{
if (this.IsRuntimeOnlyType)
{
return false;
}
var sqlDbType = (SqlDbType)this.SqlDbType;
if (sqlDbType <= System.Data.SqlDbType.NText)
{
switch (sqlDbType)
{
case System.Data.SqlDbType.Image:
case System.Data.SqlDbType.NText:
goto Label_002B;
}
goto Label_002D;
}
if ((sqlDbType != System.Data.SqlDbType.Text) && (sqlDbType != System.Data.SqlDbType.Xml))
{
goto Label_002D;
}
Label_002B:
return false;
Label_002D:
return true;
}
}
public override bool IsLargeType
{
get
{
switch ((SqlDbType)this.SqlDbType)
{
case System.Data.SqlDbType.Text:
case System.Data.SqlDbType.Xml:
case System.Data.SqlDbType.NText:
case System.Data.SqlDbType.Image:
return true;
case System.Data.SqlDbType.VarBinary:
case System.Data.SqlDbType.VarChar:
case System.Data.SqlDbType.NVarChar:
return (this.size == -1);
}
return false;
}
}
public override bool IsNumeric
{
get
{
if (!this.IsApplicationType && !this.IsRuntimeOnlyType)
{
switch ((SqlDbType)(SqlDbType)this.SqlDbType)
{
case System.Data.SqlDbType.BigInt:
case System.Data.SqlDbType.Bit:
case System.Data.SqlDbType.Decimal:
case System.Data.SqlDbType.Float:
case System.Data.SqlDbType.Int:
case System.Data.SqlDbType.Money:
case System.Data.SqlDbType.Real:
case System.Data.SqlDbType.SmallInt:
case System.Data.SqlDbType.SmallMoney:
case System.Data.SqlDbType.TinyInt:
return true;
}
}
return false;
}
}
public override bool IsOrderable
{
get
{
if (this.IsRuntimeOnlyType)
{
return false;
}
SqlDbType sqlDbType = (SqlDbType)this.SqlDbType;
if (sqlDbType <= System.Data.SqlDbType.NText)
{
switch (sqlDbType)
{
case System.Data.SqlDbType.Image:
case System.Data.SqlDbType.NText:
goto Label_002B;
}
goto Label_002D;
}
if ((sqlDbType != System.Data.SqlDbType.Text) && (sqlDbType != System.Data.SqlDbType.Xml))
{
goto Label_002D;
}
Label_002B:
return false;
Label_002D:
return true;
}
}
public override bool IsRuntimeOnlyType
{
get
{
return (this.runtimeOnlyType != null);
}
}
public override bool IsString
{
get
{
int? nullable;
if (this.IsApplicationType || this.IsRuntimeOnlyType)
{
return false;
}
SqlDbType sqlDbType = (SqlDbType)this.SqlDbType;
if (sqlDbType <= System.Data.SqlDbType.NVarChar)
{
switch (sqlDbType)
{
case System.Data.SqlDbType.NChar:
case System.Data.SqlDbType.NVarChar:
case System.Data.SqlDbType.Char:
goto Label_0043;
case System.Data.SqlDbType.NText:
goto Label_0099;
}
goto Label_009B;
}
if (sqlDbType == System.Data.SqlDbType.Text)
{
goto Label_0099;
}
if (sqlDbType != System.Data.SqlDbType.VarChar)
{
goto Label_009B;
}
Label_0043:
nullable = this.Size;
if (((nullable.GetValueOrDefault() != 0) || !nullable.HasValue) && (this.Size <= 1))
{
return (this.Size == -1);
}
return true;
Label_0099:
return true;
Label_009B:
return false;
}
}
public override bool IsBinary
{
get { return Category == TypeCategory.Binary; }
}
public override bool IsDateTime
{
get { return Category == TypeCategory.DateTime; }
}
private bool IsTypeKnownByProvider
{
get
{
return (!this.IsApplicationType && !this.IsRuntimeOnlyType);
}
}
public override bool IsUnicodeType
{
get
{
switch ((SqlDbType)this.SqlDbType)
{
case System.Data.SqlDbType.NChar:
case System.Data.SqlDbType.NText:
case System.Data.SqlDbType.NVarChar:
return true;
}
return false;
}
}
public override int Precision
{
get
{
return this.precision;
}
}
public override int Scale
{
get
{
return this.scale;
}
}
public override SqlDbType SqlDbType
{
get;
set;
}
public override int? ApplicationTypeIndex
{
get { return applicationTypeIndex; }
set { applicationTypeIndex = value; }
}
public override Type RuntimeOnlyType
{
get { return runtimeOnlyType; }
set { runtimeOnlyType = value; }
}
public override int? Size
{
get
{
return this.size;
}
}
//public override Enum SqlDbType
//{
// get
// {
// return this.sqlDbType;
// }
// set { sqlDbType = (SqlDbType) value; }
//}
public override bool SupportsComparison
{
get
{
SqlDbType sqlDbType = (SqlDbType)this.SqlDbType;
if (sqlDbType <= System.Data.SqlDbType.NText)
{
switch (sqlDbType)
{
case System.Data.SqlDbType.Image:
case System.Data.SqlDbType.NText:
goto Label_0021;
}
goto Label_0023;
}
if ((sqlDbType != System.Data.SqlDbType.Text) && (sqlDbType != System.Data.SqlDbType.Xml))
{
goto Label_0023;
}
Label_0021:
return false;
Label_0023:
return true;
}
}
public override bool SupportsLength
{
get
{
//SqlDbType sqlDbType = this.sqlDbType;
//if (sqlDbType <= System.Data.SqlDbType.NText)
//{
switch ((SqlDbType)SqlDbType)
{
case System.Data.SqlDbType.Image:
case System.Data.SqlDbType.NText:
case System.Data.SqlDbType.Text:
case System.Data.SqlDbType.Xml:
return false;
}
return true;
//}
//if ((sqlDbType == System.Data.SqlDbType.Text) || (sqlDbType == System.Data.SqlDbType.Xml))
//{
//Label_0021:
// return false;
//Label_0023:
// return true;
//}
//return true;
}
}
// Nested Types
internal enum TypeCategory
{
Numeric,
Char,
Text,
Binary,
Image,
Xml,
DateTime,
UniqueIdentifier,
Variant,
Udt
}
}
}
}
| |
namespace java.lang.reflect
{
[global::MonoJavaBridge.JavaClass()]
public partial class Modifier : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected Modifier(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public static global::java.lang.String toString(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.reflect.Modifier._m0.native == global::System.IntPtr.Zero)
global::java.lang.reflect.Modifier._m0 = @__env.GetStaticMethodIDNoThrow(global::java.lang.reflect.Modifier.staticClass, "toString", "(I)Ljava/lang/String;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.lang.reflect.Modifier.staticClass, global::java.lang.reflect.Modifier._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m1;
public static bool isInterface(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.reflect.Modifier._m1.native == global::System.IntPtr.Zero)
global::java.lang.reflect.Modifier._m1 = @__env.GetStaticMethodIDNoThrow(global::java.lang.reflect.Modifier.staticClass, "isInterface", "(I)Z");
return @__env.CallStaticBooleanMethod(java.lang.reflect.Modifier.staticClass, global::java.lang.reflect.Modifier._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m2;
public static bool isAbstract(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.reflect.Modifier._m2.native == global::System.IntPtr.Zero)
global::java.lang.reflect.Modifier._m2 = @__env.GetStaticMethodIDNoThrow(global::java.lang.reflect.Modifier.staticClass, "isAbstract", "(I)Z");
return @__env.CallStaticBooleanMethod(java.lang.reflect.Modifier.staticClass, global::java.lang.reflect.Modifier._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m3;
public static bool isProtected(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.reflect.Modifier._m3.native == global::System.IntPtr.Zero)
global::java.lang.reflect.Modifier._m3 = @__env.GetStaticMethodIDNoThrow(global::java.lang.reflect.Modifier.staticClass, "isProtected", "(I)Z");
return @__env.CallStaticBooleanMethod(java.lang.reflect.Modifier.staticClass, global::java.lang.reflect.Modifier._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m4;
public static bool isFinal(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.reflect.Modifier._m4.native == global::System.IntPtr.Zero)
global::java.lang.reflect.Modifier._m4 = @__env.GetStaticMethodIDNoThrow(global::java.lang.reflect.Modifier.staticClass, "isFinal", "(I)Z");
return @__env.CallStaticBooleanMethod(java.lang.reflect.Modifier.staticClass, global::java.lang.reflect.Modifier._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m5;
public static bool isStatic(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.reflect.Modifier._m5.native == global::System.IntPtr.Zero)
global::java.lang.reflect.Modifier._m5 = @__env.GetStaticMethodIDNoThrow(global::java.lang.reflect.Modifier.staticClass, "isStatic", "(I)Z");
return @__env.CallStaticBooleanMethod(java.lang.reflect.Modifier.staticClass, global::java.lang.reflect.Modifier._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m6;
public static bool isPublic(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.reflect.Modifier._m6.native == global::System.IntPtr.Zero)
global::java.lang.reflect.Modifier._m6 = @__env.GetStaticMethodIDNoThrow(global::java.lang.reflect.Modifier.staticClass, "isPublic", "(I)Z");
return @__env.CallStaticBooleanMethod(java.lang.reflect.Modifier.staticClass, global::java.lang.reflect.Modifier._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m7;
public static bool isPrivate(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.reflect.Modifier._m7.native == global::System.IntPtr.Zero)
global::java.lang.reflect.Modifier._m7 = @__env.GetStaticMethodIDNoThrow(global::java.lang.reflect.Modifier.staticClass, "isPrivate", "(I)Z");
return @__env.CallStaticBooleanMethod(java.lang.reflect.Modifier.staticClass, global::java.lang.reflect.Modifier._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m8;
public static bool isSynchronized(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.reflect.Modifier._m8.native == global::System.IntPtr.Zero)
global::java.lang.reflect.Modifier._m8 = @__env.GetStaticMethodIDNoThrow(global::java.lang.reflect.Modifier.staticClass, "isSynchronized", "(I)Z");
return @__env.CallStaticBooleanMethod(java.lang.reflect.Modifier.staticClass, global::java.lang.reflect.Modifier._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m9;
public static bool isVolatile(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.reflect.Modifier._m9.native == global::System.IntPtr.Zero)
global::java.lang.reflect.Modifier._m9 = @__env.GetStaticMethodIDNoThrow(global::java.lang.reflect.Modifier.staticClass, "isVolatile", "(I)Z");
return @__env.CallStaticBooleanMethod(java.lang.reflect.Modifier.staticClass, global::java.lang.reflect.Modifier._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m10;
public static bool isTransient(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.reflect.Modifier._m10.native == global::System.IntPtr.Zero)
global::java.lang.reflect.Modifier._m10 = @__env.GetStaticMethodIDNoThrow(global::java.lang.reflect.Modifier.staticClass, "isTransient", "(I)Z");
return @__env.CallStaticBooleanMethod(java.lang.reflect.Modifier.staticClass, global::java.lang.reflect.Modifier._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m11;
public static bool isNative(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.reflect.Modifier._m11.native == global::System.IntPtr.Zero)
global::java.lang.reflect.Modifier._m11 = @__env.GetStaticMethodIDNoThrow(global::java.lang.reflect.Modifier.staticClass, "isNative", "(I)Z");
return @__env.CallStaticBooleanMethod(java.lang.reflect.Modifier.staticClass, global::java.lang.reflect.Modifier._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m12;
public static bool isStrict(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.reflect.Modifier._m12.native == global::System.IntPtr.Zero)
global::java.lang.reflect.Modifier._m12 = @__env.GetStaticMethodIDNoThrow(global::java.lang.reflect.Modifier.staticClass, "isStrict", "(I)Z");
return @__env.CallStaticBooleanMethod(java.lang.reflect.Modifier.staticClass, global::java.lang.reflect.Modifier._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m13;
public Modifier() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.reflect.Modifier._m13.native == global::System.IntPtr.Zero)
global::java.lang.reflect.Modifier._m13 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Modifier.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.reflect.Modifier.staticClass, global::java.lang.reflect.Modifier._m13);
Init(@__env, handle);
}
public static int PUBLIC
{
get
{
return 1;
}
}
public static int PRIVATE
{
get
{
return 2;
}
}
public static int PROTECTED
{
get
{
return 4;
}
}
public static int STATIC
{
get
{
return 8;
}
}
public static int FINAL
{
get
{
return 16;
}
}
public static int SYNCHRONIZED
{
get
{
return 32;
}
}
public static int VOLATILE
{
get
{
return 64;
}
}
public static int TRANSIENT
{
get
{
return 128;
}
}
public static int NATIVE
{
get
{
return 256;
}
}
public static int INTERFACE
{
get
{
return 512;
}
}
public static int ABSTRACT
{
get
{
return 1024;
}
}
public static int STRICT
{
get
{
return 2048;
}
}
static Modifier()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.lang.reflect.Modifier.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/lang/reflect/Modifier"));
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Security.Cryptography;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace ViewNet
{
class DHToAES256Manager : ICryptoManager
{
#region Working Objects
readonly Rijndael Rij = Rijndael.Create ();
IViewClient client { get; set; }
ConcurrentQueue<byte[]> DecryptedNormalPackets = new ConcurrentQueue<byte[]> ();
volatile bool _IsRunning;
Thread cryptoThread { get; set; }
ConcurrentQueue<byte[]> SendingPackets = new ConcurrentQueue<byte[]> ();
DateTime CheckForKeyDate = DateTime.UtcNow;
volatile bool FirstExchange;
volatile bool IsHost;
volatile bool MiddleOfTransition;
volatile bool ChangingKey;
/// <summary>
/// The crypto cycle.
/// 0 = Key is not exchanged...
/// 1 = DH is exchanged only once. ALL OTHER PACKETS THAN DH EXCHANGES ARE FORBIDDEN.
/// 2 = Second DH exchange is encrypted and allowing minimum security. All packets are permitted for exchanges.
/// </summary>
int CryptoCycle;
/// <summary>
/// The Diffie-Hellman Module.
/// This is the primary means of exchanging new encryption keys across the network.
/// </summary>
DiffieHellman CoreDH = new DiffieHellman ();
/// <summary>
/// First Send Boolean
/// </summary>
volatile bool SendTheNewKeyNow;
#endregion
public bool IsRunning {
get {
return _IsRunning;
}
}
public DHToAES256Manager (IPEndPoint ipendpoint)
{
client = new ViewTCPClient (ipendpoint.Address, (ushort)ipendpoint.Port);
}
public DHToAES256Manager (TcpClient tcpClient)
{
client = new ViewTCPClient (tcpClient);
IsHost = true;
FirstExchange = true;
}
#region Public Methods
/// <summary>
/// Start this instance.
/// </summary>
public void Start ()
{
if (_IsRunning)
return;
if (cryptoThread != null) {
if (cryptoThread.ThreadState == ThreadState.Running)
return;
}
_IsRunning = true;
cryptoThread = new Thread (ThreadProcess);
cryptoThread.Name = "Crypto Thread";
cryptoThread.Start ();
}
/// <summary>
/// Stop this instance.
/// </summary>
public void Stop ()
{
if (!_IsRunning)
return;
_IsRunning = false;
lock (client)
client.Stop ();
}
/// <summary>
/// Sends the message.
/// </summary>
/// <param name="content">Content.</param>
public void SendMessage (byte[] content)
{
if (content.Length == 0)
return;
SendingPackets.Enqueue (content);
}
/// <summary>
/// Get the count of availables packets.
/// </summary>
/// <returns>The packets.</returns>
public int AvailablePackets ()
{
int countOfPackets;
countOfPackets = DecryptedNormalPackets.Count;
return countOfPackets;
}
/// <summary>
/// Retrieves the packet.
/// </summary>
/// <returns>The packet.</returns>
public byte[] RetrievePacket ()
{
byte[] info;
DecryptedNormalPackets.TryDequeue (out info);
return info;
}
/// <summary>
/// Allow host to invoke a request to initiate a new key exchange
/// </summary>
public void NewPublicKey ()
{
if (!IsHost)
return;
SendNewKeyRequest ();
}
#endregion
#region Private Methods
void ThreadProcess ()
{
try {
while (_IsRunning &&
client.IsConnected) {
Process ();
Thread.Sleep (1);
}
} catch (Exception) {
Stop ();
}
}
void SetToNewCryptoKey ()
{
if (CoreDH.Key.Length < 32) {
if (IsHost)
SendNewKeyRequest ();
return;
}
byte[] NewKeyToUse = SpecialXORIficateTheKey (CoreDH.Key);
Rij.Key = NewKeyToUse;
if (CryptoCycle < 2) // Incase if someone had to exchange key more times than there are in Int32...
CryptoCycle++;
}
static byte[] SpecialXORIficateTheKey (byte[] massBuffer)
{
if (massBuffer.Length <= 32)
return massBuffer;
var Mainbuffer = new byte[32];
Array.Copy (massBuffer, Mainbuffer, 32);
int current = 0;
for (int I = 32; I < massBuffer.Length; I++) {
Mainbuffer [current] ^= massBuffer [I];
current++;
if (current == 32)
current = 0;
}
return Mainbuffer;
}
Rijndael GetTemporaryNewCrypto ()
{
if (CoreDH.Key.Length < 32)
return Rij;
byte[] NewKeyToUse = SpecialXORIficateTheKey (CoreDH.Key);
Rijndael tempCrypto = Rijndael.Create ();
tempCrypto.Key = NewKeyToUse;
return tempCrypto;
}
void Process ()
{
Packet newPacket;
lock (client) {
// Send a new request for new key
if (CheckForKeyDate.AddMinutes (5) < DateTime.UtcNow && CryptoCycle >= 2 && !ChangingKey && IsHost ||
SendTheNewKeyNow) {
SendNewKeyRequest ();
CheckForKeyDate = DateTime.UtcNow;
SendTheNewKeyNow = false;
ChangingKey = true;
}
if (FirstExchange && IsHost) {
SendFirstKeyRequest ();
FirstExchange = false;
}
// Recieve Process
if (client.CountRecievedPacket () > 0) {
// Pop the Packet, prepare the byte array... then check against the identifier of that packet...
newPacket = client.DequeueRetrievedPacket ();
switch (newPacket.TypeOfPacket) {
case PacketType.Normal:
{
if (CryptoCycle < 2) {
// Software Policy Violation. Disconnect.
Stop ();
return;
}
DecryptedNormalPackets.Enqueue (DecryptBytes (newPacket.Content));
break;
}
case PacketType.NewKey:
{
try {
// Only host is allowed to do this, if sent by Client, AUTODISCONNECT!
if (IsHost){
Stop();
return;
}
if (CryptoCycle == 0) {
var sendTo = CoreDH.GenerateResponse (newPacket.Content);
if (CoreDH.Key.Length < 32)
throw new Exception ();
client.EnqueueSendingPacket (new Packet (PacketType.ReplyExchange, sendTo));
} else {
var sendTo = CoreDH.GenerateResponse (DecryptBytes (newPacket.Content));
if (CoreDH.Key.Length < 32)
throw new Exception ();
client.EnqueueSendingPacket (new Packet (PacketType.ReplyExchange, EncryptBytes (sendTo)));
}
} catch (Exception) {
client.EnqueueSendingPacket (new Packet (PacketType.KeyResponseError, new byte[0]));
break;
}
MiddleOfTransition = true;
break;
}
case PacketType.ReplyExchange:
{
if (CryptoCycle == 0) {
CoreDH.HandleResponse (newPacket.Content);
} else {
CoreDH.HandleResponse (DecryptBytes (newPacket.Content));
}
client.EnqueueSendingPacket (new Packet (PacketType.NotifyEnc, new byte[0]));
SetToNewCryptoKey ();
ChangingKey = false;
if (CryptoCycle < 2) {
SendNewKeyRequest ();
}
break;
}
case PacketType.NotifyEnc:
{
MiddleOfTransition = false;
SetToNewCryptoKey ();
break;
}
// DH can fail, so this is made for fixing this error by
// regenerating new DH key.
case PacketType.KeyResponseError:
{
if (CryptoCycle == 0) {
SendFirstKeyRequest ();
} else {
SendNewKeyRequest ();
}
break;
}
default:
{
Stop (); // Software Policy Violation. DISCONNECT ALL THE THINGS!
break;
}
}
}
if (CryptoCycle >= 2 && SendingPackets.Count > 0) {
byte[] content;
bool successCheck = SendingPackets.TryDequeue (out content);
if (!successCheck)
return;
if (MiddleOfTransition) {
client.EnqueueSendingPacket (new Packet (PacketType.Normal, TempEncryptBytes (GetTemporaryNewCrypto (), content)));
} else {
client.EnqueueSendingPacket (new Packet (PacketType.Normal, EncryptBytes (content)));
}
}
}
}
#endregion
void SendFirstKeyRequest ()
{
var firstPub = CoreDH.GenerateRequest ();
client.EnqueueSendingPacket (new Packet (PacketType.NewKey, firstPub));
ChangingKey = true;
}
void SendNewKeyRequest ()
{
var newReq = CoreDH.GenerateRequest ();
client.EnqueueSendingPacket (new Packet (PacketType.NewKey, EncryptBytes (newReq)));
ChangingKey = true;
}
byte[] EncryptBytes (byte[] message)
{
if ((message == null) || (message.Length == 0)) {
return message;
}
Rij.GenerateIV ();
using (var outStream = new MemoryStream ()) {
DataUtility.WriteBytesToStream (Rij.IV, outStream);
DataUtility.WriteBytesToStream (Rij.CreateEncryptor ().TransformFinalBlock (message, 0, message.Length), outStream);
return outStream.ToArray ();
}
}
static byte[] TempEncryptBytes (SymmetricAlgorithm crypto, byte[] message)
{
if ((message == null) || (message.Length == 0)) {
return message;
}
crypto.GenerateIV ();
using (var outStream = new MemoryStream ()) {
DataUtility.WriteBytesToStream (crypto.IV, outStream);
DataUtility.WriteBytesToStream (crypto.CreateEncryptor ().TransformFinalBlock (message, 0, message.Length), outStream);
return outStream.ToArray ();
}
}
byte[] DecryptBytes (byte[] message)
{
if ((message == null) || (message.Length == 0)) {
return message;
}
byte[] restOfData;
using (var inStream = new MemoryStream (message)) {
Rij.IV = DataUtility.ReadBytesFromStream (inStream);
restOfData = DataUtility.ReadBytesFromStream (inStream);
}
var result = Rij.CreateDecryptor ().TransformFinalBlock (restOfData, 0, restOfData.Length);
return result;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Nini.Config;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Drawing;
using System.Reflection;
namespace OpenSim.Region.CoreModules.World.LegacyMap
{
public class ShadedMapTileRenderer : IMapTileTerrainRenderer
{
private static readonly Color WATER_COLOR = Color.FromArgb(29, 71, 95);
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly string LogHeader = "[SHADED MAPTILE RENDERER]";
private Scene m_scene;
//private IConfigSource m_config; // not used currently
public void Initialise(Scene scene, IConfigSource config)
{
m_scene = scene;
// m_config = config; // not used currently
}
public void TerrainToBitmap(Bitmap mapbmp)
{
m_log.DebugFormat("{0} Generating Maptile Step 1: Terrain", LogHeader);
int tc = Environment.TickCount;
ITerrainChannel hm = m_scene.Heightmap;
if (mapbmp.Width != hm.Width || mapbmp.Height != hm.Height)
{
m_log.ErrorFormat("{0} TerrainToBitmap. Passed bitmap wrong dimensions. passed=<{1},{2}>, size=<{3},{4}>",
LogHeader, mapbmp.Width, mapbmp.Height, hm.Width, hm.Height);
}
bool ShadowDebugContinue = true;
bool terraincorruptedwarningsaid = false;
float low = 255;
float high = 0;
for (int x = 0; x < hm.Width; x++)
{
for (int y = 0; y < hm.Height; y++)
{
float hmval = (float)hm[x, y];
if (hmval < low)
low = hmval;
if (hmval > high)
high = hmval;
}
}
float waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight;
for (int x = 0; x < hm.Width; x++)
{
for (int y = 0; y < hm.Height; y++)
{
// Y flip the cordinates for the bitmap: hf origin is lower left, bm origin is upper left
int yr = ((int)hm.Height - 1) - y;
float heightvalue = (float)hm[x, y];
if (heightvalue > waterHeight)
{
// scale height value
// No, that doesn't scale it:
// heightvalue = low + mid * (heightvalue - low) / mid; => low + (heightvalue - low) * mid / mid = low + (heightvalue - low) * 1 = low + heightvalue - low = heightvalue
if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue))
heightvalue = 0;
else if (heightvalue > 255f)
heightvalue = 255f;
else if (heightvalue < 0f)
heightvalue = 0f;
Color color = Color.FromArgb((int)heightvalue, 100, (int)heightvalue);
mapbmp.SetPixel(x, yr, color);
try
{
//X
// .
//
// Shade the terrain for shadows
if (x < (hm.Width - 1) && yr < (hm.Height - 1))
{
float hfvalue = (float)hm[x, y];
float hfvaluecompare = 0f;
if ((x + 1 < hm.Width) && (y + 1 < hm.Height))
{
hfvaluecompare = (float)hm[x + 1, y + 1]; // light from north-east => look at land height there
}
if (Single.IsInfinity(hfvalue) || Single.IsNaN(hfvalue))
hfvalue = 0f;
if (Single.IsInfinity(hfvaluecompare) || Single.IsNaN(hfvaluecompare))
hfvaluecompare = 0f;
float hfdiff = hfvalue - hfvaluecompare; // => positive if NE is lower, negative if here is lower
int hfdiffi = 0;
int hfdiffihighlight = 0;
float highlightfactor = 0.18f;
try
{
// hfdiffi = Math.Abs((int)((hfdiff * 4) + (hfdiff * 0.5))) + 1;
hfdiffi = Math.Abs((int)(hfdiff * 4.5f)) + 1;
if (hfdiff % 1f != 0)
{
// hfdiffi = hfdiffi + Math.Abs((int)(((hfdiff % 1) * 0.5f) * 10f) - 1);
hfdiffi = hfdiffi + Math.Abs((int)((hfdiff % 1f) * 5f) - 1);
}
hfdiffihighlight = Math.Abs((int)((hfdiff * highlightfactor) * 4.5f)) + 1;
if (hfdiff % 1f != 0)
{
// hfdiffi = hfdiffi + Math.Abs((int)(((hfdiff % 1) * 0.5f) * 10f) - 1);
hfdiffihighlight = hfdiffihighlight + Math.Abs((int)(((hfdiff * highlightfactor) % 1f) * 5f) - 1);
}
}
catch (OverflowException)
{
m_log.Debug("[MAPTILE]: Shadow failed at value: " + hfdiff.ToString());
ShadowDebugContinue = false;
}
if (hfdiff > 0.3f)
{
// NE is lower than here
// We have to desaturate and lighten the land at the same time
// we use floats, colors use bytes, so shrink are space down to
// 0-255
if (ShadowDebugContinue)
{
int r = color.R;
int g = color.G;
int b = color.B;
color = Color.FromArgb((r + hfdiffihighlight < 255) ? r + hfdiffihighlight : 255,
(g + hfdiffihighlight < 255) ? g + hfdiffihighlight : 255,
(b + hfdiffihighlight < 255) ? b + hfdiffihighlight : 255);
}
}
else if (hfdiff < -0.3f)
{
// here is lower than NE:
// We have to desaturate and blacken the land at the same time
// we use floats, colors use bytes, so shrink are space down to
// 0-255
if (ShadowDebugContinue)
{
if ((x - 1 > 0) && (yr + 1 < hm.Height))
{
color = mapbmp.GetPixel(x - 1, yr + 1);
int r = color.R;
int g = color.G;
int b = color.B;
color = Color.FromArgb((r - hfdiffi > 0) ? r - hfdiffi : 0,
(g - hfdiffi > 0) ? g - hfdiffi : 0,
(b - hfdiffi > 0) ? b - hfdiffi : 0);
mapbmp.SetPixel(x-1, yr+1, color);
}
}
}
}
}
catch (ArgumentException)
{
if (!terraincorruptedwarningsaid)
{
m_log.WarnFormat("[SHADED MAP TILE RENDERER]: Your terrain is corrupted in region {0}, it might take a few minutes to generate the map image depending on the corruption level", m_scene.RegionInfo.RegionName);
terraincorruptedwarningsaid = true;
}
color = Color.Black;
mapbmp.SetPixel(x, yr, color);
}
}
else
{
// We're under the water level with the terrain, so paint water instead of land
// Y flip the cordinates
heightvalue = waterHeight - heightvalue;
if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue))
heightvalue = 0f;
else if (heightvalue > 19f)
heightvalue = 19f;
else if (heightvalue < 0f)
heightvalue = 0f;
heightvalue = 100f - (heightvalue * 100f) / 19f;
try
{
mapbmp.SetPixel(x, yr, WATER_COLOR);
}
catch (ArgumentException)
{
if (!terraincorruptedwarningsaid)
{
m_log.WarnFormat("[SHADED MAP TILE RENDERER]: Your terrain is corrupted in region {0}, it might take a few minutes to generate the map image depending on the corruption level", m_scene.RegionInfo.RegionName);
terraincorruptedwarningsaid = true;
}
Color black = Color.Black;
mapbmp.SetPixel(x, (hm.Width - y) - 1, black);
}
}
}
}
m_log.Debug("[SHADED MAP TILE RENDERER]: Generating Maptile Step 1: Done in " + (Environment.TickCount - tc) + " ms");
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="PrintDialog.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms {
using Microsoft.Win32;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.Runtime.InteropServices;
using System.Security;
/// <include file='doc\PrintDialog.uex' path='docs/doc[@for="PrintDialog"]/*' />
/// <devdoc>
/// <para> Allows users to select a printer and choose which
/// portions of the document to print.</para>
/// </devdoc>
[DefaultProperty("Document")]
[SRDescription(SR.DescriptionPrintDialog)]
[Designer("System.Windows.Forms.Design.PrintDialogDesigner, " + AssemblyRef.SystemDesign)]
// The only event this dialog has is HelpRequested, which isn't very useful
public sealed class PrintDialog : CommonDialog {
private const int printRangeMask = (int) (PrintRange.AllPages | PrintRange.SomePages
| PrintRange.Selection | PrintRange.CurrentPage);
// If PrintDocument != null, settings == printDocument.PrinterSettings
private PrinterSettings settings = null;
private PrintDocument printDocument = null;
// Implementing "current page" would require switching to PrintDlgEx, which is windows 2000 and later only
private bool allowCurrentPage;
private bool allowPages;
private bool allowPrintToFile;
private bool allowSelection;
private bool printToFile;
private bool showHelp;
private bool showNetwork;
private bool useEXDialog = false;
/// <include file='doc\PrintDialog.uex' path='docs/doc[@for="PrintDialog.PrintDialog"]/*' />
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Windows.Forms.PrintDialog'/> class.</para>
/// </devdoc>
public PrintDialog() {
Reset();
}
/// <summary>
/// <para>
/// Gets or sets a value indicating whether the Current Page option button is enabled.
/// </para>
/// </summary>
[
DefaultValue(false),
SRDescription(SR.PDallowCurrentPageDescr)
]
public bool AllowCurrentPage {
get { return allowCurrentPage;}
set { allowCurrentPage = value;}
}
/// <include file='doc\PrintDialog.uex' path='docs/doc[@for="PrintDialog.AllowSomePages"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets a value indicating whether the Pages option button is enabled.
/// </para>
/// </devdoc>
[
SRCategory(SR.CatBehavior),
DefaultValue(false),
SRDescription(SR.PDallowPagesDescr)
]
public bool AllowSomePages {
get { return allowPages;}
set { allowPages = value;}
}
/// <include file='doc\PrintDialog.uex' path='docs/doc[@for="PrintDialog.AllowPrintToFile"]/*' />
/// <devdoc>
/// <para>Gets or sets a value indicating whether the Print to file check box is enabled.</para>
/// </devdoc>
[
SRCategory(SR.CatBehavior),
DefaultValue(true),
SRDescription(SR.PDallowPrintToFileDescr)
]
public bool AllowPrintToFile {
get { return allowPrintToFile;}
set { allowPrintToFile = value;}
}
/// <include file='doc\PrintDialog.uex' path='docs/doc[@for="PrintDialog.AllowSelection"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets a value indicating whether the From... To... Page option button is enabled.
/// </para>
/// </devdoc>
[
SRCategory(SR.CatBehavior),
DefaultValue(false),
SRDescription(SR.PDallowSelectionDescr)
]
public bool AllowSelection {
get { return allowSelection;}
set { allowSelection = value;}
}
/// <include file='doc\PrintDialog.uex' path='docs/doc[@for="PrintDialog.Document"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets a value indicating the <see cref='System.Drawing.Printing.PrintDocument'/> used to obtain <see cref='System.Drawing.Printing.PrinterSettings'/>.
/// </para>
/// </devdoc>
[
SRCategory(SR.CatData),
DefaultValue(null),
SRDescription(SR.PDdocumentDescr)
]
public PrintDocument Document {
get { return printDocument;}
set {
printDocument = value;
if (printDocument == null)
settings = new PrinterSettings();
else
settings = printDocument.PrinterSettings;
}
}
private PageSettings PageSettings {
get {
if (Document == null)
return PrinterSettings.DefaultPageSettings;
else
return Document.DefaultPageSettings;
}
}
/// <include file='doc\PrintDialog.uex' path='docs/doc[@for="PrintDialog.PrinterSettings"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the <see cref='System.Drawing.Printing.PrinterSettings'/> the
/// dialog box will be modifying.
/// </para>
/// </devdoc>
[
SRCategory(SR.CatData),
DefaultValue(null),
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
SRDescription(SR.PDprinterSettingsDescr)
]
public PrinterSettings PrinterSettings {
get {
if (settings == null)
{
settings = new PrinterSettings();
}
return settings;
}
set {
if (value != PrinterSettings)
{
settings = value;
printDocument = null;
}
}
}
/// <include file='doc\PrintDialog.uex' path='docs/doc[@for="PrintDialog.PrintToFile"]/*' />
/// <devdoc>
/// <para>Gets or sets a value indicating whether the Print to file check box is checked.</para>
/// </devdoc>
[
SRCategory(SR.CatBehavior),
DefaultValue(false),
SRDescription(SR.PDprintToFileDescr)
]
public bool PrintToFile {
get { return printToFile;}
set { printToFile = value;}
}
/// <include file='doc\PrintDialog.uex' path='docs/doc[@for="PrintDialog.ShowHelp"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets a value indicating whether the Help button is displayed.
/// </para>
/// </devdoc>
[
SRCategory(SR.CatBehavior),
DefaultValue(false),
SRDescription(SR.PDshowHelpDescr)
]
public bool ShowHelp {
get { return showHelp;}
set { showHelp = value;}
}
/// <include file='doc\PrintDialog.uex' path='docs/doc[@for="PrintDialog.ShowNetwork"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets a value indicating whether the Network button is displayed.
/// </para>
/// </devdoc>
[
SRCategory(SR.CatBehavior),
DefaultValue(true),
SRDescription(SR.PDshowNetworkDescr)
]
public bool ShowNetwork {
get { return showNetwork;}
set { showNetwork = value;}
}
/// <summary>
/// <para>
/// UseEXDialog = true means to use the EX versions of the dialogs when running on XP or above, and to ignore the ShowHelp & ShowNetwork properties.
/// If running below XP then UseEXDialog is ignored and the non-EX dialogs are used & ShowHelp & ShowNetwork are respected.
/// UseEXDialog = false means to never use the EX versions of the dialog regardless of which O/S app is running on. ShowHelp & ShowNetwork will work in this case.
/// </para>
/// </summary>
[
DefaultValue(false),
SRDescription(SR.PDuseEXDialog)
]
public bool UseEXDialog {
get { return useEXDialog;}
set { useEXDialog = value;}
}
private int GetFlags() {
int flags = 0;
// VSWhidbey 93449: Only set this flag when using PRINTDLG and PrintDlg,
// and not when using PrintDlgEx and PRINTDLGEX.
if (!UseEXDialog || (Environment.OSVersion.Platform != System.PlatformID.Win32NT ||
Environment.OSVersion.Version.Major < 5)) {
flags |= NativeMethods.PD_ENABLEPRINTHOOK;
}
if (!allowCurrentPage) flags |= NativeMethods.PD_NOCURRENTPAGE;
if (!allowPages) flags |= NativeMethods.PD_NOPAGENUMS;
if (!allowPrintToFile) flags |= NativeMethods.PD_DISABLEPRINTTOFILE;
if (!allowSelection) flags |= NativeMethods.PD_NOSELECTION;
flags |= (int) PrinterSettings.PrintRange;
if (printToFile) flags |= NativeMethods.PD_PRINTTOFILE;
if (showHelp) flags |= NativeMethods.PD_SHOWHELP;
if (!showNetwork) flags |= NativeMethods.PD_NONETWORKBUTTON;
if (PrinterSettings.Collate) flags |= NativeMethods.PD_COLLATE;
return flags;
}
/// <include file='doc\PrintDialog.uex' path='docs/doc[@for="PrintDialog.Reset"]/*' />
/// <devdoc>
/// <para>
/// Resets all options, the last selected printer, and the page
/// settings to their default values.
/// </para>
/// </devdoc>
public override void Reset() {
allowCurrentPage = false;
allowPages = false;
allowPrintToFile = true;
allowSelection = false;
printDocument = null;
printToFile = false;
settings = null;
showHelp = false;
showNetwork = true;
}
// Create a PRINTDLG with a few useful defaults.
internal static NativeMethods.PRINTDLG CreatePRINTDLG() {
NativeMethods.PRINTDLG data = null;
if (IntPtr.Size == 4) {
data = new NativeMethods.PRINTDLG_32();
}
else {
data = new NativeMethods.PRINTDLG_64();
}
data.lStructSize = Marshal.SizeOf(data);
data.hwndOwner = IntPtr.Zero;
data.hDevMode = IntPtr.Zero;
data.hDevNames = IntPtr.Zero;
data.Flags = 0;
data.hDC = IntPtr.Zero;
data.nFromPage = 1;
data.nToPage = 1;
data.nMinPage = 0;
data.nMaxPage = 9999;
data.nCopies = 1;
data.hInstance = IntPtr.Zero;
data.lCustData = IntPtr.Zero;
data.lpfnPrintHook = null;
data.lpfnSetupHook = null;
data.lpPrintTemplateName = null;
data.lpSetupTemplateName = null;
data.hPrintTemplate = IntPtr.Zero;
data.hSetupTemplate = IntPtr.Zero;
return data;
}
// VSWhidbey 93449: Use PRINTDLGEX on Win2k and newer OS'. Note that at the time of this
// fix, PrinterSettings did not support multiple page ranges. (See VSWhidbey 193829.)
// Create a PRINTDLGEX with a few useful defaults.
internal static NativeMethods.PRINTDLGEX CreatePRINTDLGEX() {
NativeMethods.PRINTDLGEX data = new NativeMethods.PRINTDLGEX();
data.lStructSize = Marshal.SizeOf(data);
data.hwndOwner = IntPtr.Zero;
data.hDevMode = IntPtr.Zero;
data.hDevNames = IntPtr.Zero;
data.hDC = IntPtr.Zero;
data.Flags = 0;
data.Flags2 = 0;
data.ExclusionFlags = 0;
data.nPageRanges = 0;
data.nMaxPageRanges = 1;
data.pageRanges = UnsafeNativeMethods.GlobalAlloc(NativeMethods.GPTR,
data.nMaxPageRanges * Marshal.SizeOf(typeof(NativeMethods.PRINTPAGERANGE)));
data.nMinPage = 0;
data.nMaxPage = 9999;
data.nCopies = 1;
data.hInstance = IntPtr.Zero;
data.lpPrintTemplateName = null;
data.nPropertyPages = 0;
data.lphPropertyPages = IntPtr.Zero;
data.nStartPage = NativeMethods.START_PAGE_GENERAL;
data.dwResultAction = 0;
return data;
}
/// <include file='doc\PrintDialog.uex' path='docs/doc[@for="PrintDialog.RunDialog"]/*' />
/// <devdoc>
/// </devdoc>
/// <internalonly/>
// VSWhidbey 93449: Use PrintDlgEx and PRINTDLGEX on Win2k and newer OS'.
protected override bool RunDialog(IntPtr hwndOwner) {
bool returnValue = false;
IntSecurity.SafePrinting.Demand();
NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(this.HookProc);
if (!UseEXDialog || (Environment.OSVersion.Platform != System.PlatformID.Win32NT ||
Environment.OSVersion.Version.Major < 5)) {
NativeMethods.PRINTDLG data = CreatePRINTDLG();
returnValue = ShowPrintDialog(hwndOwner, hookProcPtr, data);
}
else {
NativeMethods.PRINTDLGEX data = CreatePRINTDLGEX();
returnValue = ShowPrintDialog(hwndOwner, data);
}
return returnValue;
}
// VSWhidbey 93449: Due to the nature of PRINTDLGEX vs PRINTDLG, separate but similar methods
// are required for showing the print dialog on Win2k and newer OS'.
private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.WndProc hookProcPtr, NativeMethods.PRINTDLG data) {
data.Flags = GetFlags();
data.nCopies = (short) PrinterSettings.Copies;
data.hwndOwner = hwndOwner;
data.lpfnPrintHook = hookProcPtr;
IntSecurity.AllPrintingAndUnmanagedCode.Assert();
try {
if (PageSettings == null)
data.hDevMode = PrinterSettings.GetHdevmode();
else
data.hDevMode = PrinterSettings.GetHdevmode(PageSettings);
data.hDevNames = PrinterSettings.GetHdevnames();
}
catch (InvalidPrinterException) {
data.hDevMode = IntPtr.Zero;
data.hDevNames = IntPtr.Zero;
// Leave those fields null; Windows will fill them in
}
finally {
CodeAccessPermission.RevertAssert();
}
try {
// Windows doesn't like it if page numbers are invalid
if (AllowSomePages) {
if (PrinterSettings.FromPage < PrinterSettings.MinimumPage
|| PrinterSettings.FromPage > PrinterSettings.MaximumPage)
throw new ArgumentException(SR.GetString(SR.PDpageOutOfRange, "FromPage"));
if (PrinterSettings.ToPage < PrinterSettings.MinimumPage
|| PrinterSettings.ToPage > PrinterSettings.MaximumPage)
throw new ArgumentException(SR.GetString(SR.PDpageOutOfRange, "ToPage"));
if (PrinterSettings.ToPage < PrinterSettings.FromPage)
throw new ArgumentException(SR.GetString(SR.PDpageOutOfRange, "FromPage"));
data.nFromPage = (short) PrinterSettings.FromPage;
data.nToPage = (short) PrinterSettings.ToPage;
data.nMinPage = (short) PrinterSettings.MinimumPage;
data.nMaxPage = (short) PrinterSettings.MaximumPage;
}
if (!UnsafeNativeMethods.PrintDlg(data))
return false;
IntSecurity.AllPrintingAndUnmanagedCode.Assert();
try {
UpdatePrinterSettings(data.hDevMode, data.hDevNames, data.nCopies, data.Flags, settings, PageSettings);
}
finally {
CodeAccessPermission.RevertAssert();
}
PrintToFile = ((data.Flags & NativeMethods.PD_PRINTTOFILE) != 0);
PrinterSettings.PrintToFile = PrintToFile;
if (AllowSomePages) {
PrinterSettings.FromPage = data.nFromPage;
PrinterSettings.ToPage = data.nToPage;
}
// Fix Dev10 #575399, when the flag PD_USEDEVMODECOPIESANDCOLLATE is not set,
// PRINTDLG.nCopies or PRINTDLG.nCopies indicates the number of copies the user wants
// to print, and the PD_COLLATE flag in the Flags member indicates
// whether the user wants to print them collated.
// Due to a Windows OS Bug 558734, we don't need to consider Windows XP and before
if ((data.Flags & NativeMethods.PD_USEDEVMODECOPIESANDCOLLATE) == 0) {
if (Environment.OSVersion.Version.Major >= 6) {
PrinterSettings.Copies = data.nCopies;
PrinterSettings.Collate = ((data.Flags & NativeMethods.PD_COLLATE) == NativeMethods.PD_COLLATE);
}
}
return true;
}
finally {
UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevMode));
UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevNames));
}
}
// VSWhidbey 93449: Due to the nature of PRINTDLGEX vs PRINTDLG, separate but similar methods
// are required for showing the print dialog on Win2k and newer OS'.
private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.PRINTDLGEX data) {
data.Flags = GetFlags();
data.nCopies = PrinterSettings.Copies;
data.hwndOwner = hwndOwner;
IntSecurity.AllPrintingAndUnmanagedCode.Assert();
try {
if (PageSettings == null)
data.hDevMode = PrinterSettings.GetHdevmode();
else
data.hDevMode = PrinterSettings.GetHdevmode(PageSettings);
data.hDevNames = PrinterSettings.GetHdevnames();
}
catch (InvalidPrinterException) {
data.hDevMode = IntPtr.Zero;
data.hDevNames = IntPtr.Zero;
// Leave those fields null; Windows will fill them in
}
finally {
CodeAccessPermission.RevertAssert();
}
try {
// Windows doesn't like it if page numbers are invalid
if (AllowSomePages) {
if (PrinterSettings.FromPage < PrinterSettings.MinimumPage
|| PrinterSettings.FromPage > PrinterSettings.MaximumPage)
throw new ArgumentException(SR.GetString(SR.PDpageOutOfRange, "FromPage"));
if (PrinterSettings.ToPage < PrinterSettings.MinimumPage
|| PrinterSettings.ToPage > PrinterSettings.MaximumPage)
throw new ArgumentException(SR.GetString(SR.PDpageOutOfRange, "ToPage"));
if (PrinterSettings.ToPage < PrinterSettings.FromPage)
throw new ArgumentException(SR.GetString(SR.PDpageOutOfRange, "FromPage"));
unsafe {
int* pageRangeField = (int*)data.pageRanges;
*pageRangeField = PrinterSettings.FromPage;
pageRangeField += 1;
*pageRangeField = PrinterSettings.ToPage;
}
data.nPageRanges = 1;
data.nMinPage = PrinterSettings.MinimumPage;
data.nMaxPage = PrinterSettings.MaximumPage;
}
//
// The flags NativeMethods.PD_SHOWHELP and NativeMethods.PD_NONETWORKBUTTON don't work with
// PrintDlgEx. So we have to strip them out.
data.Flags &= ~(NativeMethods.PD_SHOWHELP | NativeMethods.PD_NONETWORKBUTTON);
int hr = UnsafeNativeMethods.PrintDlgEx(data);
if (NativeMethods.Failed(hr) || data.dwResultAction == NativeMethods.PD_RESULT_CANCEL) {
return false;
}
IntSecurity.AllPrintingAndUnmanagedCode.Assert();
try {
UpdatePrinterSettings(data.hDevMode, data.hDevNames, (short)data.nCopies, data.Flags, PrinterSettings, PageSettings);
}
finally {
CodeAccessPermission.RevertAssert();
}
PrintToFile = ((data.Flags & NativeMethods.PD_PRINTTOFILE) != 0);
PrinterSettings.PrintToFile = PrintToFile;
if (AllowSomePages) {
unsafe {
int* pageRangeField = (int*)data.pageRanges;
PrinterSettings.FromPage = *pageRangeField;
pageRangeField += 1;
PrinterSettings.ToPage = *pageRangeField;
}
}
// Fix Dev10 #575399, when the flag PD_USEDEVMODECOPIESANDCOLLATE is not set,
// PRINTDLG.nCopies or PRINTDLG.nCopies indicates the number of copies the user wants
// to print, and the PD_COLLATE flag in the Flags member indicates
// whether the user wants to print them collated.
// Due to a Windows OS Bug 558734, we don't need to consider Windows XP and before
if ((data.Flags & NativeMethods.PD_USEDEVMODECOPIESANDCOLLATE) == 0) {
if(Environment.OSVersion.Version.Major >= 6) {
PrinterSettings.Copies = (short)(data.nCopies);
PrinterSettings.Collate = ((data.Flags & NativeMethods.PD_COLLATE) == NativeMethods.PD_COLLATE);
}
}
// We should return true only if the user pressed the "Print" button while dismissing the dialog.
// Please refer to VsW: 403124 for more details.
return (data.dwResultAction == NativeMethods.PD_RESULT_PRINT);
}
finally {
if (data.hDevMode != IntPtr.Zero)
UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevMode));
if (data.hDevNames != IntPtr.Zero)
UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevNames));
if (data.pageRanges != IntPtr.Zero)
UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.pageRanges));
}
}
// VSWhidbey 93449: Due to the nature of PRINTDLGEX vs PRINTDLG, separate but similar methods
// are required for updating the settings from the structure utilized by the dialog.
// Take information from print dialog and put in PrinterSettings
private static void UpdatePrinterSettings(IntPtr hDevMode, IntPtr hDevNames, short copies, int flags, PrinterSettings settings, PageSettings pageSettings) {
// Mode
settings.SetHdevmode(hDevMode);
settings.SetHdevnames(hDevNames);
if (pageSettings!= null)
pageSettings.SetHdevmode(hDevMode);
//Check for Copies == 1 since we might get the Right number of Copies from hdevMode.dmCopies...
//this is Native PrintDialogs
if (settings.Copies == 1)
settings.Copies = copies;
settings.PrintRange = (PrintRange) (flags & printRangeMask);
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Diagnostics;
using QuantConnect.Data;
namespace QuantConnect.Indicators
{
/// <summary>
/// Event handler type for the IndicatorBase.Updated event
/// </summary>
/// <param name="sender">The indicator that fired the event</param>
/// <param name="updated">The new piece of data produced by the indicator</param>
public delegate void IndicatorUpdatedHandler(object sender, IndicatorDataPoint updated);
/// <summary>
/// Provides a base type for all indicators
/// </summary>
/// <typeparam name="T">The type of data input into this indicator</typeparam>
[DebuggerDisplay("{ToDetailedString()}")]
public abstract partial class IndicatorBase<T> : IComparable<IndicatorBase<T>>, IComparable
where T : BaseData
{
/// <summary>the most recent input that was given to this indicator</summary>
private T _previousInput;
/// <summary>
/// Event handler that fires after this indicator is updated
/// </summary>
public event IndicatorUpdatedHandler Updated;
/// <summary>
/// Initializes a new instance of the Indicator class using the specified name.
/// </summary>
/// <param name="name">The name of this indicator</param>
protected IndicatorBase(string name)
{
Name = name;
Current = new IndicatorDataPoint(DateTime.MinValue, 0m);
}
/// <summary>
/// Gets a name for this indicator
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Gets a flag indicating when this indicator is ready and fully initialized
/// </summary>
public abstract bool IsReady { get; }
/// <summary>
/// Gets the current state of this indicator. If the state has not been updated
/// then the time on the value will equal DateTime.MinValue.
/// </summary>
public IndicatorDataPoint Current { get; protected set; }
/// <summary>
/// Gets the number of samples processed by this indicator
/// </summary>
public long Samples { get; private set; }
/// <summary>
/// Updates the state of this indicator with the given value and returns true
/// if this indicator is ready, false otherwise
/// </summary>
/// <param name="input">The value to use to update this indicator</param>
/// <returns>True if this indicator is ready, false otherwise</returns>
public bool Update(T input)
{
if (_previousInput != null && input.Time < _previousInput.Time)
{
// if we receive a time in the past, throw
throw new ArgumentException(string.Format("This is a forward only indicator: {0} Input: {1} Previous: {2}", Name, input.Time.ToString("u"), _previousInput.Time.ToString("u")));
}
if (!ReferenceEquals(input, _previousInput))
{
// compute a new value and update our previous time
Samples++;
_previousInput = input;
var nextResult = ValidateAndComputeNextValue(input);
if (nextResult.Status == IndicatorStatus.Success)
{
Current = new IndicatorDataPoint(input.Time, nextResult.Value);
// let others know we've produced a new data point
OnUpdated(Current);
}
}
return IsReady;
}
/// <summary>
/// Resets this indicator to its initial state
/// </summary>
public virtual void Reset()
{
Samples = 0;
_previousInput = null;
Current = new IndicatorDataPoint(DateTime.MinValue, default(decimal));
}
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <returns>
/// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public int CompareTo(IndicatorBase<T> other)
{
if (ReferenceEquals(other, null))
{
// everything is greater than null via MSDN
return 1;
}
return Current.CompareTo(other.Current);
}
/// <summary>
/// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.
/// </summary>
/// <returns>
/// A value that indicates the relative order of the objects being compared. The return value has these meanings: Value Meaning Less than zero This instance precedes <paramref name="obj"/> in the sort order. Zero This instance occurs in the same position in the sort order as <paramref name="obj"/>. Greater than zero This instance follows <paramref name="obj"/> in the sort order.
/// </returns>
/// <param name="obj">An object to compare with this instance. </param><exception cref="T:System.ArgumentException"><paramref name="obj"/> is not the same type as this instance. </exception><filterpriority>2</filterpriority>
public int CompareTo(object obj)
{
var other = obj as IndicatorBase<T>;
if (other == null)
{
throw new ArgumentException("Object must be of type " + GetType().GetBetterTypeName());
}
return CompareTo(other);
}
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// </summary>
/// <returns>
/// true if the specified object is equal to the current object; otherwise, false.
/// </returns>
/// <param name="obj">The object to compare with the current object. </param>
public override bool Equals(object obj)
{
// this implementation acts as a liason to prevent inconsistency between the operators
// == and != against primitive types. the core impl for equals between two indicators
// is still reference equality, however, when comparing value types (floats/int, ect..)
// we'll use value type semantics on Current.Value
// because of this, we shouldn't need to override GetHashCode as well since we're still
// solely relying on reference semantics (think hashset/dictionary impls)
if (ReferenceEquals(obj, null)) return false;
if (obj.GetType().IsSubclassOf(typeof (IndicatorBase<>))) return ReferenceEquals(this, obj);
// the obj is not an indicator, so let's check for value types, try converting to decimal
var converted = Convert.ToDecimal(obj);
return Current.Value == converted;
}
/// <summary>
/// ToString Overload for Indicator Base
/// </summary>
/// <returns>String representation of the indicator</returns>
public override string ToString()
{
return Current.Value.ToString("#######0.0####");
}
/// <summary>
/// Provides a more detailed string of this indicator in the form of {Name} - {Value}
/// </summary>
/// <returns>A detailed string of this indicator's current state</returns>
public string ToDetailedString()
{
return string.Format("{0} - {1}", Name, this);
}
/// <summary>
/// Computes the next value of this indicator from the given state
/// </summary>
/// <param name="input">The input given to the indicator</param>
/// <returns>A new value for this indicator</returns>
protected abstract decimal ComputeNextValue(T input);
/// <summary>
/// Computes the next value of this indicator from the given state
/// and returns an instance of the <see cref="IndicatorResult"/> class
/// </summary>
/// <param name="input">The input given to the indicator</param>
/// <returns>An IndicatorResult object including the status of the indicator</returns>
protected virtual IndicatorResult ValidateAndComputeNextValue(T input)
{
// default implementation always returns IndicatorStatus.Success
return new IndicatorResult(ComputeNextValue(input));
}
/// <summary>
/// Event invocator for the Updated event
/// </summary>
/// <param name="consolidated">This is the new piece of data produced by this indicator</param>
protected virtual void OnUpdated(IndicatorDataPoint consolidated)
{
var handler = Updated;
if (handler != null) handler(this, consolidated);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Controls;
using Avalonia.Controls.Metadata;
using Avalonia.Data;
using Avalonia.Input.GestureRecognizers;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.VisualTree;
#nullable enable
namespace Avalonia.Input
{
/// <summary>
/// Implements input-related functionality for a control.
/// </summary>
[PseudoClasses(":disabled", ":focus", ":focus-visible", ":focus-within", ":pointerover")]
public class InputElement : Interactive, IInputElement
{
/// <summary>
/// Defines the <see cref="Focusable"/> property.
/// </summary>
public static readonly StyledProperty<bool> FocusableProperty =
AvaloniaProperty.Register<InputElement, bool>(nameof(Focusable));
/// <summary>
/// Defines the <see cref="IsEnabled"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsEnabledProperty =
AvaloniaProperty.Register<InputElement, bool>(nameof(IsEnabled), true);
/// <summary>
/// Defines the <see cref="IsEffectivelyEnabled"/> property.
/// </summary>
public static readonly DirectProperty<InputElement, bool> IsEffectivelyEnabledProperty =
AvaloniaProperty.RegisterDirect<InputElement, bool>(
nameof(IsEffectivelyEnabled),
o => o.IsEffectivelyEnabled);
/// <summary>
/// Gets or sets associated mouse cursor.
/// </summary>
public static readonly StyledProperty<Cursor?> CursorProperty =
AvaloniaProperty.Register<InputElement, Cursor?>(nameof(Cursor), null, true);
/// <summary>
/// Defines the <see cref="IsKeyboardFocusWithin"/> property.
/// </summary>
public static readonly DirectProperty<InputElement, bool> IsKeyboardFocusWithinProperty =
AvaloniaProperty.RegisterDirect<InputElement, bool>(
nameof(IsKeyboardFocusWithin),
o => o.IsKeyboardFocusWithin);
/// <summary>
/// Defines the <see cref="IsFocused"/> property.
/// </summary>
public static readonly DirectProperty<InputElement, bool> IsFocusedProperty =
AvaloniaProperty.RegisterDirect<InputElement, bool>(nameof(IsFocused), o => o.IsFocused);
/// <summary>
/// Defines the <see cref="IsHitTestVisible"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsHitTestVisibleProperty =
AvaloniaProperty.Register<InputElement, bool>(nameof(IsHitTestVisible), true);
/// <summary>
/// Defines the <see cref="IsPointerOver"/> property.
/// </summary>
public static readonly DirectProperty<InputElement, bool> IsPointerOverProperty =
AvaloniaProperty.RegisterDirect<InputElement, bool>(nameof(IsPointerOver), o => o.IsPointerOver);
/// <summary>
/// Defines the <see cref="IsTabStop"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsTabStopProperty =
KeyboardNavigation.IsTabStopProperty.AddOwner<InputElement>();
/// <summary>
/// Defines the <see cref="GotFocus"/> event.
/// </summary>
public static readonly RoutedEvent<GotFocusEventArgs> GotFocusEvent =
RoutedEvent.Register<InputElement, GotFocusEventArgs>(nameof(GotFocus), RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="LostFocus"/> event.
/// </summary>
public static readonly RoutedEvent<RoutedEventArgs> LostFocusEvent =
RoutedEvent.Register<InputElement, RoutedEventArgs>(nameof(LostFocus), RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="KeyDown"/> event.
/// </summary>
public static readonly RoutedEvent<KeyEventArgs> KeyDownEvent =
RoutedEvent.Register<InputElement, KeyEventArgs>(
"KeyDown",
RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="KeyUp"/> event.
/// </summary>
public static readonly RoutedEvent<KeyEventArgs> KeyUpEvent =
RoutedEvent.Register<InputElement, KeyEventArgs>(
"KeyUp",
RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="TabIndex"/> property.
/// </summary>
public static readonly StyledProperty<int> TabIndexProperty =
KeyboardNavigation.TabIndexProperty.AddOwner<InputElement>();
/// <summary>
/// Defines the <see cref="TextInput"/> event.
/// </summary>
public static readonly RoutedEvent<TextInputEventArgs> TextInputEvent =
RoutedEvent.Register<InputElement, TextInputEventArgs>(
"TextInput",
RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="TextInputMethodClientRequested"/> event.
/// </summary>
public static readonly RoutedEvent<TextInputMethodClientRequestedEventArgs> TextInputMethodClientRequestedEvent =
RoutedEvent.Register<InputElement, TextInputMethodClientRequestedEventArgs>(
"TextInputMethodClientRequested",
RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="TextInputOptionsQuery"/> event.
/// </summary>
public static readonly RoutedEvent<TextInputOptionsQueryEventArgs> TextInputOptionsQueryEvent =
RoutedEvent.Register<InputElement, TextInputOptionsQueryEventArgs>(
"TextInputOptionsQuery",
RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="PointerEnter"/> event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerEnterEvent =
RoutedEvent.Register<InputElement, PointerEventArgs>(nameof(PointerEnter), RoutingStrategies.Direct);
/// <summary>
/// Defines the <see cref="PointerLeave"/> event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerLeaveEvent =
RoutedEvent.Register<InputElement, PointerEventArgs>(nameof(PointerLeave), RoutingStrategies.Direct);
/// <summary>
/// Defines the <see cref="PointerMoved"/> event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerMovedEvent =
RoutedEvent.Register<InputElement, PointerEventArgs>(
"PointerMove",
RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="PointerPressed"/> event.
/// </summary>
public static readonly RoutedEvent<PointerPressedEventArgs> PointerPressedEvent =
RoutedEvent.Register<InputElement, PointerPressedEventArgs>(
"PointerPressed",
RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="PointerReleased"/> event.
/// </summary>
public static readonly RoutedEvent<PointerReleasedEventArgs> PointerReleasedEvent =
RoutedEvent.Register<InputElement, PointerReleasedEventArgs>(
"PointerReleased",
RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="PointerCaptureLost"/> routed event.
/// </summary>
public static readonly RoutedEvent<PointerCaptureLostEventArgs> PointerCaptureLostEvent =
RoutedEvent.Register<InputElement, PointerCaptureLostEventArgs>(
"PointerCaptureLost",
RoutingStrategies.Direct);
/// <summary>
/// Defines the <see cref="PointerWheelChanged"/> event.
/// </summary>
public static readonly RoutedEvent<PointerWheelEventArgs> PointerWheelChangedEvent =
RoutedEvent.Register<InputElement, PointerWheelEventArgs>(
"PointerWheelChanged",
RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="Tapped"/> event.
/// </summary>
public static readonly RoutedEvent<TappedEventArgs> TappedEvent = Gestures.TappedEvent;
/// <summary>
/// Defines the <see cref="DoubleTapped"/> event.
/// </summary>
public static readonly RoutedEvent<TappedEventArgs> DoubleTappedEvent = Gestures.DoubleTappedEvent;
private bool _isEffectivelyEnabled = true;
private bool _isFocused;
private bool _isKeyboardFocusWithin;
private bool _isFocusVisible;
private bool _isPointerOver;
private GestureRecognizerCollection? _gestureRecognizers;
/// <summary>
/// Initializes static members of the <see cref="InputElement"/> class.
/// </summary>
static InputElement()
{
IsEnabledProperty.Changed.Subscribe(IsEnabledChanged);
GotFocusEvent.AddClassHandler<InputElement>((x, e) => x.OnGotFocus(e));
LostFocusEvent.AddClassHandler<InputElement>((x, e) => x.OnLostFocus(e));
KeyDownEvent.AddClassHandler<InputElement>((x, e) => x.OnKeyDown(e));
KeyUpEvent.AddClassHandler<InputElement>((x, e) => x.OnKeyUp(e));
TextInputEvent.AddClassHandler<InputElement>((x, e) => x.OnTextInput(e));
PointerEnterEvent.AddClassHandler<InputElement>((x, e) => x.OnPointerEnterCore(e));
PointerLeaveEvent.AddClassHandler<InputElement>((x, e) => x.OnPointerLeaveCore(e));
PointerMovedEvent.AddClassHandler<InputElement>((x, e) => x.OnPointerMoved(e));
PointerPressedEvent.AddClassHandler<InputElement>((x, e) => x.OnPointerPressed(e));
PointerReleasedEvent.AddClassHandler<InputElement>((x, e) => x.OnPointerReleased(e));
PointerCaptureLostEvent.AddClassHandler<InputElement>((x, e) => x.OnPointerCaptureLost(e));
PointerWheelChangedEvent.AddClassHandler<InputElement>((x, e) => x.OnPointerWheelChanged(e));
}
public InputElement()
{
UpdatePseudoClasses(IsFocused, IsPointerOver);
}
/// <summary>
/// Occurs when the control receives focus.
/// </summary>
public event EventHandler<GotFocusEventArgs>? GotFocus
{
add { AddHandler(GotFocusEvent, value); }
remove { RemoveHandler(GotFocusEvent, value); }
}
/// <summary>
/// Occurs when the control loses focus.
/// </summary>
public event EventHandler<RoutedEventArgs>? LostFocus
{
add { AddHandler(LostFocusEvent, value); }
remove { RemoveHandler(LostFocusEvent, value); }
}
/// <summary>
/// Occurs when a key is pressed while the control has focus.
/// </summary>
public event EventHandler<KeyEventArgs>? KeyDown
{
add { AddHandler(KeyDownEvent, value); }
remove { RemoveHandler(KeyDownEvent, value); }
}
/// <summary>
/// Occurs when a key is released while the control has focus.
/// </summary>
public event EventHandler<KeyEventArgs>? KeyUp
{
add { AddHandler(KeyUpEvent, value); }
remove { RemoveHandler(KeyUpEvent, value); }
}
/// <summary>
/// Occurs when a user typed some text while the control has focus.
/// </summary>
public event EventHandler<TextInputEventArgs>? TextInput
{
add { AddHandler(TextInputEvent, value); }
remove { RemoveHandler(TextInputEvent, value); }
}
/// <summary>
/// Occurs when an input element gains input focus and input method is looking for the corresponding client
/// </summary>
public event EventHandler<TextInputMethodClientRequestedEventArgs>? TextInputMethodClientRequested
{
add { AddHandler(TextInputMethodClientRequestedEvent, value); }
remove { RemoveHandler(TextInputMethodClientRequestedEvent, value); }
}
/// <summary>
/// Occurs when an input element gains input focus and input method is asking for required content options
/// </summary>
public event EventHandler<TextInputOptionsQueryEventArgs>? TextInputOptionsQuery
{
add { AddHandler(TextInputOptionsQueryEvent, value); }
remove { RemoveHandler(TextInputOptionsQueryEvent, value); }
}
/// <summary>
/// Occurs when the pointer enters the control.
/// </summary>
public event EventHandler<PointerEventArgs>? PointerEnter
{
add { AddHandler(PointerEnterEvent, value); }
remove { RemoveHandler(PointerEnterEvent, value); }
}
/// <summary>
/// Occurs when the pointer leaves the control.
/// </summary>
public event EventHandler<PointerEventArgs>? PointerLeave
{
add { AddHandler(PointerLeaveEvent, value); }
remove { RemoveHandler(PointerLeaveEvent, value); }
}
/// <summary>
/// Occurs when the pointer moves over the control.
/// </summary>
public event EventHandler<PointerEventArgs>? PointerMoved
{
add { AddHandler(PointerMovedEvent, value); }
remove { RemoveHandler(PointerMovedEvent, value); }
}
/// <summary>
/// Occurs when the pointer is pressed over the control.
/// </summary>
public event EventHandler<PointerPressedEventArgs>? PointerPressed
{
add { AddHandler(PointerPressedEvent, value); }
remove { RemoveHandler(PointerPressedEvent, value); }
}
/// <summary>
/// Occurs when the pointer is released over the control.
/// </summary>
public event EventHandler<PointerReleasedEventArgs>? PointerReleased
{
add { AddHandler(PointerReleasedEvent, value); }
remove { RemoveHandler(PointerReleasedEvent, value); }
}
/// <summary>
/// Occurs when the control or its child control loses the pointer capture for any reason,
/// event will not be triggered for a parent control if capture was transferred to another child of that parent control
/// </summary>
public event EventHandler<PointerCaptureLostEventArgs>? PointerCaptureLost
{
add => AddHandler(PointerCaptureLostEvent, value);
remove => RemoveHandler(PointerCaptureLostEvent, value);
}
/// <summary>
/// Occurs when the mouse is scrolled over the control.
/// </summary>
public event EventHandler<PointerWheelEventArgs>? PointerWheelChanged
{
add { AddHandler(PointerWheelChangedEvent, value); }
remove { RemoveHandler(PointerWheelChangedEvent, value); }
}
/// <summary>
/// Occurs when a tap gesture occurs on the control.
/// </summary>
public event EventHandler<TappedEventArgs>? Tapped
{
add { AddHandler(TappedEvent, value); }
remove { RemoveHandler(TappedEvent, value); }
}
/// <summary>
/// Occurs when a double-tap gesture occurs on the control.
/// </summary>
public event EventHandler<TappedEventArgs>? DoubleTapped
{
add { AddHandler(DoubleTappedEvent, value); }
remove { RemoveHandler(DoubleTappedEvent, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the control can receive focus.
/// </summary>
public bool Focusable
{
get { return GetValue(FocusableProperty); }
set { SetValue(FocusableProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the control is enabled for user interaction.
/// </summary>
public bool IsEnabled
{
get { return GetValue(IsEnabledProperty); }
set { SetValue(IsEnabledProperty, value); }
}
/// <summary>
/// Gets or sets associated mouse cursor.
/// </summary>
public Cursor? Cursor
{
get { return GetValue(CursorProperty); }
set { SetValue(CursorProperty, value); }
}
/// <summary>
/// Gets a value indicating whether keyboard focus is anywhere within the element or its visual tree child elements.
/// </summary>
public bool IsKeyboardFocusWithin
{
get => _isKeyboardFocusWithin;
internal set => SetAndRaise(IsKeyboardFocusWithinProperty, ref _isKeyboardFocusWithin, value);
}
/// <summary>
/// Gets a value indicating whether the control is focused.
/// </summary>
public bool IsFocused
{
get { return _isFocused; }
private set { SetAndRaise(IsFocusedProperty, ref _isFocused, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the control is considered for hit testing.
/// </summary>
public bool IsHitTestVisible
{
get { return GetValue(IsHitTestVisibleProperty); }
set { SetValue(IsHitTestVisibleProperty, value); }
}
/// <summary>
/// Gets a value indicating whether the pointer is currently over the control.
/// </summary>
public bool IsPointerOver
{
get { return _isPointerOver; }
internal set { SetAndRaise(IsPointerOverProperty, ref _isPointerOver, value); }
}
/// <summary>
/// Gets or sets a value that indicates whether the control is included in tab navigation.
/// </summary>
public bool IsTabStop
{
get => GetValue(IsTabStopProperty);
set => SetValue(IsTabStopProperty, value);
}
/// <inheritdoc/>
public bool IsEffectivelyEnabled
{
get => _isEffectivelyEnabled;
private set
{
SetAndRaise(IsEffectivelyEnabledProperty, ref _isEffectivelyEnabled, value);
PseudoClasses.Set(":disabled", !value);
}
}
/// <summary>
/// Gets or sets a value that determines the order in which elements receive focus when the
/// user navigates through controls by pressing the Tab key.
/// </summary>
public int TabIndex
{
get => GetValue(TabIndexProperty);
set => SetValue(TabIndexProperty, value);
}
public List<KeyBinding> KeyBindings { get; } = new List<KeyBinding>();
/// <summary>
/// Allows a derived class to override the enabled state of the control.
/// </summary>
/// <remarks>
/// Derived controls may wish to disable the enabled state of the control without overwriting the
/// user-supplied <see cref="IsEnabled"/> setting. This can be done by overriding this property
/// to return the overridden enabled state. If the value returned from <see cref="IsEnabledCore"/>
/// should change, then the derived control should call <see cref="UpdateIsEffectivelyEnabled()"/>.
/// </remarks>
protected virtual bool IsEnabledCore => IsEnabled;
public GestureRecognizerCollection GestureRecognizers
=> _gestureRecognizers ?? (_gestureRecognizers = new GestureRecognizerCollection(this));
/// <summary>
/// Focuses the control.
/// </summary>
public void Focus()
{
FocusManager.Instance?.Focus(this);
}
/// <inheritdoc/>
protected override void OnDetachedFromVisualTreeCore(VisualTreeAttachmentEventArgs e)
{
base.OnDetachedFromVisualTreeCore(e);
if (IsFocused)
{
FocusManager.Instance?.Focus(null);
}
}
/// <inheritdoc/>
protected override void OnAttachedToVisualTreeCore(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTreeCore(e);
UpdateIsEffectivelyEnabled();
}
/// <summary>
/// Called before the <see cref="GotFocus"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnGotFocus(GotFocusEventArgs e)
{
var isFocused = e.Source == this;
_isFocusVisible = isFocused && (e.NavigationMethod == NavigationMethod.Directional || e.NavigationMethod == NavigationMethod.Tab);
IsFocused = isFocused;
}
/// <summary>
/// Called before the <see cref="LostFocus"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnLostFocus(RoutedEventArgs e)
{
_isFocusVisible = false;
IsFocused = false;
}
/// <summary>
/// Called before the <see cref="KeyDown"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnKeyDown(KeyEventArgs e)
{
}
/// <summary>
/// Called before the <see cref="KeyUp"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnKeyUp(KeyEventArgs e)
{
}
/// <summary>
/// Called before the <see cref="TextInput"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnTextInput(TextInputEventArgs e)
{
}
/// <summary>
/// Called before the <see cref="PointerEnter"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnPointerEnter(PointerEventArgs e)
{
}
/// <summary>
/// Called before the <see cref="PointerLeave"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnPointerLeave(PointerEventArgs e)
{
}
/// <summary>
/// Called before the <see cref="PointerMoved"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnPointerMoved(PointerEventArgs e)
{
if (_gestureRecognizers?.HandlePointerMoved(e) == true)
e.Handled = true;
}
/// <summary>
/// Called before the <see cref="PointerPressed"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnPointerPressed(PointerPressedEventArgs e)
{
if (_gestureRecognizers?.HandlePointerPressed(e) == true)
e.Handled = true;
}
/// <summary>
/// Called before the <see cref="PointerReleased"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnPointerReleased(PointerReleasedEventArgs e)
{
if (_gestureRecognizers?.HandlePointerReleased(e) == true)
e.Handled = true;
}
/// <summary>
/// Called before the <see cref="PointerCaptureLost"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnPointerCaptureLost(PointerCaptureLostEventArgs e)
{
_gestureRecognizers?.HandlePointerCaptureLost(e);
}
/// <summary>
/// Called before the <see cref="PointerWheelChanged"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnPointerWheelChanged(PointerWheelEventArgs e)
{
}
protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change)
{
base.OnPropertyChanged(change);
if (change.Property == IsFocusedProperty)
{
UpdatePseudoClasses(change.NewValue.GetValueOrDefault<bool>(), null);
}
else if (change.Property == IsPointerOverProperty)
{
UpdatePseudoClasses(null, change.NewValue.GetValueOrDefault<bool>());
}
else if (change.Property == IsKeyboardFocusWithinProperty)
{
PseudoClasses.Set(":focus-within", change.NewValue.GetValueOrDefault<bool>());
}
}
/// <summary>
/// Updates the <see cref="IsEffectivelyEnabled"/> property value according to the parent
/// control's enabled state and <see cref="IsEnabledCore"/>.
/// </summary>
protected void UpdateIsEffectivelyEnabled()
{
UpdateIsEffectivelyEnabled(this.GetVisualParent<InputElement>());
}
private static void IsEnabledChanged(AvaloniaPropertyChangedEventArgs e)
{
((InputElement)e.Sender).UpdateIsEffectivelyEnabled();
}
/// <summary>
/// Called before the <see cref="PointerEnter"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
private void OnPointerEnterCore(PointerEventArgs e)
{
IsPointerOver = true;
OnPointerEnter(e);
}
/// <summary>
/// Called before the <see cref="PointerLeave"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
private void OnPointerLeaveCore(PointerEventArgs e)
{
IsPointerOver = false;
OnPointerLeave(e);
}
/// <summary>
/// Updates the <see cref="IsEffectivelyEnabled"/> property based on the parent's
/// <see cref="IsEffectivelyEnabled"/>.
/// </summary>
/// <param name="parent">The parent control.</param>
private void UpdateIsEffectivelyEnabled(InputElement? parent)
{
IsEffectivelyEnabled = IsEnabledCore && (parent?.IsEffectivelyEnabled ?? true);
// PERF-SENSITIVE: This is called on entire hierarchy and using foreach or LINQ
// will cause extra allocations and overhead.
var children = VisualChildren;
// ReSharper disable once ForCanBeConvertedToForeach
for (int i = 0; i < children.Count; ++i)
{
var child = children[i] as InputElement;
child?.UpdateIsEffectivelyEnabled(this);
}
}
private void UpdatePseudoClasses(bool? isFocused, bool? isPointerOver)
{
if (isFocused.HasValue)
{
PseudoClasses.Set(":focus", isFocused.Value);
PseudoClasses.Set(":focus-visible", _isFocusVisible);
}
if (isPointerOver.HasValue)
{
PseudoClasses.Set(":pointerover", isPointerOver.Value);
}
}
}
}
| |
using System;
namespace Free.Database.Dao.Net
{
public class Field
{
internal DAO.Field fld;
public Field(DAO.Field _fld)
{
fld=_fld;
}
[Obsolete("Use FieldSize instead.", false)]
public int _30_FieldSize()
{
return fld._30_FieldSize();
}
public void AppendChunk(string chunk)
{
fld.AppendChunk(chunk);
}
public Property CreateProperty()
{
return new Property(fld.CreateProperty(System.Type.Missing, System.Type.Missing,
System.Type.Missing, System.Type.Missing));
}
public Property CreateProperty(string name)
{
return new Property(fld.CreateProperty(name, System.Type.Missing,
System.Type.Missing, System.Type.Missing));
}
public Property CreateProperty(string name, DataType type)
{
return new Property(fld.CreateProperty(name, type,
System.Type.Missing, System.Type.Missing));
}
public Property CreateProperty(string name, DataType type, object val)
{
return new Property(fld.CreateProperty(name, type, val, System.Type.Missing));
}
public Property CreateProperty(string name, DataType type, object val, bool ddl)
{
return new Property(fld.CreateProperty(name, type, val, ddl));
}
public string GetChunk(int offset, int count)
{
return (string)fld.GetChunk(offset, count);
}
public bool AllowZeroLength
{
get { return fld.AllowZeroLength; }
set { fld.AllowZeroLength=value; }
}
public FieldAttribute Attributes
{
get { return (FieldAttribute)fld.Attributes; }
set { fld.Attributes=(int)value; }
}
public CollatingOrder CollatingOrder
{
get { return (CollatingOrder)fld.CollatingOrder; }
}
public short CollectionIndex
{
get { return fld.CollectionIndex; }
}
public bool DataUpdatable
{
get { return fld.DataUpdatable; }
}
public object DefaultValue
{
get { return fld.DefaultValue; }
set { fld.DefaultValue=value; }
}
public int FieldSize
{
get { return fld.FieldSize; }
}
public string ForeignName
{
get { return fld.ForeignName; }
set { fld.ForeignName=value; }
}
public string Name
{
get { return fld.Name; }
set { fld.Name=value; }
}
public short OrdinalPosition
{
get { return fld.OrdinalPosition; }
set { fld.OrdinalPosition=value; }
}
public object OriginalValue
{
get { return fld.OriginalValue; }
}
public Properties Properties
{
get{ return new Properties(fld.Properties); }
}
public bool Required
{
get { return fld.Required; }
set { fld.Required=value; }
}
public int Size
{
get { return fld.Size; }
set { fld.Size=value; }
}
public string SourceField
{
get { return fld.SourceField; }
}
public string SourceTable
{
get { return fld.SourceTable; }
}
public DataType Type
{
get { return (DataType)fld.Type; }
}
public bool ValidateOnSet
{
get { return fld.ValidateOnSet; }
set { fld.ValidateOnSet=value; }
}
public string ValidationRule
{
get { return fld.ValidationRule; }
set { fld.ValidationRule=value; }
}
public string ValidationText
{
get { return fld.ValidationText; }
set { fld.ValidationText=value; }
}
public object Value
{
get { return fld.Value; }
set { fld.Value=value; }
}
public object VisibleValue
{
get { return fld.VisibleValue; }
}
}
class FieldsEnumerator : System.Collections.IEnumerator
{
internal System.Collections.IEnumerator Enmtr;
public FieldsEnumerator(System.Collections.IEnumerator _Enmtr) { Enmtr=_Enmtr; }
public void Reset() { Enmtr.Reset(); }
public bool MoveNext() { return Enmtr.MoveNext(); }
public object Current { get{ return new Field((DAO.Field)Enmtr.Current); } }
}
public class Fields
{
internal DAO.Fields flds;
public Fields(DAO.Fields _flds)
{
flds=_flds;
}
short Count
{
get{ return flds.Count; }
}
public System.Collections.IEnumerator GetEnumerator()
{
return new FieldsEnumerator(flds.GetEnumerator());
}
public void Refresh()
{
flds.Refresh();
}
public void Append(Field fld)
{
flds.Append(fld.fld);
}
public void Delete(string name)
{
flds.Delete(name);
}
public Field this[string index]
{
get{ return new Field(flds[index]); }
}
public Field this[int index]
{
get{ return new Field(flds[index]); }
}
}
public class IndexFields
{
internal DAO.IndexFields flds;
public IndexFields(DAO.IndexFields _flds)
{
flds=_flds;
}
short Count
{
get{ return flds.Count; }
}
public System.Collections.IEnumerator GetEnumerator()
{
return new FieldsEnumerator(flds.GetEnumerator());
}
public void Refresh()
{
flds.Refresh();
}
public void Append(Field fld)
{
flds.Append(fld.fld);
}
public void Delete(string name)
{
flds.Delete(name);
}
public Field this[string index]
{
get{ return new Field((DAO.Field)flds[index]); }
}
public Field this[int index]
{
get{ return new Field((DAO.Field)flds[index]); }
}
}
}
| |
namespace ZhangShashaCSharp
{
using Antlr4.Runtime;
using Antlr4.Runtime.Tree;
using System.Collections.Generic;
using System.Linq;
public class Tree
{
public Node root;
public Dictionary<int, Node> all_nodes = new Dictionary<int, Node>();
// function l() which gives the leftmost leaf for a given node (identified by post-order number).
Dictionary<int, int> ll = new Dictionary<int, int>();
// list of keyroots for a tree root, i.e., nodes with a left sibling, or in the case of the root, the root itself.
List<int> keyroots = new List<int>();
// list of the labels of the nodes used for node comparison
Dictionary<int, string> labels = new Dictionary<int, string>();
public Dictionary<Node, IParseTree> antlr_nodes = new Dictionary<Node, IParseTree>();
// the following constructor handles s-expression notation. E.g., ( f a ( b c ) )
public Tree(IParseTree t, Parser parser, Lexer lexer)
{
root = Convert(t, parser, lexer);
}
private Node Convert(IParseTree t, Parser parser, Lexer lexer)
{
Node n = new Node();
antlr_nodes[n] = t;
if (t is ParserRuleContext tt)
{
n.label = parser.RuleNames[tt.RuleIndex];
if (tt.children != null)
{
var ch = tt.children.Select(c => Convert(c, parser, lexer)).ToList();
n.children = ch;
}
else n.children = new List<Node>();
}
else if (t is TerminalNodeImpl ff)
{
n.label = lexer.Vocabulary.GetSymbolicName(ff.Symbol.Type);
}
return n;
}
public void Traverse()
{
// put together an ordered list of node labels of the tree
Traverse(root, labels);
}
private static Dictionary<int, string> Traverse(Node node, Dictionary<int, string> labels)
{
for (int i = 0; i < node.children.Count; i++)
{
labels = Traverse(node.children[i], labels);
}
labels.Add(node.postorder_number, node.label);
return labels;
}
public void ComputePostOrderNumber()
{
// index each node in the tree according to traversal method
ComputePostOrderNumber(root, 0);
}
private int ComputePostOrderNumber(Node node, int index)
{
for (int i = 0; i < node.children.Count; i++)
{
index = ComputePostOrderNumber(node.children[i], index);
}
index++;
node.postorder_number = index;
all_nodes[index] = node;
return index;
}
public void ComputeLeftMostLeaf()
{
// put together a function which gives l()
Leftmost();
var z = new Dictionary<int, int>();
ll = ComputeLeftMostLeaf(root, z);
}
private Dictionary<int, int> ComputeLeftMostLeaf(Node node, Dictionary<int, int> l)
{
for (int i = 0; i < node.children.Count; i++)
{
l = ComputeLeftMostLeaf(node.children[i], l);
}
l.Add(node.postorder_number, node.leftmost.postorder_number);
return l;
}
private void Leftmost()
{
Leftmost(root);
}
private static void Leftmost(Node node)
{
if (node == null)
return;
for (int i = 0; i < node.children.Count; i++)
{
Leftmost(node.children[i]);
}
if (node.children.Count == 0)
{
node.leftmost = node;
}
else
{
node.leftmost = node.children[0].leftmost;
}
}
public void Keyroots()
{
// calculate the keyroots
for (int i = 1; i <= ll.Count; i++)
{
int flag = 0;
for (int j = i + 1; j <= ll.Count; j++)
{
if (ll[j] == ll[i])
{
flag = 1;
}
}
if (flag == 0)
{
this.keyroots.Add(i);
}
}
}
static int[,] tree_distance;
static List<Operation>[,] tree_operations;
public static (int, List<Operation>) ZhangShasha(Tree tree1, Tree tree2)
{
tree1.ComputePostOrderNumber();
tree1.ComputeLeftMostLeaf();
tree1.Keyroots();
tree1.Traverse();
tree2.ComputePostOrderNumber();
tree2.ComputeLeftMostLeaf();
tree2.Keyroots();
tree2.Traverse();
Dictionary<int, int> l1 = tree1.ll;
List<int> keyroots1 = tree1.keyroots;
Dictionary<int, int> l2 = tree2.ll;
List<int> keyroots2 = tree2.keyroots;
// space complexity of the algorithm
tree_distance = new int[l1.Count + 1, l2.Count + 1];
tree_operations = new List<Operation>[l1.Count + 1, l2.Count + 1];
for (int m = 0; m <= l1.Count; ++m)
for (int n = 0; n <= l2.Count; ++n)
tree_operations[m, n] = new List<Operation>();
// solve subproblems
for (int i1 = 1; i1 <= keyroots1.Count; i1++)
{
for (int j1 = 1; j1 <= keyroots2.Count; j1++)
{
int i = keyroots1[i1 - 1];
int j = keyroots2[j1 - 1];
Treedist(l1, l2, i, j, tree1, tree2);
}
}
return (tree_distance[l1.Count, l2.Count], tree_operations[l1.Count, l2.Count]);
}
private static void Treedist(Dictionary<int, int> l1, Dictionary<int, int> l2, int i, int j, Tree tree1, Tree tree2)
{
int[,] forest_distance = new int[l1.Count + 1, l2.Count + 1];
List<Operation>[,] forest_operations = new List<Operation>[l1.Count + 1, l2.Count + 1];
for (int m = 0; m < l1.Count + 1; ++m)
for (int n = 0; n < l2.Count + 1; ++n)
forest_operations[m, n] = new List<Operation>();
// costs of the three atomic operations
int Delete = 1;
int Insert = 1;
int Relabel = 1;
for (int i1 = l1[i]; i1 <= i; i1++)
{
forest_distance[i1, 0] = forest_distance[i1 - 1, 0] + Delete;
forest_operations[i1, 0] = new List<Operation>(forest_operations[i1 - 1, 0]);
forest_operations[i1, 0].Add(new Operation() { O = Operation.Op.Delete, N1 = i1});
}
for (int j1 = l2[j]; j1 <= j; j1++)
{
forest_distance[0, j1] = forest_distance[0, j1 - 1] + Insert;
forest_operations[0, j1] = new List<Operation>(forest_operations[0, j1 - 1]);
forest_operations[0, j1].Add(new Operation() { O = Operation.Op.Insert, N2 = j1});
}
for (int i1 = l1[i]; i1 <= i; i1++)
{
for (int j1 = l2[j]; j1 <= j; j1++)
{
if (l1[i1] == l1[i] && l2[j1] == l2[j])
{
var z = i1 - 1 < l1[i] ? 0 : i1 - 1;
var z2 = j1 - 1 < l2[j] ? 0 : j1 - 1;
var i_temp = forest_distance[z, j1] + Delete;
var i_list = new List<Operation>(forest_operations[z, j1]);
i_list.Add(new Operation() { O = Operation.Op.Delete, N1 = i1 });
var i_op = i_list;
var j_temp = forest_distance[i1, z2] + Insert;
var j_list = new List<Operation>(forest_operations[i1, z2]);
j_list.Add(new Operation() { O = Operation.Op.Insert, N2 = j1 });
var j_op = j_list;
var cost = tree1.labels[i1] == tree2.labels[j1] ? 0 : Relabel;
var k_temp = forest_distance[z, z2] + cost;
var k_list = new List<Operation>(forest_operations[z, z2]);
if (cost != 0)
k_list.Add(new Operation() { O = Operation.Op.Change, N1 = i1, N2 = j1 });
var k_op = k_list;
if (i_temp < j_temp)
{
if (i_temp < k_temp)
{
forest_distance[i1, j1] = i_temp;
forest_operations[i1, j1] = i_op;
}
else
{
forest_distance[i1, j1] = k_temp;
forest_operations[i1, j1] = k_op;
}
}
else
{
if (j_temp < k_temp)
{
forest_distance[i1, j1] = j_temp;
forest_operations[i1, j1] = j_op;
}
else
{
forest_distance[i1, j1] = k_temp;
forest_operations[i1, j1] = k_op;
}
}
tree_distance[i1, j1] = forest_distance[i1, j1];
tree_operations[i1, j1] = forest_operations[i1, j1];
}
else
{
var z = i1 - 1 < l1[i] ? 0 : i1 - 1;
var z2 = j1 - 1 < l2[j] ? 0 : j1 - 1;
var i_temp = forest_distance[z, j1] + Delete;
var i_list = new List<Operation>(forest_operations[z, j1]);
i_list.Add(new Operation() { O = Operation.Op.Delete, N1 = i1 });
var i_op = i_list;
var j_temp = forest_distance[i1, z2] + Insert;
var j_list = new List<Operation>(forest_operations[i1, z2]);
j_list.Add(new Operation() { O = Operation.Op.Insert, N2 = j1 });
var j_op = j_list;
var k_temp = forest_distance[z, z2] + tree_distance[i1, j1];
var k_list = new List<Operation>(forest_operations[z, z2]);
k_list.AddRange(tree_operations[i1, j1]);
var k_op = k_list;
if (i_temp < j_temp)
{
if (i_temp < k_temp)
{
forest_distance[i1, j1] = i_temp;
forest_operations[i1, j1] = i_op;
}
else
{
forest_distance[i1, j1] = k_temp;
forest_operations[i1, j1] = k_op;
}
}
else
{
if (j_temp < k_temp)
{
forest_distance[i1, j1] = j_temp;
forest_operations[i1, j1] = j_op;
}
else
{
forest_distance[i1, j1] = k_temp;
forest_operations[i1, j1] = k_op;
}
}
}
}
}
tree_distance[i, j] = forest_distance[i, j];
tree_operations[i, j] = forest_operations[i, j];
}
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Windows.Forms;
using SDRSharp.Radio;
namespace SDRSharp.PanView
{
public class SpectrumAnalyzer : UserControl
{
private const float TrackingFontSize = 16.0f;
private const int AxisMargin = 30;
private const int CarrierPenWidth = 1;
private const int GradientAlpha = 180;
public const float DefaultCursorHeight = 32.0f;
private readonly static Color _spectrumColor = Utils.GetColorSetting("spectrumAnalyzerColor", Color.DarkGray);
private readonly static bool _fillSpectrumAnalyzer = Utils.GetBooleanSetting("fillSpectrumAnalyzer");
private double _attack;
private double _decay;
private bool _performNeeded;
private bool _drawBackgroundNeeded;
private byte[] _maxSpectrum;
private byte[] _spectrum;
private bool[] _peaks;
private byte[] _temp;
private byte[] _scaledPowerSpectrum;
private Bitmap _bkgBuffer;
private Bitmap _buffer;
private Graphics _graphics;
private long _spectrumWidth;
private long _centerFrequency;
private long _displayCenterFrequency;
private Point[] _points;
private BandType _bandType;
private int _filterBandwidth;
private int _filterOffset;
private int _stepSize = 1000;
private float _xIncrement;
private long _frequency;
private float _lower;
private float _upper;
private int _zoom;
private float _scale = 1f;
private int _oldX;
private int _trackingX;
private int _trackingY;
private long _trackingFrequency;
private int _oldFilterBandwidth;
private long _oldFrequency;
private long _oldCenterFrequency;
private bool _changingBandwidth;
private bool _changingFrequency;
private bool _changingCenterFrequency;
private bool _useSmoothing;
private bool _enableFilter = true;
private bool _hotTrackNeeded;
private bool _useSnap;
private bool _markPeaks;
private bool _showMaxLine;
private float _trackingPower;
private string _statusText;
private int _displayRange = 130;
private int _displayOffset;
private LinearGradientBrush _gradientBrush;
private ColorBlend _gradientColorBlend = Utils.GetGradientBlend(GradientAlpha, "spectrumAnalyzerGradient");
public SpectrumAnalyzer()
{
_bkgBuffer = new Bitmap(ClientRectangle.Width, ClientRectangle.Height, PixelFormat.Format32bppPArgb);
_buffer = new Bitmap(ClientRectangle.Width, ClientRectangle.Height, PixelFormat.Format32bppPArgb);
_graphics = Graphics.FromImage(_buffer);
_gradientBrush = new LinearGradientBrush(new Rectangle(AxisMargin, AxisMargin, ClientRectangle.Width - AxisMargin, ClientRectangle.Height - AxisMargin), Color.White, Color.Black, LinearGradientMode.Vertical);
_gradientBrush.InterpolationColors = _gradientColorBlend;
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
SetStyle(ControlStyles.DoubleBuffer, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
UpdateStyles();
}
~SpectrumAnalyzer()
{
_buffer.Dispose();
_graphics.Dispose();
_gradientBrush.Dispose();
}
public event ManualFrequencyChange FrequencyChanged;
public event ManualFrequencyChange CenterFrequencyChanged;
public event ManualBandwidthChange BandwidthChanged;
public int SpectrumWidth
{
get
{
return (int) _spectrumWidth;
}
set
{
if (_spectrumWidth != value)
{
_spectrumWidth = value;
ApplyZoom();
}
}
}
public int FilterBandwidth
{
get
{
return _filterBandwidth;
}
set
{
if (_filterBandwidth != value)
{
_filterBandwidth = value;
_performNeeded = true;
}
}
}
public int FilterOffset
{
get
{
return _filterOffset;
}
set
{
if (_filterOffset != value)
{
_filterOffset = value;
_performNeeded = true;
}
}
}
public BandType BandType
{
get
{
return _bandType;
}
set
{
if (_bandType != value)
{
_bandType = value;
_performNeeded = true;
}
}
}
public long Frequency
{
get
{
return _frequency;
}
set
{
if (_frequency != value)
{
_frequency = value;
_performNeeded = true;
}
}
}
public long CenterFrequency
{
get
{
return _centerFrequency;
}
set
{
if (_centerFrequency != value)
{
_displayCenterFrequency += value - _centerFrequency;
_centerFrequency = value;
_drawBackgroundNeeded = true;
}
}
}
public int DisplayRange
{
get { return _displayRange; }
set
{
if (_displayRange != value)
{
_displayRange = value;
_drawBackgroundNeeded = true;
}
}
}
public int DisplayOffset
{
get { return _displayOffset; }
set
{
if (_displayOffset != value)
{
_displayOffset = value;
_drawBackgroundNeeded = true;
}
}
}
public int Zoom
{
get
{
return _zoom;
}
set
{
if (_zoom != value)
{
_zoom = value;
ApplyZoom();
}
}
}
public bool UseSmoothing
{
get { return _useSmoothing; }
set { _useSmoothing = value; }
}
public bool EnableFilter
{
get { return _enableFilter; }
set
{
_enableFilter = value;
_performNeeded = true;
}
}
public string StatusText
{
get { return _statusText; }
set
{
_statusText = value;
_performNeeded = true;
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public ColorBlend GradientColorBlend
{
get
{
return _gradientColorBlend;
}
set
{
_gradientColorBlend = new ColorBlend(value.Colors.Length);
for (var i = 0; i < value.Colors.Length; i++)
{
_gradientColorBlend.Colors[i] = Color.FromArgb(GradientAlpha, value.Colors[i]);
_gradientColorBlend.Positions[i] = value.Positions[i];
}
_gradientBrush.Dispose();
_gradientBrush = new LinearGradientBrush(new Rectangle(AxisMargin, AxisMargin, ClientRectangle.Width - AxisMargin, ClientRectangle.Height - AxisMargin), Color.White, Color.Black, LinearGradientMode.Vertical);
_gradientBrush.InterpolationColors = _gradientColorBlend;
_drawBackgroundNeeded = true;
}
}
public double Attack
{
get { return _attack; }
set { _attack = value; }
}
public double Decay
{
get { return _decay; }
set { _decay = value; }
}
public int StepSize
{
get { return _stepSize; }
set
{
if (_stepSize != value)
{
_stepSize = value;
_drawBackgroundNeeded = true;
_performNeeded = true;
}
}
}
public bool UseSnap
{
get { return _useSnap; }
set { _useSnap = value; }
}
public bool MarkPeaks
{
get { return _markPeaks; }
set { _markPeaks = value; }
}
public bool ShowMaxLine
{
get { return _showMaxLine; }
set { _showMaxLine = value; }
}
private void ApplyZoom()
{
_scale = (float) Math.Pow(10, _zoom * Waterfall.MaxZoom / 100.0f);
if (_spectrumWidth > 0)
{
_displayCenterFrequency = GetDisplayCenterFrequency();
_xIncrement = _scale * (ClientRectangle.Width - 2 * AxisMargin) / _spectrumWidth;
_drawBackgroundNeeded = true;
}
}
public void CenterZoom()
{
_displayCenterFrequency = GetDisplayCenterFrequency();
}
private long GetDisplayCenterFrequency()
{
var f = _frequency;
switch (_bandType)
{
case BandType.Lower:
f -= _filterBandwidth / 2 + _filterOffset;
break;
case BandType.Upper:
f += _filterBandwidth / 2 + _filterOffset;
break;
}
var lowerLeadingSpectrum = (long) ((_centerFrequency - _spectrumWidth / 2) - (f - _spectrumWidth / _scale / 2));
if (lowerLeadingSpectrum > 0)
{
f += lowerLeadingSpectrum + 10;
}
var upperLeadingSpectrum = (long) ((f + _spectrumWidth / _scale / 2) - (_centerFrequency + _spectrumWidth / 2));
if (upperLeadingSpectrum > 0)
{
f -= upperLeadingSpectrum + 10;
}
return f;
}
public void Perform()
{
if (_drawBackgroundNeeded)
{
DrawBackground();
}
if (_performNeeded || _drawBackgroundNeeded)
{
DrawForeground();
Invalidate();
}
_performNeeded = false;
_drawBackgroundNeeded = false;
}
private void DrawCursor()
{
_lower = 0f;
float bandpassOffset;
var bandpassWidth = 0f;
var cursorWidth = Math.Max((_filterBandwidth + _filterOffset) * _xIncrement, 2);
var xCarrier = (float) ClientRectangle.Width / 2 + (_frequency - _displayCenterFrequency) * _xIncrement;
switch (_bandType)
{
case BandType.Upper:
bandpassOffset = _filterOffset * _xIncrement;
bandpassWidth = cursorWidth - bandpassOffset;
_lower = xCarrier + bandpassOffset;
break;
case BandType.Lower:
bandpassOffset = _filterOffset * _xIncrement;
bandpassWidth = cursorWidth - bandpassOffset;
_lower = xCarrier - bandpassOffset - bandpassWidth;
break;
case BandType.Center:
_lower = xCarrier - cursorWidth / 2;
bandpassWidth = cursorWidth;
break;
}
_upper = _lower + bandpassWidth;
using (var transparentBackground = new SolidBrush(Color.FromArgb(80, Color.DarkGray)))
using (var redPen = new Pen(Color.Red))
using (var graphics = Graphics.FromImage(_buffer))
using (var fontFamily = new FontFamily("Arial"))
using (var path = new GraphicsPath())
using (var outlinePen = new Pen(Color.Black))
{
if (_enableFilter && cursorWidth < ClientRectangle.Width)
{
var carrierPen = redPen;
carrierPen.Width = CarrierPenWidth;
graphics.FillRectangle(transparentBackground, (int) _lower + 1, 0, (int) bandpassWidth, ClientRectangle.Height);
if (xCarrier >= AxisMargin && xCarrier <= ClientRectangle.Width - AxisMargin)
{
graphics.DrawLine(carrierPen, xCarrier, 0f, xCarrier, ClientRectangle.Height);
}
}
if (_markPeaks && _spectrumWidth > 0)
{
var windowSize = (int) bandpassWidth;
windowSize = Math.Max(windowSize, 10);
windowSize = Math.Min(windowSize, _spectrum.Length);
PeakDetector.GetPeaks(_spectrum, _peaks, windowSize);
var yIncrement = (ClientRectangle.Height - 2 * AxisMargin) / (float) byte.MaxValue;
for (var i = 0; i < _peaks.Length; i++)
{
if (_peaks[i])
{
var y = (int) (ClientRectangle.Height - AxisMargin - _spectrum[i] * yIncrement);
var x = i + AxisMargin;
graphics.DrawEllipse(Pens.Yellow, x - 5, y - 5, 10, 10);
}
}
}
if (_hotTrackNeeded && _trackingX >= AxisMargin && _trackingX <= ClientRectangle.Width - AxisMargin &&
_trackingY >= AxisMargin && _trackingY <= ClientRectangle.Height - AxisMargin)
{
if (_spectrum != null && !_changingFrequency && !_changingCenterFrequency && !_changingBandwidth)
{
var index = _trackingX - AxisMargin;
if (_useSnap)
{
// Todo: snap the index
}
if (index > 0 && index < _spectrum.Length)
{
graphics.DrawLine(redPen, _trackingX, 0, _trackingX, ClientRectangle.Height);
}
}
string fstring;
if (_changingFrequency)
{
fstring = "VFO = " + GetFrequencyDisplay(_frequency);
}
else if (_changingBandwidth)
{
fstring = "BW = " + GetFrequencyDisplay(_filterBandwidth);
}
else if (_changingCenterFrequency)
{
fstring = "Center Freq. = " + GetFrequencyDisplay(_centerFrequency);
}
else
{
fstring = string.Format("{0}\r\n{1:0.##}dB", GetFrequencyDisplay(_trackingFrequency), _trackingPower);
}
path.AddString(fstring, fontFamily, (int)FontStyle.Regular, TrackingFontSize, Point.Empty, StringFormat.GenericTypographic);
var stringSize = path.GetBounds();
var currentCursor = Cursor.Current;
var xOffset = _trackingX + 15.0f;
var yOffset = _trackingY + (currentCursor == null ? DefaultCursorHeight : currentCursor.Size.Height) - 8.0f;
xOffset = Math.Min(xOffset, ClientRectangle.Width - stringSize.Width - 5);
yOffset = Math.Min(yOffset, ClientRectangle.Height - stringSize.Height - 5);
path.Reset();
path.AddString(fstring, fontFamily, (int)FontStyle.Regular, TrackingFontSize, new Point((int)xOffset, (int)yOffset), StringFormat.GenericTypographic);
var smoothingMode = graphics.SmoothingMode;
var interpolationMode = graphics.InterpolationMode;
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
outlinePen.Width = 2;
graphics.DrawPath(outlinePen, path);
graphics.FillPath(Brushes.White, path);
graphics.SmoothingMode = smoothingMode;
graphics.InterpolationMode = interpolationMode;
}
}
}
public unsafe void Render(float* powerSpectrum, int length)
{
if (_scaledPowerSpectrum == null || _scaledPowerSpectrum.Length != length)
{
_scaledPowerSpectrum = new byte[length];
}
fixed (byte* scaledPowerSpectrumPtr = _scaledPowerSpectrum)
{
var displayOffset = _displayOffset / 10 * 10;
var displayRange = _displayRange / 10 * 10;
Fourier.ScaleFFT(powerSpectrum, scaledPowerSpectrumPtr, length, displayOffset - displayRange, displayOffset);
}
var scaledLength = (int) (length / _scale);
var offset = (int) ((length - scaledLength) / 2.0 + length * (double) (_displayCenterFrequency - _centerFrequency) / _spectrumWidth);
if (_useSmoothing)
{
Fourier.SmoothCopy(_scaledPowerSpectrum, _temp, length, _scale, offset);
for (var i = 0; i < _spectrum.Length; i++)
{
var ratio = _spectrum[i] < _temp[i] ? Attack : Decay;
_spectrum[i] = (byte) Math.Round(_spectrum[i] * (1 - ratio) + _temp[i] * ratio);
}
}
else
{
Fourier.SmoothCopy(_scaledPowerSpectrum, _spectrum, length, _scale, offset);
}
for (var i = 0; i < _spectrum.Length; i++)
{
if (_maxSpectrum[i] < _spectrum[i])
_maxSpectrum[i] = _spectrum[i];
}
_performNeeded = true;
}
private void DrawBackground()
{
using (var fontBrush = new SolidBrush(Color.Silver))
using (var gridPen = new Pen(Color.FromArgb(80, 80, 80)))
using (var axisPen = new Pen(Color.DarkGray))
using (var font = new Font("Arial", 8f))
using (var graphics = Graphics.FromImage(_bkgBuffer))
{
ConfigureGraphics(graphics);
// Background
graphics.Clear(Color.Black);
if (_spectrumWidth > 0)
{
#region Frequency markers
var baseLabelLength = (int)graphics.MeasureString("1,000,000.000kHz", font).Width;
var frequencyStep = (int)(_spectrumWidth / _scale * baseLabelLength / (ClientRectangle.Width - 2 * AxisMargin));
int stepSnap = _stepSize;
frequencyStep = frequencyStep / stepSnap * stepSnap + stepSnap;
var lineCount = (int)(_spectrumWidth / _scale / frequencyStep) + 4;
var xIncrement = (ClientRectangle.Width - 2.0f * AxisMargin) * frequencyStep * _scale / _spectrumWidth;
var centerShift = (int)((_displayCenterFrequency % frequencyStep) * (ClientRectangle.Width - 2.0 * AxisMargin) * _scale / _spectrumWidth);
for (var i = -lineCount / 2; i < lineCount / 2; i++)
{
var x = (ClientRectangle.Width - 2 * AxisMargin) / 2 + AxisMargin + xIncrement * i - centerShift;
if (x >= AxisMargin && x <= ClientRectangle.Width - AxisMargin)
{
graphics.DrawLine(gridPen, x, AxisMargin, x, ClientRectangle.Height - AxisMargin);
}
}
for (var i = -lineCount / 2; i < lineCount / 2; i++)
{
var frequency = _displayCenterFrequency + i * frequencyStep - _displayCenterFrequency % frequencyStep;
var fstring = GetFrequencyDisplay(frequency);
var sizeF = graphics.MeasureString(fstring, font);
var width = sizeF.Width;
var x = (ClientRectangle.Width - 2 * AxisMargin) / 2 + AxisMargin + xIncrement * i - centerShift;
if (x >= AxisMargin && x <= ClientRectangle.Width - AxisMargin)
{
x -= width / 2f;
graphics.DrawString(fstring, font, fontBrush, x, ClientRectangle.Height - AxisMargin + 8f);
}
}
#endregion
}
#region Grid
gridPen.DashStyle = DashStyle.Dash;
var powerMarkerCount = _displayRange / 10;
// Power axis
var yIncrement = (ClientRectangle.Height - 2 * AxisMargin) / (float) powerMarkerCount;
for (var i = 1; i <= powerMarkerCount; i++)
{
graphics.DrawLine(gridPen, AxisMargin, (int)(ClientRectangle.Height - AxisMargin - i * yIncrement), ClientRectangle.Width - AxisMargin, (int)(ClientRectangle.Height - AxisMargin - i * yIncrement));
}
var displayOffset = _displayOffset / 10 * 10;
for (var i = 0; i <= powerMarkerCount; i++)
{
var db = (displayOffset - (powerMarkerCount - i) * 10).ToString();
var sizeF = graphics.MeasureString(db, font);
var width = sizeF.Width;
var height = sizeF.Height;
graphics.DrawString(db, font, fontBrush, AxisMargin - width - 3, ClientRectangle.Height - AxisMargin - i * yIncrement - height / 2f);
}
// Axis
graphics.DrawLine(axisPen, AxisMargin, AxisMargin, AxisMargin, ClientRectangle.Height - AxisMargin);
graphics.DrawLine(axisPen, AxisMargin, ClientRectangle.Height - AxisMargin, ClientRectangle.Width - AxisMargin, ClientRectangle.Height - AxisMargin);
#endregion
}
}
public static string GetFrequencyDisplay(long frequency)
{
string result;
if (frequency == 0)
{
result = "DC";
}
else if (Math.Abs(frequency) > 1500000000)
{
result = string.Format("{0:#,0.000 000}GHz", frequency / 1000000000.0);
}
else if (Math.Abs(frequency) > 30000000)
{
result = string.Format("{0:0,0.000#}MHz", frequency / 1000000.0);
}
else if (Math.Abs(frequency) > 1000)
{
result = string.Format("{0:#,#.###}kHz", frequency / 1000.0);
}
else
{
result = string.Format("{0}Hz", frequency);
}
return result;
}
public static void ConfigureGraphics(Graphics graphics)
{
graphics.CompositingMode = CompositingMode.SourceOver;
graphics.CompositingQuality = CompositingQuality.HighSpeed;
graphics.SmoothingMode = SmoothingMode.None;
graphics.PixelOffsetMode = PixelOffsetMode.HighSpeed;
graphics.InterpolationMode = InterpolationMode.High;
}
private void DrawForeground()
{
if (ClientRectangle.Width <= AxisMargin || ClientRectangle.Height <= AxisMargin)
{
return;
}
CopyBackground();
DrawSpectrum();
DrawStatusText();
DrawCursor();
}
private unsafe void CopyBackground()
{
var data1 = _buffer.LockBits(ClientRectangle, ImageLockMode.WriteOnly, _buffer.PixelFormat);
var data2 = _bkgBuffer.LockBits(ClientRectangle, ImageLockMode.ReadOnly, _bkgBuffer.PixelFormat);
Utils.Memcpy((void*) data1.Scan0, (void*) data2.Scan0, Math.Abs(data1.Stride) * data1.Height);
_buffer.UnlockBits(data1);
_bkgBuffer.UnlockBits(data2);
}
private void DrawSpectrum()
{
if (_spectrum == null || _spectrum.Length == 0)
{
return;
}
var xIncrement = (ClientRectangle.Width - 2 * AxisMargin) / (float) _spectrum.Length;
var yIncrement = (ClientRectangle.Height - 2 * AxisMargin) / (float) byte.MaxValue;
if (_showMaxLine != false)
{
using (var spectrumPen = new Pen(Color.Red))
{
for (var i = 0; i < _spectrum.Length; i++)
{
var strenght = _maxSpectrum[i];
var x = (int)(AxisMargin + i * xIncrement);
var y = (int)(ClientRectangle.Height - AxisMargin - strenght * yIncrement);
_points[i + 1].X = x;
_points[i + 1].Y = y;
}
//if (_fillSpectrumAnalyzer)
//{
// _points[0].X = AxisMargin;
// _points[0].Y = ClientRectangle.Height - AxisMargin + 1;
// _points[_points.Length - 1].X = ClientRectangle.Width - AxisMargin;
// _points[_points.Length - 1].Y = ClientRectangle.Height - AxisMargin + 1;
// _graphics.FillPolygon(_gradientBrush, _points);
//}
_points[0] = _points[1];
_points[_points.Length - 1] = _points[_points.Length - 2];
_graphics.DrawLines(spectrumPen, _points);
}
}
using (var spectrumPen = new Pen(_spectrumColor))
{
for (var i = 0; i < _spectrum.Length; i++)
{
var strenght = _spectrum[i];
var x = (int) (AxisMargin + i * xIncrement);
var y = (int) (ClientRectangle.Height - AxisMargin - strenght * yIncrement);
_points[i + 1].X = x;
_points[i + 1].Y = y;
}
if (_fillSpectrumAnalyzer)
{
_points[0].X = AxisMargin;
_points[0].Y = ClientRectangle.Height - AxisMargin + 1;
_points[_points.Length - 1].X = ClientRectangle.Width - AxisMargin;
_points[_points.Length - 1].Y = ClientRectangle.Height - AxisMargin + 1;
_graphics.FillPolygon(_gradientBrush, _points);
}
_points[0] = _points[1];
_points[_points.Length - 1] = _points[_points.Length - 2];
_graphics.DrawLines(spectrumPen, _points);
}
}
private void DrawStatusText()
{
if (string.IsNullOrEmpty(_statusText))
{
return;
}
using (var font = new Font("Lucida Console", 9))
{
_graphics.DrawString(_statusText, font, Brushes.White, AxisMargin, 10);
}
}
protected override void OnPaint(PaintEventArgs e)
{
ConfigureGraphics(e.Graphics);
e.Graphics.DrawImageUnscaled(_buffer, 0, 0);
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
if (ClientRectangle.Width > 0 && ClientRectangle.Height > 0)
{
_buffer.Dispose();
_graphics.Dispose();
_bkgBuffer.Dispose();
_buffer = new Bitmap(ClientRectangle.Width, ClientRectangle.Height, PixelFormat.Format32bppPArgb);
_graphics = Graphics.FromImage(_buffer);
ConfigureGraphics(_graphics);
_bkgBuffer = new Bitmap(ClientRectangle.Width, ClientRectangle.Height, PixelFormat.Format32bppPArgb);
var length = ClientRectangle.Width - 2 * AxisMargin;
var oldSpectrum = _spectrum;
_maxSpectrum = new byte[length];
_spectrum = new byte[length];
_peaks = new bool[length];
if (oldSpectrum != null)
{
Fourier.SmoothCopy(oldSpectrum, _spectrum, oldSpectrum.Length, 1, 0);
}
else
{
for (var i = 0; i < _spectrum.Length; i++)
{
_spectrum[i] = 0;
}
}
_temp = new byte[length];
_points = new Point[length + 2];
if (_spectrumWidth > 0)
{
_xIncrement = _scale * (ClientRectangle.Width - 2 * AxisMargin) / _spectrumWidth;
}
_gradientBrush.Dispose();
_gradientBrush = new LinearGradientBrush(new Rectangle(AxisMargin, AxisMargin, ClientRectangle.Width - AxisMargin, ClientRectangle.Height - AxisMargin), Color.White, Color.Black, LinearGradientMode.Vertical);
_gradientBrush.InterpolationColors = _gradientColorBlend;
_drawBackgroundNeeded = true;
Perform();
}
}
protected override void OnPaintBackground(PaintEventArgs e)
{
// Prevent default background painting
}
protected virtual void OnFrequencyChanged(FrequencyEventArgs e)
{
if (FrequencyChanged != null)
{
FrequencyChanged(this, e);
}
}
protected virtual void OnCenterFrequencyChanged(FrequencyEventArgs e)
{
if (CenterFrequencyChanged != null)
{
CenterFrequencyChanged(this, e);
}
}
protected virtual void OnBandwidthChanged(BandwidthEventArgs e)
{
if (BandwidthChanged != null)
{
BandwidthChanged(this, e);
}
}
private void UpdateFrequency(long f, FrequencyChangeSource source)
{
var min = (long) (_displayCenterFrequency - _spectrumWidth / _scale / 2);
if (f < min)
{
f = min;
}
var max = (long) (_displayCenterFrequency + _spectrumWidth / _scale / 2);
if (f > max)
{
f = max;
}
if (_useSnap)
{
f = (f + Math.Sign(f) * _stepSize / 2) / _stepSize * _stepSize;
}
if (f != _frequency)
{
var args = new FrequencyEventArgs(f, source);
OnFrequencyChanged(args);
if (!args.Cancel)
{
_frequency = args.Frequency;
_performNeeded = true;
}
}
}
private void UpdateCenterFrequency(long f, FrequencyChangeSource source)
{
if (f < 0)
{
f = 0;
}
if (_useSnap)
{
f = (f + Math.Sign(f) * _stepSize / 2) / _stepSize * _stepSize;
}
if (f != _centerFrequency)
{
var args = new FrequencyEventArgs(f, source);
OnCenterFrequencyChanged(args);
if (!args.Cancel)
{
var delta = args.Frequency - _centerFrequency;
_displayCenterFrequency += delta;
_centerFrequency = args.Frequency;
_drawBackgroundNeeded = true;
}
}
}
private void UpdateBandwidth(int bw)
{
bw = 10 * (bw / 10);
if (bw < 10)
{
bw = 10;
}
if (bw != _filterBandwidth)
{
var args = new BandwidthEventArgs(bw);
OnBandwidthChanged(args);
if (!args.Cancel)
{
_filterBandwidth = args.Bandwidth;
_performNeeded = true;
}
}
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (e.Button == MouseButtons.Left)
{
var cursorWidth = Math.Max((_filterBandwidth + _filterOffset) * _xIncrement, 2);
if (e.X > _lower && e.X < _upper && cursorWidth < ClientRectangle.Width)
{
_oldX = e.X;
_oldFrequency = _frequency;
_changingFrequency = true;
}
else if (_enableFilter &&
((Math.Abs(e.X - _lower + Waterfall.CursorSnapDistance) <= Waterfall.CursorSnapDistance &&
(_bandType == BandType.Center || _bandType == BandType.Lower))
||
(Math.Abs(e.X - _upper - Waterfall.CursorSnapDistance) <= Waterfall.CursorSnapDistance &&
(_bandType == BandType.Center || _bandType == BandType.Upper))))
{
_oldX = e.X;
_oldFilterBandwidth = _filterBandwidth;
_changingBandwidth = true;
}
else
{
_oldX = e.X;
_oldCenterFrequency = _centerFrequency;
_changingCenterFrequency = true;
}
}
else if (e.Button == MouseButtons.Right)
{
UpdateFrequency(_frequency / Waterfall.RightClickSnapDistance * Waterfall.RightClickSnapDistance, FrequencyChangeSource.Click);
for(int i=0;i<_maxSpectrum.Length;i++)
_maxSpectrum[i] = 0;
}
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (_changingCenterFrequency && e.X == _oldX)
{
var f = (long)((_oldX - ClientRectangle.Width / 2) * _spectrumWidth / _scale / (ClientRectangle.Width - 2 * AxisMargin) + _displayCenterFrequency);
UpdateFrequency(f, FrequencyChangeSource.Click);
}
_changingCenterFrequency = false;
_drawBackgroundNeeded = true;
_changingBandwidth = false;
_changingFrequency = false;
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
_trackingX = e.X;
_trackingY = e.Y;
_trackingFrequency = (long)((e.X - ClientRectangle.Width / 2) * _spectrumWidth / _scale / (ClientRectangle.Width - 2 * AxisMargin) + _displayCenterFrequency);
if (_useSnap)
{
_trackingFrequency = (_trackingFrequency + Math.Sign(_trackingFrequency) * _stepSize / 2) / _stepSize * _stepSize;
}
var displayRange = _displayRange / 10 * 10;
var displayOffset = _displayOffset / 10 * 10;
var yIncrement = (ClientRectangle.Height - 2 * AxisMargin) / (float) displayRange;
_trackingPower = displayOffset - displayRange - (_trackingY + AxisMargin - ClientRectangle.Height) / yIncrement;
if (_changingFrequency)
{
var f = (long) ((e.X - _oldX) * _spectrumWidth / _scale / (ClientRectangle.Width - 2 * AxisMargin) + _oldFrequency);
UpdateFrequency(f, FrequencyChangeSource.Drag);
}
else if (_changingCenterFrequency)
{
var f = (long) ((_oldX - e.X) * _spectrumWidth / _scale / (ClientRectangle.Width - 2 * AxisMargin) + _oldCenterFrequency);
UpdateCenterFrequency(f, FrequencyChangeSource.Drag);
}
else if (_changingBandwidth)
{
var bw = 0;
switch (_bandType)
{
case BandType.Upper:
bw = e.X - _oldX;
break;
case BandType.Lower:
bw = _oldX - e.X;
break;
case BandType.Center:
bw = (_oldX > (_lower + _upper) / 2 ? e.X - _oldX : _oldX - e.X) * 2;
break;
}
bw = (int) (bw * _spectrumWidth / _scale / (ClientRectangle.Width - 2 * AxisMargin) + _oldFilterBandwidth);
UpdateBandwidth(bw);
}
else if (_enableFilter &&
((Math.Abs(e.X - _lower + Waterfall.CursorSnapDistance) <= Waterfall.CursorSnapDistance &&
(_bandType == BandType.Center || _bandType == BandType.Lower))
||
(Math.Abs(e.X - _upper - Waterfall.CursorSnapDistance) <= Waterfall.CursorSnapDistance &&
(_bandType == BandType.Center || _bandType == BandType.Upper))))
{
Cursor = Cursors.SizeWE;
}
else
{
Cursor = Cursors.Default;
}
_performNeeded = true;
}
protected override void OnMouseWheel(MouseEventArgs e)
{
base.OnMouseWheel(e);
UpdateFrequency(_frequency + _stepSize * Math.Sign(e.Delta), FrequencyChangeSource.Scroll);
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
_hotTrackNeeded = false;
_performNeeded = true;
}
protected override void OnMouseEnter(EventArgs e)
{
Focus();
base.OnMouseEnter(e);
_hotTrackNeeded = true;
}
}
}
| |
//
// RatingEntry.cs
//
// Authors:
// Aaron Bockover <[email protected]>
// Gabriel Burt <[email protected]>
//
// Copyright (C) 2006-2008 Novell, Inc.
// Copyright (C) 2006 Gabriel Burt
//
// 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 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 Gtk;
using System;
using Hyena.Gui;
namespace Hyena.Widgets
{
public class RatingEntry : Widget
{
private RatingRenderer renderer;
private Gdk.Rectangle event_alloc;
private int hover_value = -1;
private bool interior_focus;
private int focus_width;
private Gdk.Window event_window;
public event EventHandler Changing;
public event EventHandler Changed;
static RatingEntry ()
{
#if ENABLE_ATK
RatingAccessibleFactory.Init ();
#endif
}
public RatingEntry () : this (0)
{
WidgetFlags |= Gtk.WidgetFlags.NoWindow;
}
public RatingEntry (int rating)
{
renderer = new RatingRenderer ();
renderer.Value = rating;
CanFocus = true;
Name = "GtkEntry";
}
protected virtual void OnChanging ()
{
EventHandler handler = Changing;
if (handler != null) {
handler (this, new EventArgs ());
}
}
protected virtual void OnChanged ()
{
QueueDraw ();
EventHandler handler = Changed;
if (handler != null) {
handler (this, new EventArgs ());
}
}
internal void SetValueFromPosition (int x)
{
Value = renderer.RatingFromPosition (event_alloc, x);
}
#region Public Properties
private bool always_show_empty_stars = false;
public bool AlwaysShowEmptyStars {
get { return always_show_empty_stars; }
set { always_show_empty_stars = value; }
}
private bool preview_on_hover = true;
public bool PreviewOnHover {
get { return preview_on_hover; }
set { preview_on_hover = value; }
}
private bool has_frame = true;
public bool HasFrame {
get { return has_frame; }
set { has_frame = value; QueueResize (); }
}
public int Value {
get { return renderer.Value; }
set {
if (renderer.Value != value && renderer.Value >= renderer.MinRating && value <= renderer.MaxRating) {
renderer.Value = value;
OnChanging ();
OnChanged ();
}
}
}
public int MaxRating {
get { return renderer.MaxRating; }
set { renderer.MaxRating = value; }
}
public int MinRating {
get { return renderer.MinRating; }
set { renderer.MinRating = value; }
}
public int RatingLevels {
get { return renderer.RatingLevels; }
}
private object rated_object;
public object RatedObject {
get { return rated_object; }
set { rated_object = value; }
}
#endregion
#region Protected Gtk.Widget Overrides
protected override void OnRealized ()
{
WidgetFlags |= WidgetFlags.Realized | WidgetFlags.NoWindow;
GdkWindow = Parent.GdkWindow;
Gdk.WindowAttr attributes = new Gdk.WindowAttr ();
attributes.WindowType = Gdk.WindowType.Child;
attributes.X = Allocation.X;
attributes.Y = Allocation.Y;
attributes.Width = Allocation.Width;
attributes.Height = Allocation.Height;
attributes.Wclass = Gdk.WindowClass.InputOnly;
attributes.EventMask = (int)(
Gdk.EventMask.PointerMotionMask |
Gdk.EventMask.EnterNotifyMask |
Gdk.EventMask.LeaveNotifyMask |
Gdk.EventMask.KeyPressMask |
Gdk.EventMask.KeyReleaseMask |
Gdk.EventMask.ButtonPressMask |
Gdk.EventMask.ButtonReleaseMask |
Gdk.EventMask.ExposureMask);
Gdk.WindowAttributesType attributes_mask =
Gdk.WindowAttributesType.X |
Gdk.WindowAttributesType.Y |
Gdk.WindowAttributesType.Wmclass;
event_window = new Gdk.Window (GdkWindow, attributes, attributes_mask);
event_window.UserData = Handle;
Style = Gtk.Rc.GetStyleByPaths (Settings, "*.GtkEntry", "*.GtkEntry", GType);
base.OnRealized ();
}
protected override void OnUnrealized ()
{
WidgetFlags &= ~WidgetFlags.Realized;
event_window.UserData = IntPtr.Zero;
Hyena.Gui.GtkWorkarounds.WindowDestroy (event_window);
event_window = null;
base.OnUnrealized ();
}
protected override void OnMapped ()
{
WidgetFlags |= WidgetFlags.Mapped;
event_window.Show ();
}
protected override void OnUnmapped ()
{
WidgetFlags &= ~WidgetFlags.Mapped;
event_window.Hide ();
}
private bool changing_style;
protected override void OnStyleSet (Style previous_style)
{
if (changing_style) {
return;
}
base.OnStyleSet (previous_style);
changing_style = true;
focus_width = (int)StyleGetProperty ("focus-line-width");
interior_focus = (bool)StyleGetProperty ("interior-focus");
changing_style = false;
}
protected override void OnSizeAllocated (Gdk.Rectangle allocation)
{
base.OnSizeAllocated (allocation);
event_alloc = new Gdk.Rectangle (0, 0, allocation.Width, allocation.Height);
if (IsRealized) {
event_window.MoveResize (allocation);
}
}
protected override void OnSizeRequested (ref Gtk.Requisition requisition)
{
EnsureStyle ();
Pango.FontMetrics metrics = PangoContext.GetMetrics (Style.FontDescription, PangoContext.Language);
renderer.Size = ((int)(metrics.Ascent + metrics.Descent) + 512) >> 10; // PANGO_PIXELS(d)
metrics.Dispose ();
if (HasFrame) {
renderer.Xpad = Style.Xthickness + (interior_focus ? focus_width : 0) + 2;
renderer.Ypad = Style.Ythickness + (interior_focus ? focus_width : 0) + 2;
} else {
renderer.Xpad = 0;
renderer.Ypad = 0;
}
requisition.Width = renderer.Width;
requisition.Height = renderer.Height;
}
protected override bool OnExposeEvent (Gdk.EventExpose evnt)
{
if (evnt.Window != GdkWindow) {
return true;
}
if (HasFrame) {
int y_mid = (int)Math.Round ((Allocation.Height - renderer.Height) / 2.0);
Gtk.Style.PaintFlatBox (Style, GdkWindow, State, ShadowType.None, evnt.Area, this, "entry",
Allocation.X, Allocation.Y + y_mid, Allocation.Width, renderer.Height);
Gtk.Style.PaintShadow (Style, GdkWindow, State, ShadowType.In,
evnt.Area, this, "entry", Allocation.X, Allocation.Y + y_mid, Allocation.Width, renderer.Height);
}
Cairo.Context cr = Gdk.CairoHelper.Create (GdkWindow);
renderer.Render (cr, Allocation,
CairoExtensions.GdkColorToCairoColor (HasFrame ? Parent.Style.Text (State) : Parent.Style.Foreground (State)),
AlwaysShowEmptyStars, PreviewOnHover && hover_value >= renderer.MinRating, hover_value,
State == StateType.Insensitive ? 1 : 0.90,
State == StateType.Insensitive ? 1 : 0.55,
State == StateType.Insensitive ? 1 : 0.45);
((IDisposable)cr.Target).Dispose ();
((IDisposable)cr).Dispose ();
return true;
}
protected override bool OnButtonPressEvent (Gdk.EventButton evnt)
{
if (evnt.Button != 1) {
return false;
}
HasFocus = true;
Value = renderer.RatingFromPosition (event_alloc, evnt.X);
return true;
}
protected override bool OnEnterNotifyEvent (Gdk.EventCrossing evnt)
{
hover_value = renderer.MinRating;
QueueDraw ();
return true;
}
protected override bool OnLeaveNotifyEvent (Gdk.EventCrossing crossing)
{
return HandleLeaveNotify (crossing);
}
protected override bool OnMotionNotifyEvent (Gdk.EventMotion motion)
{
return HandleMotionNotify (motion.State, motion.X);
}
protected override bool OnKeyPressEvent (Gdk.EventKey evnt)
{
switch (evnt.Key) {
case Gdk.Key.Up:
case Gdk.Key.Right:
case Gdk.Key.plus:
case Gdk.Key.equal:
Value++;
return true;
case Gdk.Key.Down:
case Gdk.Key.Left:
case Gdk.Key.minus:
Value--;
return true;
}
if (evnt.KeyValue >= (48 + MinRating) && evnt.KeyValue <= (48 + MaxRating) && evnt.KeyValue <= 59) {
Value = (int)evnt.KeyValue - 48;
return true;
}
return false;
}
protected override bool OnScrollEvent (Gdk.EventScroll args)
{
return HandleScroll (args);
}
#endregion
#region Internal API, primarily for RatingMenuItem
internal void ClearHover ()
{
hover_value = renderer.MinRating - 1;
}
internal bool HandleKeyPress (Gdk.EventKey evnt)
{
return this.OnKeyPressEvent (evnt);
}
internal bool HandleScroll (Gdk.EventScroll args)
{
switch (args.Direction) {
case Gdk.ScrollDirection.Up:
case Gdk.ScrollDirection.Right:
Value++;
return true;
case Gdk.ScrollDirection.Down:
case Gdk.ScrollDirection.Left:
Value--;
return true;
}
return false;
}
internal bool HandleMotionNotify (Gdk.ModifierType state, double x)
{
hover_value = renderer.RatingFromPosition (event_alloc, x);
/*if ((state & Gdk.ModifierType.Button1Mask) != 0) {
Value = hover_value;
}*/
QueueDraw ();
return true;
}
internal bool HandleLeaveNotify (Gdk.EventCrossing crossing)
{
ClearHover ();
QueueDraw ();
return true;
}
#endregion
}
#region Test Module
public class RatingAccessible : Atk.Object, Atk.Value, Atk.ValueImplementor
{
private RatingEntry rating;
public RatingAccessible (IntPtr raw) : base (raw)
{
Hyena.Log.Information ("RatingAccessible raw ctor..");
}
public RatingAccessible (GLib.Object widget): base ()
{
rating = widget as RatingEntry;
Name = "Rating entry";
Description = "Rating entry, from 0 to 5 stars";
Role = Atk.Role.Slider;
}
public void GetMaximumValue (ref GLib.Value val)
{
val = new GLib.Value (5);
}
public void GetMinimumIncrement (ref GLib.Value val)
{
val = new GLib.Value (1);
}
public void GetMinimumValue (ref GLib.Value val)
{
val = new GLib.Value (0);
}
public void GetCurrentValue (ref GLib.Value val)
{
val = new GLib.Value (rating.Value);
}
public bool SetCurrentValue (GLib.Value val)
{
int r = (int) val.Val;
if (r <= 0 || r > 5) {
return false;
}
rating.Value = (int) val.Val;
return true;
}
}
#if ENABLE_ATK
internal class RatingAccessibleFactory : Atk.ObjectFactory
{
public static void Init ()
{
new RatingAccessibleFactory ();
Atk.Global.DefaultRegistry.SetFactoryType ((GLib.GType)typeof (RatingEntry), (GLib.GType)typeof (RatingAccessibleFactory));
}
protected override Atk.Object OnCreateAccessible (GLib.Object obj)
{
return new RatingAccessible (obj);
}
protected override GLib.GType OnGetAccessibleType ()
{
return RatingAccessible.GType;
}
}
#endif
[Hyena.Gui.TestModule ("Rating Entry")]
internal class RatingEntryTestModule : Gtk.Window
{
public RatingEntryTestModule () : base ("Rating Entry")
{
VBox pbox = new VBox ();
Add (pbox);
Menu m = new Menu ();
MenuBar b = new MenuBar ();
MenuItem item = new MenuItem ("Rate Me!");
item.Submenu = m;
b.Append (item);
m.Append (new MenuItem ("Apples"));
m.Append (new MenuItem ("Pears"));
m.Append (new RatingMenuItem ());
m.Append (new ImageMenuItem ("gtk-remove", null));
m.ShowAll ();
pbox.PackStart (b, false, false, 0);
VBox box = new VBox ();
box.BorderWidth = 10;
box.Spacing = 10;
pbox.PackStart (box, true, true, 0);
RatingEntry entry1 = new RatingEntry ();
box.PackStart (entry1, true, true, 0);
RatingEntry entry2 = new RatingEntry ();
box.PackStart (entry2, false, false, 0);
box.PackStart (new Entry ("Normal GtkEntry"), false, false, 0);
RatingEntry entry3 = new RatingEntry ();
Pango.FontDescription fd = entry3.PangoContext.FontDescription.Copy ();
fd.Size = (int)(fd.Size * Pango.Scale.XXLarge);
entry3.ModifyFont (fd);
box.PackStart (entry3, true, true, 0);
pbox.ShowAll ();
}
}
#endregion
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// James Driscoll, mailto:[email protected]
//
// 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
[assembly: Elmah.Scc("$Id: AccessErrorLog.cs 923 2011-12-23 22:02:10Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using IDictionary = System.Collections.IDictionary;
using System.Collections.Generic;
#endregion
/// <summary>
/// An <see cref="ErrorLog"/> implementation that uses Microsoft Access
/// as its backing store.
/// </summary>
/// <remarks>
/// The MDB file is automatically created at the path specified in the
/// connection string if it does not already exist.
/// </remarks>
public class AccessErrorLog : ErrorLog
{
private readonly string _connectionString;
private const int _maxAppNameLength = 60;
private const string _scriptResourceName = "mkmdb.vbs";
private static readonly object _mdbInitializationLock = new object();
/// <summary>
/// Initializes a new instance of the <see cref="AccessErrorLog"/> class
/// using a dictionary of configured settings.
/// </summary>
public AccessErrorLog(IDictionary config)
{
if (config == null)
throw new ArgumentNullException("config");
var connectionString = ConnectionStringHelper.GetConnectionString(config);
//
// If there is no connection string to use then throw an
// exception to abort construction.
//
if (connectionString.Length == 0)
throw new ApplicationException("Connection string is missing for the Access error log.");
_connectionString = connectionString;
InitializeDatabase();
//
// Set the application name as this implementation provides
// per-application isolation over a single store.
//
var appName = config.Find("applicationName", string.Empty);
if (appName.Length > _maxAppNameLength)
{
throw new ApplicationException(string.Format(
"Application name is too long. Maximum length allowed is {0} characters.",
_maxAppNameLength.ToString("N0")));
}
ApplicationName = appName;
}
/// <summary>
/// Initializes a new instance of the <see cref="AccessErrorLog"/> class
/// to use a specific connection string for connecting to the database.
/// </summary>
public AccessErrorLog(string connectionString)
{
if (connectionString == null)
throw new ArgumentNullException("connectionString");
if (connectionString.Length == 0)
throw new ArgumentException(null, "connectionString");
_connectionString = connectionString;
}
/// <summary>
/// Gets the name of this error log implementation.
/// </summary>
public override string Name
{
get { return "Microsoft Access Error Log"; }
}
/// <summary>
/// Gets the connection string used by the log to connect to the database.
/// </summary>
public virtual string ConnectionString
{
get { return _connectionString; }
}
/// <summary>
/// Logs an error to the database.
/// </summary>
/// <remarks>
/// Use the stored procedure called by this implementation to set a
/// policy on how long errors are kept in the log. The default
/// implementation stores all errors for an indefinite time.
/// </remarks>
public override string Log(Error error)
{
if (error == null)
throw new ArgumentNullException("error");
var errorXml = ErrorXml.EncodeString(error);
using (var connection = new OleDbConnection(this.ConnectionString))
using (var command = connection.CreateCommand())
{
connection.Open();
command.CommandType = CommandType.Text;
command.CommandText = @"INSERT INTO ELMAH_Error
(Application, Host, Type, Source,
Message, UserName, StatusCode, TimeUtc, AllXml)
VALUES
(@Application, @Host, @Type, @Source,
@Message, @UserName, @StatusCode, @TimeUtc, @AllXml)";
command.CommandType = CommandType.Text;
var parameters = command.Parameters;
parameters.Add("@Application", OleDbType.VarChar, _maxAppNameLength).Value = ApplicationName;
parameters.Add("@Host", OleDbType.VarChar, 30).Value = error.HostName;
parameters.Add("@Type", OleDbType.VarChar, 100).Value = error.Type;
parameters.Add("@Source", OleDbType.VarChar, 60).Value = error.Source;
parameters.Add("@Message", OleDbType.LongVarChar, error.Message.Length).Value = error.Message;
parameters.Add("@User", OleDbType.VarChar, 50).Value = error.User;
parameters.Add("@StatusCode", OleDbType.Integer).Value = error.StatusCode;
parameters.Add("@TimeUtc", OleDbType.Date).Value = error.Time.ToUniversalTime();
parameters.Add("@AllXml", OleDbType.LongVarChar, errorXml.Length).Value = errorXml;
command.ExecuteNonQuery();
using (var identityCommand = connection.CreateCommand())
{
identityCommand.CommandType = CommandType.Text;
identityCommand.CommandText = "SELECT @@IDENTITY";
return Convert.ToString(identityCommand.ExecuteScalar(), CultureInfo.InvariantCulture);
}
}
}
/// <summary>
/// Returns a page of errors from the databse in descending order
/// of logged time.
/// </summary>
public override int GetErrors(int pageIndex, int pageSize, ICollection<ErrorLogEntry> errorEntryList)
{
if (pageIndex < 0)
throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null);
if (pageSize < 0)
throw new ArgumentOutOfRangeException("pageSize", pageSize, null);
using (var connection = new OleDbConnection(this.ConnectionString))
using (var command = connection.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = "SELECT COUNT(*) FROM ELMAH_Error";
connection.Open();
var totalCount = (int)command.ExecuteScalar();
if (errorEntryList != null && pageIndex * pageSize < totalCount)
{
var maxRecords = pageSize * (pageIndex + 1);
if (maxRecords > totalCount)
{
maxRecords = totalCount;
pageSize = totalCount - pageSize * (totalCount / pageSize);
}
var sql = new StringBuilder(1000);
sql.Append("SELECT e.* FROM (");
sql.Append("SELECT TOP ");
sql.Append(pageSize.ToString(CultureInfo.InvariantCulture));
sql.Append(" TimeUtc, ErrorId FROM (");
sql.Append("SELECT TOP ");
sql.Append(maxRecords.ToString(CultureInfo.InvariantCulture));
sql.Append(" TimeUtc, ErrorId FROM ELMAH_Error ");
sql.Append("ORDER BY TimeUtc DESC, ErrorId DESC) ");
sql.Append("ORDER BY TimeUtc ASC, ErrorId ASC) AS i ");
sql.Append("INNER JOIN Elmah_Error AS e ON i.ErrorId = e.ErrorId ");
sql.Append("ORDER BY e.TimeUtc DESC, e.ErrorId DESC");
command.CommandText = sql.ToString();
using (var reader = command.ExecuteReader())
{
Debug.Assert(reader != null);
while (reader.Read())
{
var id = Convert.ToString(reader["ErrorId"], CultureInfo.InvariantCulture);
var error = new Error
{
ApplicationName = reader["Application"].ToString(),
HostName = reader["Host"].ToString(),
Type = reader["Type"].ToString(),
Source = reader["Source"].ToString(),
Message = reader["Message"].ToString(),
User = reader["UserName"].ToString(),
StatusCode = Convert.ToInt32(reader["StatusCode"]),
Time = Convert.ToDateTime(reader["TimeUtc"]).ToLocalTime()
};
errorEntryList.Add(new ErrorLogEntry(this, id, error));
}
reader.Close();
}
}
return totalCount;
}
}
/// <summary>
/// Returns the specified error from the database, or null
/// if it does not exist.
/// </summary>
public override ErrorLogEntry GetError(string id)
{
if (id == null)
throw new ArgumentNullException("id");
if (id.Length == 0)
throw new ArgumentException(null, "id");
int errorId;
try
{
errorId = int.Parse(id, CultureInfo.InvariantCulture);
}
catch (FormatException e)
{
throw new ArgumentException(e.Message, "id", e);
}
catch (OverflowException e)
{
throw new ArgumentException(e.Message, "id", e);
}
string errorXml;
using (var connection = new OleDbConnection(this.ConnectionString))
using (var command = connection.CreateCommand())
{
command.CommandText = @"SELECT AllXml
FROM ELMAH_Error
WHERE ErrorId = @ErrorId";
command.CommandType = CommandType.Text;
var parameters = command.Parameters;
parameters.Add("@ErrorId", OleDbType.Integer).Value = errorId;
connection.Open();
errorXml = (string)command.ExecuteScalar();
}
if (errorXml == null)
return null;
var error = ErrorXml.DecodeString(errorXml);
return new ErrorLogEntry(this, id, error);
}
private void InitializeDatabase()
{
var connectionString = ConnectionString;
Debug.AssertStringNotEmpty(connectionString);
var dbFilePath = ConnectionStringHelper.GetDataSourceFilePath(connectionString);
if (File.Exists(dbFilePath))
return;
//
// Make sure that we don't have multiple instances trying to create the database.
//
lock (_mdbInitializationLock)
{
//
// Just double-check that no other thread has created the database while
// we were waiting for the lock.
//
if (File.Exists(dbFilePath))
return;
//
// Create a temporary copy of the mkmdb.vbs script.
// We do this in the same directory as the resulting database for security permission purposes.
//
var scriptPath = Path.Combine(Path.GetDirectoryName(dbFilePath), _scriptResourceName);
using (var scriptStream = new FileStream(scriptPath, FileMode.Create, FileAccess.Write, FileShare.None))
{
ManifestResourceHelper.WriteResourceToStream(scriptStream, GetType(), _scriptResourceName);
}
//
// Run the script file to create the database using batch
// mode (//B), which suppresses script errors and prompts
// from displaying.
//
var psi = new ProcessStartInfo(
"cscript", "\"" + scriptPath + "\" \"" + dbFilePath + "\" //B //NoLogo");
psi.UseShellExecute = false; // i.e. CreateProcess
psi.CreateNoWindow = true; // Stay lean, stay mean
try
{
using (var process = Process.Start(psi))
{
//
// A few seconds should be plenty of time to create the database.
//
var tolerance = TimeSpan.FromSeconds(2);
if (!process.WaitForExit((int) tolerance.TotalMilliseconds))
{
//
// but it wasn't, so clean up and throw an exception!
// Realistically, I don't expect to ever get here!
//
process.Kill();
throw new Exception(string.Format(
"The Microsoft Access database creation script took longer than the allocated time of {0} seconds to execute. "
+ "The script was terminated prematurely.",
tolerance.TotalSeconds));
}
if (process.ExitCode != 0)
{
throw new Exception(string.Format(
"The Microsoft Access database creation script failed with exit code {0}.",
process.ExitCode));
}
}
}
finally
{
//
// Clean up after ourselves!!
//
File.Delete(scriptPath);
}
}
}
}
}
| |
using Microsoft.Diagnostics.Tracing;
using Microsoft.Diagnostics.Tracing.Analysis.GC;
using Microsoft.Diagnostics.Tracing.Etlx;
using Microsoft.Diagnostics.Tracing.Parsers;
using Microsoft.Diagnostics.Tracing.Parsers.Clr;
using Microsoft.Diagnostics.Tracing.Parsers.ClrPrivate;
using Microsoft.Diagnostics.Tracing.Parsers.Kernel;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Media;
namespace PerfView
{
/// <summary>
/// All managed heap related events
/// </summary>
public enum HeapEvents
{
Unknown,
CPUSample,
ContentionStart,
ContentionStop,
GCAllocationTick,
GCHeapStats,
BGCAllocWaitStart,
BGCAllocWaitStop,
GCOptimized,
GCCreateSegment,
GCFreeSegment,
GCCreateConcurrentThread,
GCTerminateConcurrentThread,
GCDecision,
GCSettings,
GCPerHeapHistory,
GCGlobalHeapHistory,
GCFullNotify,
///
GCFinalizersBegin,
GCFinalizersEnd,
GCSuspendEEBegin,
GCSuspendEEEnd,
GCStart,
GCEnd,
GCRestartEEBegin,
GCRestartEEEnd,
// GarbageCollectionPrivate
GCJoin,
GCMarkStackRoots,
GCMarkFinalizeQueueRoots,
GCMarkHandles,
GCMarkCards,
BGCBegin,
BGC1stNonCondEnd,
BGC1stConEnd,
BGC2ndNonConBegin,
BGC2ndNonConEnd,
BGC2ndConBegin,
BGC2ndConEnd,
BGCPlanEnd,
BGCSweepEnd,
BGCDrainMark,
BGCRevisit,
BGCOverflow,
/// //////////////////////////
FinalizeObject,
CCWRefCountChange,
SetGCHandle,
DestroyGCHandle,
GCEventMax,
GCMarkerFirst = GCFinalizersBegin,
GCMarkerLast = GCMarkCards,
BGCMarkerFirst = BGCBegin,
BGCMarkerLast = BGCOverflow,
}
/// <summary>
/// Per event data
/// </summary>
public struct HeapEventData
{
internal HeapEvents m_event;
internal double m_time;
internal object m_data;
}
/// <summary>
/// Sorting thread by name(type) and then CPU sample
/// </summary>
public class ThreadMemoryInfoComparer : IComparer<ThreadMemoryInfo>
{
public int Compare(ThreadMemoryInfo x, ThreadMemoryInfo y)
{
string n1 = x.Name;
string n2 = y.Name;
if (n1 == null)
{
n1 = String.Empty;
}
if (n2 == null)
{
n2 = String.Empty;
}
int r = n1.CompareTo(n2);
if (r != 0)
{
return -r;
}
else
{
return -x.CpuSample.CompareTo(y.CpuSample);
}
}
}
/// <summary>
/// Per-thread data
/// </summary>
public class ThreadMemoryInfo
{
private ProcessMemoryInfo m_process;
private int m_threadID;
private string m_name;
internal List<HeapEventData> m_events;
internal int[] m_histogram;
internal int m_heapNum = -1; // User by server GC thread
internal bool m_backgroundGc; // User by background GC
private int GetCount(HeapEvents e)
{
return m_histogram[(int)e];
}
public int CLRContentionCount
{
get
{
return Math.Min(GetCount(HeapEvents.ContentionStart), GetCount(HeapEvents.ContentionStop));
}
}
public int ThreadID
{
get
{
return m_threadID;
}
}
public string Name
{
get
{
return m_name;
}
}
public double CpuSample
{
get
{
return GetCount(HeapEvents.CPUSample) * SampleInterval;
}
}
public double CpuSamplePercent
{
get
{
return CpuSample * 100 / m_process.TotalCpuSample;
}
}
public double FirstEvent
{
get
{
return m_events[0].m_time;
}
}
public double LastEvent
{
get
{
return m_events[m_events.Count - 1].m_time;
}
}
public double SampleInterval;
internal ThreadMemoryInfo(ProcessMemoryInfo proc, int threadID)
{
m_process = proc;
m_threadID = threadID;
}
public void AddEvent(HeapEvents evt, double time, object obj = null)
{
switch (evt)
{
case HeapEvents.GCAllocationTick:
if (m_name == null)
{
m_name = ".Net";
}
break;
case HeapEvents.GCFinalizersBegin:
m_name = ".Net Finalizer";
break;
case HeapEvents.BGCBegin:
m_name = ".Net BGC";
break;
case HeapEvents.GCJoin:
if (m_name == null)
{
m_name = ".Net GC";
}
break;
default:
break;
}
if (m_events == null)
{
m_events = new List<HeapEventData>();
m_histogram = new int[(int)HeapEvents.GCEventMax];
}
HeapEventData data = new HeapEventData();
data.m_event = evt;
data.m_time = time;
data.m_data = obj;
m_histogram[(int)evt]++;
m_events.Add(data);
}
}
internal class GcEventExtra
{
internal EventIndex GCStartIndex;
internal TraceThread GCStartThread;
}
/// <summary>
/// Per-process data, extension of GCProcess
/// </summary>
internal partial class ProcessMemoryInfo : HeapDiagramGenerator
{
private const int OneMB = 1024 * 1024;
private const double OneMBD = 1024 * 1024;
protected TraceLog m_traceLog;
protected PerfViewFile m_dataFile;
protected Dictionary<int, ThreadMemoryInfo> m_threadInfo = new Dictionary<int, ThreadMemoryInfo>();
private Dictionary<int, GcEventExtra> m_gcEventExtra = new Dictionary<int, GcEventExtra>();
internal Dictionary<int, ThreadMemoryInfo> Threads
{
get
{
return m_threadInfo;
}
}
internal int ProcessID
{
get
{
return m_procID;
}
}
private StackDecoder m_stackDecoder;
private StatusBar m_statusBar;
public ProcessMemoryInfo(TraceLog traceLog, PerfViewFile dataFile, StatusBar statusBar)
{
m_traceLog = traceLog;
m_dataFile = dataFile;
m_statusBar = statusBar;
m_stackDecoder = new StackDecoder(m_traceLog);
}
private ThreadMemoryInfo GetThread(int threadID)
{
ThreadMemoryInfo ret;
if (!m_threadInfo.TryGetValue(threadID, out ret))
{
ret = new ThreadMemoryInfo(this, threadID);
ret.SampleInterval = m_SampleInterval;
m_threadInfo[threadID] = ret;
}
return ret;
}
private GcEventExtra GetGcEventExtra(int gc, bool create = true)
{
GcEventExtra data;
if (!m_gcEventExtra.TryGetValue(gc, out data) && create)
{
data = new GcEventExtra();
m_gcEventExtra[gc] = data;
}
return data;
}
internal double m_g0Budget;
internal double m_g3Budget;
internal double m_g0Alloc;
internal double m_g3Alloc;
internal bool seenBadAlloc;
internal void OnClrEvent(TraceEvent data)
{
TraceEventID eventID = data.ID;
HeapEvents heapEvent = HeapEvents.Unknown;
// TODO don't use IDs but use individual callbacks.
const TraceEventID GCStartEventID = (TraceEventID)1;
const TraceEventID GCStopEventID = (TraceEventID)2;
const TraceEventID GCRestartEEStopEventID = (TraceEventID)3;
const TraceEventID GCHeapStatsEventID = (TraceEventID)4;
const TraceEventID GCCreateSegmentEventID = (TraceEventID)5;
const TraceEventID GCFreeSegmentEventID = (TraceEventID)6;
const TraceEventID GCRestartEEStartEventID = (TraceEventID)7;
const TraceEventID GCSuspendEEStopEventID = (TraceEventID)8;
const TraceEventID GCSuspendEEStartEventID = (TraceEventID)9;
const TraceEventID GCAllocationTickEventID = (TraceEventID)10;
const TraceEventID GCCreateConcurrentThreadEventID = (TraceEventID)11;
const TraceEventID GCTerminateConcurrentThreadEventID = (TraceEventID)12;
const TraceEventID GCFinalizersStopEventID = (TraceEventID)13;
const TraceEventID GCFinalizersStartEventID = (TraceEventID)14;
const TraceEventID ContentionStartEventID = (TraceEventID)81;
const TraceEventID ContentionStopEventID = (TraceEventID)91;
switch (eventID)
{
case GCStartEventID:
{
var mdata = data as Microsoft.Diagnostics.Tracing.Parsers.Clr.GCStartTraceData;
if (mdata != null)
{
GcEventExtra extra = GetGcEventExtra(mdata.Count);
extra.GCStartIndex = data.EventIndex;
extra.GCStartThread = data.Thread();
}
}
heapEvent = HeapEvents.GCStart;
break;
case GCStopEventID:
heapEvent = HeapEvents.GCEnd;
break;
case GCRestartEEStartEventID:
heapEvent = HeapEvents.GCRestartEEBegin;
break;
case GCRestartEEStopEventID:
heapEvent = HeapEvents.GCRestartEEEnd;
break;
case GCHeapStatsEventID:
heapEvent = HeapEvents.GCHeapStats;
break;
case GCCreateSegmentEventID:
heapEvent = HeapEvents.GCCreateSegment;
break;
case GCFreeSegmentEventID:
heapEvent = HeapEvents.GCFreeSegment;
break;
case GCSuspendEEStartEventID:
heapEvent = HeapEvents.GCSuspendEEBegin;
break;
case GCSuspendEEStopEventID:
heapEvent = HeapEvents.GCSuspendEEEnd;
break;
case GCAllocationTickEventID:
heapEvent = HeapEvents.GCAllocationTick;
{
GCAllocationTickTraceData mdata = data as GCAllocationTickTraceData;
AllocationTick(mdata, mdata.AllocationKind == GCAllocationKind.Large, mdata.GetAllocAmount(ref seenBadAlloc) / OneMBD);
}
break;
case GCCreateConcurrentThreadEventID:
heapEvent = HeapEvents.GCCreateConcurrentThread;
break;
case GCTerminateConcurrentThreadEventID:
heapEvent = HeapEvents.GCTerminateConcurrentThread;
break;
case GCFinalizersStartEventID:
heapEvent = HeapEvents.GCFinalizersBegin;
break;
case GCFinalizersStopEventID:
heapEvent = HeapEvents.GCFinalizersEnd;
break;
case ContentionStartEventID:
heapEvent = HeapEvents.ContentionStart;
break;
case ContentionStopEventID:
heapEvent = HeapEvents.ContentionStop;
break;
default:
break;
}
if (heapEvent != HeapEvents.Unknown)
{
ThreadMemoryInfo thread = GetThread(data.ThreadID);
thread.AddEvent(heapEvent, data.TimeStampRelativeMSec);
}
}
internal void OnClrPrivateEvent(TraceEvent data)
{
TraceEventID eventID = data.ID;
HeapEvents heapEvent = HeapEvents.Unknown;
// TODO don't use IDs but use individual callbacks.
const TraceEventID GCDecisionEventID = (TraceEventID)1;
const TraceEventID GCSettingsEventID = (TraceEventID)2;
const TraceEventID GCOptimizedEventID = (TraceEventID)3;
const TraceEventID GCPerHeapHistoryEventID = (TraceEventID)4;
const TraceEventID GCGlobalHeapHistoryEventID = (TraceEventID)5;
const TraceEventID GCJoinEventID = (TraceEventID)6;
const TraceEventID GCMarkStackRootsEventID = (TraceEventID)7;
const TraceEventID GCMarkFinalizeQueueRootsEventID = (TraceEventID)8;
const TraceEventID GCMarkHandlesEventID = (TraceEventID)9;
const TraceEventID GCMarkCardsEventID = (TraceEventID)10;
const TraceEventID GCBGCStartEventID = (TraceEventID)11;
const TraceEventID GCBGC1stNonCondStopEventID = (TraceEventID)12;
const TraceEventID GCBGC1stConStopEventID = (TraceEventID)13;
const TraceEventID GCBGC2ndNonConStartEventID = (TraceEventID)14;
const TraceEventID GCBGC2ndNonConStopEventID = (TraceEventID)15;
const TraceEventID GCBGC2ndConStartEventID = (TraceEventID)16;
const TraceEventID GCBGC2ndConStopEventID = (TraceEventID)17;
const TraceEventID GCBGCPlanStopEventID = (TraceEventID)18;
const TraceEventID GCBGCSweepStopEventID = (TraceEventID)19;
const TraceEventID GCBGCDrainMarkEventID = (TraceEventID)20;
const TraceEventID GCBGCRevisitEventID = (TraceEventID)21;
const TraceEventID GCBGCOverflowEventID = (TraceEventID)22;
const TraceEventID GCBGCAllocWaitStartEventID = (TraceEventID)23;
const TraceEventID GCBGCAllocWaitStopEventID = (TraceEventID)24;
const TraceEventID GCFullNotifyEventID = (TraceEventID)25;
switch (eventID)
{
case GCDecisionEventID:
heapEvent = HeapEvents.GCDecision;
break;
case GCSettingsEventID:
heapEvent = HeapEvents.GCSettings;
break;
case GCOptimizedEventID:
heapEvent = HeapEvents.GCOptimized;
{
GCOptimizedTraceData mdata = data as GCOptimizedTraceData;
if (mdata.GenerationNumber == 0)
{
m_g0Budget = mdata.DesiredAllocation;
m_g0Alloc = mdata.NewAllocation;
}
else
{
m_g3Budget = mdata.DesiredAllocation;
m_g3Alloc = mdata.NewAllocation;
}
}
break;
case GCPerHeapHistoryEventID:
heapEvent = HeapEvents.GCPerHeapHistory;
break;
case GCGlobalHeapHistoryEventID:
heapEvent = HeapEvents.GCGlobalHeapHistory;
{
GCGlobalHeapHistoryTraceData mdata = data as GCGlobalHeapHistoryTraceData;
m_heapCount = mdata.NumHeaps;
}
break;
case GCJoinEventID:
heapEvent = HeapEvents.GCJoin;
break;
case GCMarkStackRootsEventID:
heapEvent = HeapEvents.GCMarkStackRoots;
break;
case GCMarkFinalizeQueueRootsEventID:
heapEvent = HeapEvents.GCMarkFinalizeQueueRoots;
break;
case GCMarkHandlesEventID:
heapEvent = HeapEvents.GCMarkHandles;
break;
case GCMarkCardsEventID:
heapEvent = HeapEvents.GCMarkCards;
break;
case GCBGCStartEventID:
heapEvent = HeapEvents.BGCBegin;
break;
case GCBGC1stNonCondStopEventID:
heapEvent = HeapEvents.BGC1stNonCondEnd;
break;
case GCBGC1stConStopEventID:
heapEvent = HeapEvents.BGC1stConEnd;
break;
case GCBGC2ndNonConStartEventID:
heapEvent = HeapEvents.BGC2ndNonConBegin;
break;
case GCBGC2ndNonConStopEventID:
heapEvent = HeapEvents.BGC2ndNonConEnd;
break;
case GCBGC2ndConStartEventID:
heapEvent = HeapEvents.BGC2ndConBegin;
break;
case GCBGC2ndConStopEventID:
heapEvent = HeapEvents.BGC2ndConEnd;
break;
case GCBGCPlanStopEventID:
heapEvent = HeapEvents.BGCPlanEnd;
break;
case GCBGCSweepStopEventID:
heapEvent = HeapEvents.BGCSweepEnd;
break;
case GCBGCDrainMarkEventID:
heapEvent = HeapEvents.BGCDrainMark;
break;
case GCBGCRevisitEventID:
heapEvent = HeapEvents.BGCRevisit;
break;
case GCBGCOverflowEventID:
heapEvent = HeapEvents.BGCOverflow;
break;
case GCBGCAllocWaitStartEventID:
heapEvent = HeapEvents.BGCAllocWaitStart;
break;
case GCBGCAllocWaitStopEventID:
heapEvent = HeapEvents.BGCAllocWaitStop;
break;
case GCFullNotifyEventID:
heapEvent = HeapEvents.GCFullNotify;
break;
// FinalizeObject,
// CCWRefCountChange,
// SetGCHandle,
// DestroyGCHandle,
default:
break;
}
if (heapEvent != HeapEvents.Unknown)
{
ThreadMemoryInfo thread = GetThread(data.ThreadID);
thread.AddEvent(heapEvent, data.TimeStampRelativeMSec);
}
}
internal void DumpThreadInfo(HtmlWriter writer)
{
writer.WriteLine("<pre>");
foreach (ThreadMemoryInfo v in m_threadInfo.Values.OrderByDescending(e => e.CpuSample))
{
writer.Write("Thread {0}, {1} samples, {2}", v.ThreadID, v.CpuSample, v.Name);
int count = v.m_events.Count;
if (count != 0)
{
writer.Write(", {0:N3} .. {1:N3} ms", v.m_events[0].m_time, v.m_events[count - 1].m_time);
}
writer.WriteLine();
for (int i = 0; i < v.m_histogram.Length; i++)
{
int val = v.m_histogram[i];
if (val != 0)
{
writer.WriteLine(" {0},{1}", val, (HeapEvents)i);
}
}
}
writer.WriteLine("</pre>");
}
private Microsoft.Diagnostics.Tracing.Analysis.TraceProcess m_process;
private Microsoft.Diagnostics.Tracing.Analysis.TraceLoadedDotNetRuntime m_runtime;
private int m_heapCount;
private double m_SampleInterval;
private TraceEventSource m_source;
internal double TotalCpuSample
{
get
{
return m_process.CPUMSec;
}
}
internal List<TraceGC> GcEvents
{
get
{
if (m_runtime != null)
{
return m_runtime.GC.GCs;
}
else
{
return null;
}
}
}
private int m_procID;
private Guid kernelGuid;
private Dictionary<int /*pid*/, Microsoft.Diagnostics.Tracing.Analysis.TraceProcess> m_processLookup;
/// <summary>
/// Event filtering by process ID. Called in ForwardEventEnumerator::MoveNext
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
private bool FilterEvent(TraceEvent data)
{
if (data.ProcessID == m_procID)
{
if (m_process == null && m_processLookup.ContainsKey(data.ProcessID))
{
m_process = m_processLookup[data.ProcessID];
m_runtime = Microsoft.Diagnostics.Tracing.Analysis.TraceLoadedDotNetRuntimeExtensions.LoadedDotNetRuntime(m_process);
}
if (m_source == null)
{
m_source = data.Source;
FirstEventTime = data.TimeStampRelativeMSec;
}
LastEventTime = data.TimeStampRelativeMSec;
if (data.ProviderGuid == kernelGuid)
{
}
return true;
}
return false;
}
internal bool HasVmAlloc
{
get
{
return m_MaxVMSize > 0;
}
}
// Single entry for 1 mb of commited memory, 256 + byte
// 1 gb = 256 kb memory
// 64 gb = 16 mb memory
private Dictionary<ulong, ModuleClass[]> m_MemMap;
private ulong m_VMSize;
private ulong[] m_ModuleVMSize;
private ulong m_MaxVMSize;
private const int PageSize = 4096;
private List<double> m_VMCurve;
internal void OnVirtualMem(VirtualAllocTraceData data)
{
VirtualAllocTraceData.VirtualAllocFlags flags = data.Flags;
ModuleClass alloc = ModuleClass.Free;
if ((flags & VirtualAllocTraceData.VirtualAllocFlags.MEM_COMMIT) != 0)
{
alloc = ModuleClass.Unknown;
CallStackIndex s = m_stackDecoder.FirstFrame(data.EventIndex);
while (s != CallStackIndex.Invalid)
{
ModuleClass old = alloc;
alloc = m_stackDecoder.GetModuleClass(s);
if ((old == ModuleClass.OSUser) && (alloc != old))
{
break;
}
s = m_stackDecoder.GetCaller(s);
}
}
else if ((flags & (VirtualAllocTraceData.VirtualAllocFlags.MEM_DECOMMIT | VirtualAllocTraceData.VirtualAllocFlags.MEM_RELEASE)) == 0)
{
return;
}
if (m_MemMap == null)
{
m_MemMap = new Dictionary<ulong, ModuleClass[]>();
m_ModuleVMSize = new ulong[(int)(ModuleClass.Max)];
}
Debug.Assert((data.BaseAddr % PageSize) == 0);
Debug.Assert((data.Length % PageSize) == 0);
ulong addr = data.BaseAddr;
// TODO because of the algorithm below, we can't handle very large blocks of memory
// because it is linear in size of the alloc or free. It turns out that sometimes
// we free very large chunks. Thus cap it. This is not accurate but at least we
// complete.
long len = data.Length / PageSize;
if (len > 0x400000) // Cap it at 4M pages = 16GB chunks.
{
len = 0x400000;
}
while (len > 0)
{
ModuleClass[] bit;
ulong region = addr / OneMB;
if (!m_MemMap.TryGetValue(region, out bit))
{
bit = new ModuleClass[OneMB / PageSize];
m_MemMap[region] = bit;
}
int offset = (int)(addr % OneMB) / PageSize;
if (alloc != bit[offset])
{
ModuleClass old = bit[offset];
bit[offset] = alloc;
if (alloc != ModuleClass.Free)
{
if (old == ModuleClass.Free)
{
m_ModuleVMSize[(int)alloc] += PageSize;
m_VMSize += PageSize;
if (m_VMSize > m_MaxVMSize)
{
m_MaxVMSize = m_VMSize;
}
}
}
else
{
m_ModuleVMSize[(int)old] -= PageSize;
m_VMSize -= PageSize;
}
}
addr += PageSize;
len--;
}
if (m_VMCurve == null)
{
m_VMCurve = new List<double>();
}
double clrSize = m_ModuleVMSize[(int)ModuleClass.Clr] / OneMBD;
double graphSize = m_ModuleVMSize[(int)ModuleClass.OSGraphics] / OneMBD;
double win8StoreSize;
if (m_stackDecoder.WwaHost)
{
win8StoreSize = m_ModuleVMSize[(int)ModuleClass.JScript] / OneMBD;
}
else
{
win8StoreSize = m_ModuleVMSize[(int)ModuleClass.Win8Store] / OneMBD;
}
m_VMCurve.Add(data.TimeStampRelativeMSec);
m_VMCurve.Add(clrSize);
m_VMCurve.Add(clrSize + graphSize);
m_VMCurve.Add(clrSize + graphSize + win8StoreSize);
m_VMCurve.Add(m_VMSize / OneMBD);
}
public bool LoadEvents(int procID, int sampleInterval100ns)
{
m_procID = procID;
m_SampleInterval = sampleInterval100ns / 10000.0;
// Filter to process
TraceEvents processEvents = m_traceLog.Events.Filter(FilterEvent);
// Get Dispatcher
TraceEventDispatcher source = processEvents.GetSource();
kernelGuid = KernelTraceEventParser.ProviderGuid;
// Hookup events
source.Clr.All += OnClrEvent;
ClrPrivateTraceEventParser clrPrivate = new ClrPrivateTraceEventParser(source);
clrPrivate.All += OnClrPrivateEvent;
KernelTraceEventParser kernel = source.Kernel;
kernel.PerfInfoSample += delegate (SampledProfileTraceData data)
{
ThreadMemoryInfo thread = GetThread(data.ThreadID);
thread.AddEvent(HeapEvents.CPUSample, data.TimeStampRelativeMSec);
};
kernel.VirtualMemAlloc += OnVirtualMem;
kernel.VirtualMemFree += OnVirtualMem;
m_processLookup = new Dictionary<int, Microsoft.Diagnostics.Tracing.Analysis.TraceProcess>();
// Process all events into GCProcess lookup dictionary
Microsoft.Diagnostics.Tracing.Analysis.TraceLoadedDotNetRuntimeExtensions.NeedLoadedDotNetRuntimes(source);
Microsoft.Diagnostics.Tracing.Analysis.TraceProcessesExtensions.AddCallbackOnProcessStart(source, proc =>
{
Microsoft.Diagnostics.Tracing.Analysis.TraceProcessesExtensions.SetSampleIntervalMSec(proc, sampleInterval100ns);
proc.Log = m_traceLog;
});
source.Process();
foreach (var proc in Microsoft.Diagnostics.Tracing.Analysis.TraceProcessesExtensions.Processes(source))
{
if (Microsoft.Diagnostics.Tracing.Analysis.TraceLoadedDotNetRuntimeExtensions.LoadedDotNetRuntime(proc) != null)
{
m_processLookup.Add(proc.ProcessID, proc);
}
}
// Get the process we want
if (!m_processLookup.ContainsKey(procID))
{
return false;
}
m_process = m_processLookup[procID];
m_runtime = Microsoft.Diagnostics.Tracing.Analysis.TraceLoadedDotNetRuntimeExtensions.LoadedDotNetRuntime(m_process);
return true;
}
public List<Metric> GetMetrics()
{
List<Metric> metrics = new List<Metric>();
string version = m_runtime.RuntimeVersion;
if (!String.IsNullOrEmpty(version))
{
if (version.StartsWith("V ", StringComparison.OrdinalIgnoreCase))
{
version = version.Substring(2);
}
metrics.Add(new Metric("Version", version));
}
metrics.Add(new Metric("Cpu", TotalCpuSample, Toolbox.TimeFormatN0));
metrics.Add(new Metric("GC Cpu", m_runtime.GC.Stats().TotalCpuMSec, Toolbox.TimeFormatN0));
metrics.Add(new Metric("GC %", m_runtime.GC.Stats().TotalCpuMSec * 100.0 / m_process.CPUMSec, Toolbox.PercentageFormat));
metrics.Add(new Metric("GC Pause", m_runtime.GC.Stats().TotalPauseTimeMSec, Toolbox.TimeFormatN0));
metrics.Add(new Metric("Thread #", m_threadInfo.Count));
if (m_process.PeakWorkingSet != 0)
{
metrics.Add(new Metric("Peak VM", m_process.PeakVirtual / 1000000.0, Toolbox.MemoryFormatN0));
}
if (m_process.PeakWorkingSet != 0)
{
metrics.Add(new Metric("Peak WS", m_process.PeakWorkingSet / 1000000.0, Toolbox.MemoryFormatN0));
}
metrics.Add(new Metric("Alloc", m_runtime.GC.Stats().TotalAllocatedMB, Toolbox.MemoryFormatN0));
metrics.Add(new Metric("Max heap", m_runtime.GC.Stats().MaxSizePeakMB, Toolbox.MemoryFormatN0));
metrics.Add(new Metric("Heap #", m_heapCount));
metrics.Add(new Metric("GC", m_runtime.GC.Stats().Count));
metrics.Add(new Metric("Gen0 GC", (m_runtime.GC.Generations()[0] != null) ? m_runtime.GC.Generations()[0].Count : 0));
metrics.Add(new Metric("Gen1 GC", (m_runtime.GC.Generations()[1] != null) ? m_runtime.GC.Generations()[1].Count : 0));
metrics.Add(new Metric("Gen2 GC", (m_runtime.GC.Generations()[2] != null) ? m_runtime.GC.Generations()[2].Count : 0));
metrics.Add(new Metric("FirstEvent", FirstEventTime, Toolbox.TimeFormatN0));
metrics.Add(new Metric("LastEvent", LastEventTime, Toolbox.TimeFormatN0));
if (m_MemMap != null)
{
metrics.Add(new Metric("\u2228 VMCmt", m_MaxVMSize / OneMBD, Toolbox.MemoryFormatN0));
}
return metrics;
}
public DiagramData RenderLegend(int width, int height, int threads)
{
DiagramData data = new DiagramData();
data.dataFile = m_traceLog;
data.events = m_runtime.GC.GCs;
data.procID = m_process.ProcessID;
data.threads = m_threadInfo;
data.allocsites = m_allocSites;
data.drawLegend = true;
data.drawThreadCount = threads;
RenderDiagram(width, height, data);
return data;
}
public DiagramData RenderDiagram(
int width, int height,
double start, double end,
bool gcEvents,
int threadCount,
bool drawMarker,
bool alloctick)
{
DiagramData data = new DiagramData();
data.dataFile = m_traceLog;
data.events = m_runtime.GC.GCs;
data.procID = m_process.ProcessID;
data.threads = m_threadInfo;
data.allocsites = m_allocSites;
data.vmCurve = m_VMCurve;
data.vmMaxVM = m_MaxVMSize / OneMBD;
data.wwaHost = m_stackDecoder.WwaHost;
data.startTime = start;
data.endTime = end;
data.drawGCEvents = gcEvents;
data.drawThreadCount = threadCount;
data.drawMarker = drawMarker;
data.drawAllocTicks = alloctick;
RenderDiagram(width, height, data);
return data;
}
public void SaveDiagram(string fileName, bool xps)
{
fileName = Path.ChangeExtension(fileName, null).Replace(" ", "") + "_" + m_process.ProcessID;
if (xps)
{
fileName = Toolbox.GetSaveFileName(fileName, ".xps", "XPS");
}
else
{
fileName = Toolbox.GetSaveFileName(fileName, ".png", "PNG");
}
if (fileName != null)
{
int width = 1280;
int height = 720;
DiagramData data = RenderDiagram(width, height, FirstEventTime, LastEventTime, true, 100, true, true);
if (xps)
{
Toolbox.SaveAsXps(data.visual, width, height, fileName);
}
else
{
Toolbox.SaveAsPng(data.visual, width, height, fileName);
}
}
}
internal double FirstEventTime = -1;
internal double LastEventTime = 0;
#region Allocation Tick
// AllocTickKey -> int
private Dictionary<AllocTick, int> m_typeMap = new Dictionary<AllocTick, int>(new AllocTickComparer());
// int -> AllocTickKey
internal List<AllocTick> m_allocSites = new List<AllocTick>();
private bool m_hasBadAllocTick;
private void AddAlloc(AllocTick key, bool large, double val)
{
int id;
if (!m_typeMap.TryGetValue(key, out id))
{
id = m_typeMap.Count;
m_allocSites.Add(key);
m_typeMap[key] = id;
}
if (val < 0)
{
m_hasBadAllocTick = true;
}
if (m_hasBadAllocTick)
{
// Clap this between 90K and 110K (for small objs) and 90K to 2Meg (for large obects).
val = Math.Max(val, .090);
val = Math.Min(val, large ? 2 : .11);
}
m_allocSites[id].Add(large, val);
}
public void AllocationTick(GCAllocationTickTraceData data, bool large, double value)
{
AllocTick key = new AllocTick();
// May not have type name prior to 4.5
if (!String.IsNullOrEmpty(data.TypeName))
{
key.m_type = data.TypeName;
}
TraceCallStack stack = data.CallStack();
// Walk the call stack to find module above clr
while ((stack != null) && (stack.Caller != null) && stack.CodeAddress.ModuleName.IsClr())
{
stack = stack.Caller;
}
if (stack != null)
{
key.m_caller1 = stack.CodeAddress.CodeAddressIndex;
stack = stack.Caller;
// Walk call stack to find module above mscorlib
while ((stack != null) && (stack.Caller != null) && stack.CodeAddress.ModuleName.IsMscorlib())
{
stack = stack.Caller;
}
if (stack != null)
{
key.m_caller2 = stack.CodeAddress.CodeAddressIndex;
}
}
AddAlloc(key, large, value);
}
#endregion
}
/// <summary>
/// Data passed to HeapDiagram
/// </summary>
internal class DiagramData
{
internal TraceLog dataFile;
internal int procID;
internal List<TraceGC> events;
internal Dictionary<int, ThreadMemoryInfo> threads;
internal List<AllocTick> allocsites;
internal List<double> vmCurve;
internal double vmMaxVM;
internal bool wwaHost;
internal double startTime;
internal double endTime;
internal bool drawGCEvents;
internal int drawThreadCount;
internal bool drawAllocTicks;
internal bool drawLegend;
internal bool drawMarker;
internal double x0;
internal double x1;
internal double t0;
internal double t1;
internal Visual visual;
}
}
| |
using System.Globalization;
using System.Threading.Tasks;
using Abp.Application.Features;
using Abp.Authorization;
using Abp.Configuration;
using Abp.Dependency;
using Abp.Domain.Uow;
using Abp.Events.Bus;
using Abp.Localization;
using Abp.Localization.Sources;
using Abp.ObjectMapping;
using Abp.Runtime.Session;
using Abp.Web.Mvc.Alerts;
using Castle.Core.Logging;
using Microsoft.AspNetCore.Mvc;
namespace Abp.AspNetCore.Mvc.Controllers
{
/// <summary>
/// Base class for all MVC Controllers in Abp system.
/// </summary>
public abstract class AbpController : Controller, ITransientDependency
{
/// <summary>
/// Gets current session information.
/// </summary>
public IAbpSession AbpSession { get; set; }
/// <summary>
/// Gets the event bus.
/// </summary>
public IEventBus EventBus { get; set; }
/// <summary>
/// Reference to the permission manager.
/// </summary>
public IPermissionManager PermissionManager { get; set; }
/// <summary>
/// Reference to the setting manager.
/// </summary>
public ISettingManager SettingManager { get; set; }
/// <summary>
/// Reference to the permission checker.
/// </summary>
public IPermissionChecker PermissionChecker { protected get; set; }
/// <summary>
/// Reference to the feature manager.
/// </summary>
public IFeatureManager FeatureManager { protected get; set; }
/// <summary>
/// Reference to the permission checker.
/// </summary>
public IFeatureChecker FeatureChecker { protected get; set; }
/// <summary>
/// Reference to the object to object mapper.
/// </summary>
public IObjectMapper ObjectMapper { get; set; }
/// <summary>
/// Reference to the localization manager.
/// </summary>
public ILocalizationManager LocalizationManager { protected get; set; }
/// <summary>
/// Gets/sets name of the localization source that is used in this application service.
/// It must be set in order to use <see cref="L(string)"/> and <see cref="L(string,CultureInfo)"/> methods.
/// </summary>
protected string LocalizationSourceName { get; set; }
/// <summary>
/// Gets localization source.
/// It's valid if <see cref="LocalizationSourceName"/> is set.
/// </summary>
protected ILocalizationSource LocalizationSource
{
get
{
if (LocalizationSourceName == null)
{
throw new AbpException("Must set LocalizationSourceName before, in order to get LocalizationSource");
}
if (_localizationSource == null || _localizationSource.Name != LocalizationSourceName)
{
_localizationSource = LocalizationManager.GetSource(LocalizationSourceName);
}
return _localizationSource;
}
}
private ILocalizationSource _localizationSource;
/// <summary>
/// Reference to the logger to write logs.
/// </summary>
public ILogger Logger { get; set; }
/// <summary>
/// Reference to <see cref="IUnitOfWorkManager"/>.
/// </summary>
public IUnitOfWorkManager UnitOfWorkManager
{
get
{
if (_unitOfWorkManager == null)
{
throw new AbpException("Must set UnitOfWorkManager before use it.");
}
return _unitOfWorkManager;
}
set { _unitOfWorkManager = value; }
}
public IAlertManager AlertManager { get; set; }
public AlertList Alerts => AlertManager.Alerts;
private IUnitOfWorkManager _unitOfWorkManager;
/// <summary>
/// Gets current unit of work.
/// </summary>
protected IActiveUnitOfWork CurrentUnitOfWork { get { return UnitOfWorkManager.Current; } }
/// <summary>
/// Constructor.
/// </summary>
protected AbpController()
{
AbpSession = NullAbpSession.Instance;
Logger = NullLogger.Instance;
LocalizationManager = NullLocalizationManager.Instance;
PermissionChecker = NullPermissionChecker.Instance;
EventBus = NullEventBus.Instance;
ObjectMapper = NullObjectMapper.Instance;
}
/// <summary>
/// Gets localized string for given key name and current language.
/// </summary>
/// <param name="name">Key name</param>
/// <returns>Localized string</returns>
protected virtual string L(string name)
{
return LocalizationSource.GetString(name);
}
/// <summary>
/// Gets localized string for given key name and current language with formatting strings.
/// </summary>
/// <param name="name">Key name</param>
/// <param name="args">Format arguments</param>
/// <returns>Localized string</returns>
protected virtual string L(string name, params object[] args)
{
return LocalizationSource.GetString(name, args);
}
/// <summary>
/// Gets localized string for given key name and specified culture information.
/// </summary>
/// <param name="name">Key name</param>
/// <param name="culture">culture information</param>
/// <returns>Localized string</returns>
protected virtual string L(string name, CultureInfo culture)
{
return LocalizationSource.GetString(name, culture);
}
/// <summary>
/// Gets localized string for given key name and current language with formatting strings.
/// </summary>
/// <param name="name">Key name</param>
/// <param name="culture">culture information</param>
/// <param name="args">Format arguments</param>
/// <returns>Localized string</returns>
protected virtual string L(string name, CultureInfo culture, params object[] args)
{
return LocalizationSource.GetString(name, culture, args);
}
/// <summary>
/// Checks if current user is granted for a permission.
/// </summary>
/// <param name="permissionName">Name of the permission</param>
protected Task<bool> IsGrantedAsync(string permissionName)
{
return PermissionChecker.IsGrantedAsync(permissionName);
}
/// <summary>
/// Checks if current user is granted for a permission.
/// </summary>
/// <param name="permissionName">Name of the permission</param>
protected bool IsGranted(string permissionName)
{
return PermissionChecker.IsGranted(permissionName);
}
/// <summary>
/// Checks if given feature is enabled for current tenant.
/// </summary>
/// <param name="featureName">Name of the feature</param>
/// <returns></returns>
protected virtual Task<bool> IsEnabledAsync(string featureName)
{
return FeatureChecker.IsEnabledAsync(featureName);
}
/// <summary>
/// Checks if given feature is enabled for current tenant.
/// </summary>
/// <param name="featureName">Name of the feature</param>
/// <returns></returns>
protected virtual bool IsEnabled(string featureName)
{
return FeatureChecker.IsEnabled(featureName);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using NetGore.IO;
namespace NetGore.AI
{
/// <summary>
/// Represents the ID for an AI module.
/// </summary>
[Serializable]
[TypeConverter(typeof(AIIDTypeConverter))]
public struct AIID : IComparable<AIID>, IConvertible, IFormattable, IComparable<int>, IEquatable<int>
{
/// <summary>
/// Represents the largest possible value of AIID. This field is constant.
/// </summary>
public const int MaxValue = ushort.MaxValue;
/// <summary>
/// Represents the smallest possible value of AIID. This field is constant.
/// </summary>
public const int MinValue = ushort.MinValue;
/// <summary>
/// The underlying value. This contains the actual value of the struct instance.
/// </summary>
readonly ushort _value;
/// <summary>
/// Initializes a new instance of the <see cref="AIID"/> struct.
/// </summary>
/// <param name="value">Value to assign to the new AIID.</param>
/// <exception cref="ArgumentOutOfRangeException"><c>value</c> is out of range.</exception>
public AIID(int value)
{
if (value < MinValue || value > MaxValue)
throw new ArgumentOutOfRangeException("value");
_value = (ushort)value;
}
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="other">Another object to compare to.</param>
/// <returns>
/// True if <paramref name="other"/> and this instance are the same type and represent the same value; otherwise, false.
/// </returns>
public bool Equals(AIID other)
{
return other._value == _value;
}
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="obj">Another object to compare to.</param>
/// <returns>
/// True if <paramref name="obj"/> and this instance are the same type and represent the same value; otherwise, false.
/// </returns>
public override bool Equals(object obj)
{
return obj is AIID && this == (AIID)obj;
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>
/// A 32-bit signed integer that is the hash code for this instance.
/// </returns>
public override int GetHashCode()
{
return _value.GetHashCode();
}
/// <summary>
/// Gets the raw internal value of this AIID.
/// </summary>
/// <returns>The raw internal value.</returns>
public ushort GetRawValue()
{
return _value;
}
/// <summary>
/// Reads an AIID from an IValueReader.
/// </summary>
/// <param name="reader">IValueReader to read from.</param>
/// <param name="name">Unique name of the value to read.</param>
/// <returns>The AIID read from the IValueReader.</returns>
public static AIID Read(IValueReader reader, string name)
{
var value = reader.ReadUShort(name);
return new AIID(value);
}
/// <summary>
/// Reads an AIID from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="reader"><see cref="IDataRecord"/> to get the value from.</param>
/// <param name="i">The index of the field to find.</param>
/// <returns>The AIID read from the <see cref="IDataRecord"/>.</returns>
public static AIID Read(IDataRecord reader, int i)
{
var value = reader.GetValue(i);
if (value is ushort)
return new AIID((ushort)value);
var convertedValue = Convert.ToUInt16(value);
return new AIID(convertedValue);
}
/// <summary>
/// Reads an AIID from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="reader"><see cref="IDataRecord"/> to get the value from.</param>
/// <param name="name">The name of the field to find.</param>
/// <returns>The AIID read from the <see cref="IDataRecord"/>.</returns>
public static AIID Read(IDataRecord reader, string name)
{
return Read(reader, reader.GetOrdinal(name));
}
/// <summary>
/// Reads an AIID from an IValueReader.
/// </summary>
/// <param name="bitStream">BitStream to read from.</param>
/// <returns>The AIID read from the BitStream.</returns>
public static AIID Read(BitStream bitStream)
{
var value = bitStream.ReadUShort();
return new AIID(value);
}
/// <summary>
/// Converts the numeric value of this instance to its equivalent string representation.
/// </summary>
/// <returns>The string representation of the value of this instance, consisting of a sequence
/// of digits ranging from 0 to 9, without leading zeroes.</returns>
public override string ToString()
{
return _value.ToString();
}
/// <summary>
/// Writes the AIID to an IValueWriter.
/// </summary>
/// <param name="writer">IValueWriter to write to.</param>
/// <param name="name">Unique name of the AIID that will be used to distinguish it
/// from other values when reading.</param>
public void Write(IValueWriter writer, string name)
{
writer.Write(name, _value);
}
/// <summary>
/// Writes the AIID to an IValueWriter.
/// </summary>
/// <param name="bitStream">BitStream to write to.</param>
public void Write(BitStream bitStream)
{
bitStream.Write(_value);
}
#region IComparable<AIID> Members
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared.
/// The return value has the following meanings:
/// Value
/// Meaning
/// Less than zero
/// This object is less than the <paramref name="other"/> parameter.
/// Zero
/// This object is equal to <paramref name="other"/>.
/// Greater than zero
/// This object is greater than <paramref name="other"/>.
/// </returns>
public int CompareTo(AIID other)
{
return _value.CompareTo(other._value);
}
#endregion
#region IComparable<int> Members
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings:
/// Value
/// Meaning
/// Less than zero
/// This object is less than the <paramref name="other"/> parameter.
/// Zero
/// This object is equal to <paramref name="other"/>.
/// Greater than zero
/// This object is greater than <paramref name="other"/>.
/// </returns>
public int CompareTo(int other)
{
return _value.CompareTo(other);
}
#endregion
#region IConvertible Members
/// <summary>
/// Returns the <see cref="T:System.TypeCode"/> for this instance.
/// </summary>
/// <returns>
/// The enumerated constant that is the <see cref="T:System.TypeCode"/> of the class or value type that implements this interface.
/// </returns>
public TypeCode GetTypeCode()
{
return _value.GetTypeCode();
}
/// <summary>
/// Converts the value of this instance to an equivalent Boolean value using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation
/// that supplies culture-specific formatting information.</param>
/// <returns>
/// A Boolean value equivalent to the value of this instance.
/// </returns>
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return ((IConvertible)_value).ToBoolean(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 8-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 8-bit unsigned integer equivalent to the value of this instance.
/// </returns>
byte IConvertible.ToByte(IFormatProvider provider)
{
return ((IConvertible)_value).ToByte(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent Unicode character using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A Unicode character equivalent to the value of this instance.
/// </returns>
char IConvertible.ToChar(IFormatProvider provider)
{
return ((IConvertible)_value).ToChar(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent <see cref="T:System.DateTime"/> using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A <see cref="T:System.DateTime"/> instance equivalent to the value of this instance.
/// </returns>
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
return ((IConvertible)_value).ToDateTime(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent <see cref="T:System.Decimal"/> number using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information. </param>
/// <returns>
/// A <see cref="T:System.Decimal"/> number equivalent to the value of this instance.
/// </returns>
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return ((IConvertible)_value).ToDecimal(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent double-precision floating-point number using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A double-precision floating-point number equivalent to the value of this instance.
/// </returns>
double IConvertible.ToDouble(IFormatProvider provider)
{
return ((IConvertible)_value).ToDouble(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 16-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 16-bit signed integer equivalent to the value of this instance.
/// </returns>
short IConvertible.ToInt16(IFormatProvider provider)
{
return ((IConvertible)_value).ToInt16(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 32-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 32-bit signed integer equivalent to the value of this instance.
/// </returns>
int IConvertible.ToInt32(IFormatProvider provider)
{
return ((IConvertible)_value).ToInt32(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 64-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 64-bit signed integer equivalent to the value of this instance.
/// </returns>
long IConvertible.ToInt64(IFormatProvider provider)
{
return ((IConvertible)_value).ToInt64(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 8-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 8-bit signed integer equivalent to the value of this instance.
/// </returns>
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return ((IConvertible)_value).ToSByte(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent single-precision floating-point number using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information. </param>
/// <returns>
/// A single-precision floating-point number equivalent to the value of this instance.
/// </returns>
float IConvertible.ToSingle(IFormatProvider provider)
{
return ((IConvertible)_value).ToSingle(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent <see cref="T:System.String"/> using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A <see cref="T:System.String"/> instance equivalent to the value of this instance.
/// </returns>
public string ToString(IFormatProvider provider)
{
return ((IConvertible)_value).ToString(provider);
}
/// <summary>
/// Converts the value of this instance to an <see cref="T:System.Object"/> of the specified <see cref="T:System.Type"/> that has an equivalent value, using the specified culture-specific formatting information.
/// </summary>
/// <param name="conversionType">The <see cref="T:System.Type"/> to which the value of this instance is converted.</param>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An <see cref="T:System.Object"/> instance of type <paramref name="conversionType"/> whose value is equivalent to the value of this instance.
/// </returns>
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
return ((IConvertible)_value).ToType(conversionType, provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 16-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 16-bit unsigned integer equivalent to the value of this instance.
/// </returns>
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return ((IConvertible)_value).ToUInt16(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 32-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 32-bit unsigned integer equivalent to the value of this instance.
/// </returns>
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return ((IConvertible)_value).ToUInt32(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 64-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 64-bit unsigned integer equivalent to the value of this instance.
/// </returns>
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return ((IConvertible)_value).ToUInt64(provider);
}
#endregion
#region IEquatable<int> Members
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
public bool Equals(int other)
{
return _value.Equals(other);
}
#endregion
#region IFormattable Members
/// <summary>
/// Formats the value of the current instance using the specified format.
/// </summary>
/// <param name="format">The <see cref="T:System.String"/> specifying the format to use.
/// -or-
/// null to use the default format defined for the type of the <see cref="T:System.IFormattable"/> implementation.
/// </param>
/// <param name="formatProvider">The <see cref="T:System.IFormatProvider"/> to use to format the value.
/// -or-
/// null to obtain the numeric format information from the current locale setting of the operating system.
/// </param>
/// <returns>
/// A <see cref="T:System.String"/> containing the value of the current instance in the specified format.
/// </returns>
public string ToString(string format, IFormatProvider formatProvider)
{
return _value.ToString(format, formatProvider);
}
#endregion
/// <summary>
/// Implements operator ++.
/// </summary>
/// <param name="l">The AIID to increment.</param>
/// <returns>The incremented AIID.</returns>
public static AIID operator ++(AIID l)
{
return new AIID(l._value + 1);
}
/// <summary>
/// Implements operator --.
/// </summary>
/// <param name="l">The AIID to decrement.</param>
/// <returns>The decremented AIID.</returns>
public static AIID operator --(AIID l)
{
return new AIID(l._value - 1);
}
/// <summary>
/// Implements operator +.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>Result of the left side plus the right side.</returns>
public static AIID operator +(AIID left, AIID right)
{
return new AIID(left._value + right._value);
}
/// <summary>
/// Implements operator -.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>Result of the left side minus the right side.</returns>
public static AIID operator -(AIID left, AIID right)
{
return new AIID(left._value - right._value);
}
/// <summary>
/// Implements operator ==.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are equal.</returns>
public static bool operator ==(AIID left, int right)
{
return left._value == right;
}
/// <summary>
/// Implements operator !=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are not equal.</returns>
public static bool operator !=(AIID left, int right)
{
return left._value != right;
}
/// <summary>
/// Implements operator ==.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are equal.</returns>
public static bool operator ==(int left, AIID right)
{
return left == right._value;
}
/// <summary>
/// Implements operator !=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are not equal.</returns>
public static bool operator !=(int left, AIID right)
{
return left != right._value;
}
/// <summary>
/// Casts a AIID to an Int32.
/// </summary>
/// <param name="AIID">AIID to cast.</param>
/// <returns>The Int32.</returns>
public static explicit operator int(AIID AIID)
{
return AIID._value;
}
/// <summary>
/// Casts an Int32 to a AIID.
/// </summary>
/// <param name="value">Int32 to cast.</param>
/// <returns>The AIID.</returns>
public static explicit operator AIID(int value)
{
return new AIID(value);
}
/// <summary>
/// Implements the operator >.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than the right.</returns>
public static bool operator >(int left, AIID right)
{
return left > right._value;
}
/// <summary>
/// Implements the operator <.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than the left.</returns>
public static bool operator <(int left, AIID right)
{
return left < right._value;
}
/// <summary>
/// Implements the operator >.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than the right.</returns>
public static bool operator >(AIID left, AIID right)
{
return left._value > right._value;
}
/// <summary>
/// Implements the operator <.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than the left.</returns>
public static bool operator <(AIID left, AIID right)
{
return left._value < right._value;
}
/// <summary>
/// Implements the operator >.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than the right.</returns>
public static bool operator >(AIID left, int right)
{
return left._value > right;
}
/// <summary>
/// Implements the operator <.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than the left.</returns>
public static bool operator <(AIID left, int right)
{
return left._value < right;
}
/// <summary>
/// Implements the operator >=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than or equal to the right.</returns>
public static bool operator >=(int left, AIID right)
{
return left >= right._value;
}
/// <summary>
/// Implements the operator <=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than or equal to the left.</returns>
public static bool operator <=(int left, AIID right)
{
return left <= right._value;
}
/// <summary>
/// Implements the operator >=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than or equal to the right.</returns>
public static bool operator >=(AIID left, int right)
{
return left._value >= right;
}
/// <summary>
/// Implements the operator <=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than or equal to the left.</returns>
public static bool operator <=(AIID left, int right)
{
return left._value <= right;
}
/// <summary>
/// Implements the operator >=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than or equal to the right.</returns>
public static bool operator >=(AIID left, AIID right)
{
return left._value >= right._value;
}
/// <summary>
/// Implements the operator <=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than or equal to the left.</returns>
public static bool operator <=(AIID left, AIID right)
{
return left._value <= right._value;
}
/// <summary>
/// Implements operator !=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are not equal.</returns>
public static bool operator !=(AIID left, AIID right)
{
return left._value != right._value;
}
/// <summary>
/// Implements operator ==.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are equal.</returns>
public static bool operator ==(AIID left, AIID right)
{
return left._value == right._value;
}
}
/// <summary>
/// Adds extensions to some data I/O objects for performing Read and Write operations for the AIID.
/// All of the operations are implemented in the AIID struct. These extensions are provided
/// purely for the convenience of accessing all the I/O operations from the same place.
/// </summary>
public static class AIIDReadWriteExtensions
{
/// <summary>
/// Gets the value in the <paramref name="dict"/> entry at the given <paramref name="key"/> as type AIID.
/// </summary>
/// <typeparam name="T">The key Type.</typeparam>
/// <param name="dict">The IDictionary.</param>
/// <param name="key">The key for the value to get.</param>
/// <returns>The value at the given <paramref name="key"/> parsed as a AIID.</returns>
public static AIID AsAIID<T>(this IDictionary<T, string> dict, T key)
{
return Parser.Invariant.ParseAIID(dict[key]);
}
/// <summary>
/// Tries to get the value in the <paramref name="dict"/> entry at the given <paramref name="key"/> as type AIID.
/// </summary>
/// <typeparam name="T">The key Type.</typeparam>
/// <param name="dict">The IDictionary.</param>
/// <param name="key">The key for the value to get.</param>
/// <param name="defaultValue">The value to use if the value at the <paramref name="key"/> could not be parsed.</param>
/// <returns>The value at the given <paramref name="key"/> parsed as an int, or the
/// <paramref name="defaultValue"/> if the <paramref name="key"/> did not exist in the <paramref name="dict"/>
/// or the value at the given <paramref name="key"/> could not be parsed.</returns>
public static AIID AsAIID<T>(this IDictionary<T, string> dict, T key, AIID defaultValue)
{
string value;
if (!dict.TryGetValue(key, out value))
return defaultValue;
AIID parsed;
if (!Parser.Invariant.TryParse(value, out parsed))
return defaultValue;
return parsed;
}
/// <summary>
/// Reads the AIID from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="r"><see cref="IDataRecord"/> to read the AIID from.</param>
/// <param name="i">The field index to read.</param>
/// <returns>The AIID read from the <see cref="IDataRecord"/>.</returns>
public static AIID GetAIID(this IDataRecord r, int i)
{
return AIID.Read(r, i);
}
/// <summary>
/// Reads the AIID from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="r"><see cref="IDataRecord"/> to read the AIID from.</param>
/// <param name="name">The name of the field to read the value from.</param>
/// <returns>The AIID read from the <see cref="IDataRecord"/>.</returns>
public static AIID GetAIID(this IDataRecord r, string name)
{
return AIID.Read(r, name);
}
/// <summary>
/// Parses the AIID from a string.
/// </summary>
/// <param name="parser">The Parser to use.</param>
/// <param name="value">The string to parse.</param>
/// <returns>The AIID parsed from the string.</returns>
public static AIID ParseAIID(this Parser parser, string value)
{
return new AIID(parser.ParseUShort(value));
}
/// <summary>
/// Reads the AIID from a BitStream.
/// </summary>
/// <param name="bitStream">BitStream to read the AIID from.</param>
/// <returns>The AIID read from the BitStream.</returns>
public static AIID ReadAIID(this BitStream bitStream)
{
return AIID.Read(bitStream);
}
/// <summary>
/// Reads the AIID from an IValueReader.
/// </summary>
/// <param name="valueReader">IValueReader to read the AIID from.</param>
/// <param name="name">The unique name of the value to read.</param>
/// <returns>The AIID read from the IValueReader.</returns>
public static AIID ReadAIID(this IValueReader valueReader, string name)
{
return AIID.Read(valueReader, name);
}
/// <summary>
/// Tries to parse the AIID from a string.
/// </summary>
/// <param name="parser">The Parser to use.</param>
/// <param name="value">The string to parse.</param>
/// <param name="outValue">If this method returns true, contains the parsed AIID.</param>
/// <returns>True if the parsing was successfully; otherwise false.</returns>
public static bool TryParse(this Parser parser, string value, out AIID outValue)
{
ushort tmp;
var ret = parser.TryParse(value, out tmp);
outValue = new AIID(tmp);
return ret;
}
/// <summary>
/// Writes a AIID to a BitStream.
/// </summary>
/// <param name="bitStream">BitStream to write to.</param>
/// <param name="value">AIID to write.</param>
public static void Write(this BitStream bitStream, AIID value)
{
value.Write(bitStream);
}
/// <summary>
/// Writes a AIID to a IValueWriter.
/// </summary>
/// <param name="valueWriter">IValueWriter to write to.</param>
/// <param name="name">Unique name of the AIID that will be used to distinguish it
/// from other values when reading.</param>
/// <param name="value">AIID to write.</param>
public static void Write(this IValueWriter valueWriter, string name, AIID value)
{
value.Write(valueWriter, name);
}
}
}
| |
#region Copyright
/*Copyright (C) 2015 Konstantin Udilovich
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Reflection;
using Dynamo.Controls;
using Dynamo.Models;
using Dynamo.Wpf;
using Kodestruct.Dynamo.Common;
using System.Xml;
using System.Windows;
using Kodestruct.Dynamo.Common.Infra;
using System.Collections.ObjectModel;
using System.Windows.Resources;
using System.IO;
using System.Linq;
using Dynamo.Nodes;
using Dynamo.Graph;
using Dynamo.Graph.Nodes;
namespace Kodestruct.Wood.NDS.General
{
/// <summary>
///Selection of species, commercial grade and size class for determining NDS reference values
/// </summary>
[NodeName("Wood species and grade")]
[NodeCategory("Kodestruct.Wood.NDS.General")]
[NodeDescription("Wood species and grade")]
[IsDesignScriptCompatible]
public class WoodSpeciesAndGradeSelection : UiNodeBase
{
public WoodSpeciesAndGradeSelection()
{
//OutPortData.Add(new PortData("ReportEntry", "Calculation log entries (for reporting)"));
OutPortData.Add(new PortData("WoodSpeciesId", "Wood species for reference value selection"));
OutPortData.Add(new PortData("CommercialGradeId", "Wood commercial grade"));
OutPortData.Add(new PortData("SizeClassId", "Wood species size classification for reference value selection"));
OutPortData.Add(new PortData("WoodMemberType", "Wood member type"));
RegisterAllPorts();
this.WoodMemberType = "SawnDimensionLumber"; //initial member type assignment to get species list
SetDefaultParams();
//PropertyChanged += NodePropertyChanged;
}
private void PopulateSpeciesList()
{
if (WoodMemberType == "SawnDimensionLumber")
{
AvailableWoodSpecies = FetchSpeciesList(ResourceFileName);
}
else
{
ClearAllAvailableData();
}
}
/// <summary>
/// Gets the type of this class, to be used in base class for reflection
/// </summary>
protected override Type GetModelType()
{
return GetType();
}
#region properties
#region OutputProperties
#region WoodSpeciesIdProperty
/// <summary>
/// WoodSpeciesId property
/// </summary>
/// <value>Section name from steel shape database</value>
public string _WoodSpeciesId;
public string WoodSpeciesId
{
get { return _WoodSpeciesId; }
set
{
if (value!=null)
{
_WoodSpeciesId = value;
RaisePropertyChanged("WoodSpeciesId");
UpdateViewForSelectedSpecies();
OnNodeModified(true);
}
}
}
#endregion
#region CommercialGradeIdProperty
/// <summary>
/// CommercialGradeId property
/// </summary>
/// <value>Section name from steel shape database</value>
public string _CommercialGradeId;
public string CommercialGradeId
{
get { return _CommercialGradeId; }
set
{
if (value != null)
{
_CommercialGradeId = value;
RaisePropertyChanged("CommercialGradeId");
UpdateViewForSelectedGrade();
OnNodeModified(true);
}
}
}
#endregion
#region SizeClassIdProperty
/// <summary>
/// SizeClassId property
/// </summary>
/// <value>Section name from steel shape database</value>
public string _SizeClassId;
public string SizeClassId
{
get { return _SizeClassId; }
set
{
if (value != null)
{
_SizeClassId = value;
RaisePropertyChanged("SizeClassId");
OnNodeModified(true);
}
}
}
#endregion
#region WoodMemberTypeProperty
/// <summary>
/// WoodMemberType property
/// </summary>
/// <value>Section name from steel shape database</value>
public string _WoodMemberType;
public string WoodMemberType
{
get { return _WoodMemberType; }
set
{
if (value != null)
{
_WoodMemberType = value;
RaisePropertyChanged("WoodMemberType");
SetResourceFileName(_WoodMemberType);
PopulateSpeciesList();
OnNodeModified(true);
}
}
}
#endregion
#region ReportEntryProperty
/// <summary>
/// log property
/// </summary>
/// <value>Calculation entries that can be converted into a report.</value>
public string reportEntry;
public string ReportEntry
{
get { return reportEntry; }
set
{
reportEntry = value;
RaisePropertyChanged("ReportEntry");
OnNodeModified(true);
}
}
#endregion
#endregion
#endregion
#region SelectedItem Property
private EnumDataElement selectedItem;
public EnumDataElement SelectedItem
{
get { return selectedItem; }
set { selectedItem = value; RaisePropertyChanged("SelectedItem"); }
}
#endregion
private void SetDefaultParams()
{
//this.WoodMemberType = "SawnDimensionLumber";
this.WoodSpeciesId = "DOUGLAS FIR-LARCH";
this.CommercialGradeId = "Stud";
}
bool RefreshView;
#region Display parameters
private string _resourceFileName;
public string ResourceFileName
{
get { return _resourceFileName; }
set { _resourceFileName = value; }
}
private void UpdateViewForSelectedSpecies()
{
CommercialGrades = FetchCommercialGradeList(ResourceFileName, WoodSpeciesId);
if (CommercialGrades.Contains(CommercialGradeId))
{
//Leave grade untouched
}
else
{
if (CommercialGrades.Contains("Stud"))
{
CommercialGradeId = "Stud";
}
else
{
CommercialGradeId = CommercialGrades[4];
}
}
}
private void UpdateViewForSelectedGrade()
{
SizeClasses = FetchSizeClassList(ResourceFileName, WoodSpeciesId, CommercialGradeId);
if (SizeClasses.Contains(SizeClassId))
{
//can keep current size class
}
else
{
SizeClassId = SizeClasses[0];
}
}
private void SetResourceFileName(string _WoodMemberType)
{
//NDS2015Table4A
if (WoodMemberType == "SawnDimensionLumber")
{
ResourceFileName = "NDS2015Table4A";
}
else
{
ResourceFileName = null;
}
}
private ObservableCollection<string> FetchSpeciesList(string ResourceFileName)
{
IEnumerable<string> distValues = null;
if (ResourceFileName != null)
{
string resourceName = string.Format("KodestructDynamoUI.Resources.{0}.txt", ResourceFileName);
var assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
string line;
using (TextReader tr = new StreamReader(stream))
{
//read full list of reference values
List<string> AllReferenceValues = new List<string>();
while ((line = tr.ReadLine()) != null)
{
AllReferenceValues.Add(line);
}
distValues = AllReferenceValues.Select(
v =>
{
string[] Vals = v.Split(',');
if (Vals.Length > 1)
{
return Vals[0];
}
else
{
return null;
}
}
).Distinct();
}
}
}
ObservableCollection<string> availabilitytList = new ObservableCollection<string>(distValues);
return availabilitytList;
}
private ObservableCollection<string> FetchCommercialGradeList(string ResourceFileName, string WoodSpecies)
{
//ObservableCollection<string> availabilitytList = new ObservableCollection<string>();
List<string> filteredList = new List<string>();
if ( ResourceFileName != null)
{
string resourceName = string.Format("KodestructDynamoUI.Resources.{0}.txt", ResourceFileName);
var assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
string line;
using (TextReader tr = new StreamReader(stream))
{
//read full list of reference values
List<string> AllReferenceValues = new List<string>();
while ((line = tr.ReadLine()) != null)
{
AllReferenceValues.Add(line);
}
//Lookup
foreach (var sh in AllReferenceValues)
{
string[] Vals = sh.Split(',');
if (Vals.Length == 3)
{
if (Vals[0] == WoodSpecies)
{
filteredList.Add( (string)Vals[1]);
}
}
}
}
}
}
ObservableCollection<string> availabilitytList = new ObservableCollection<string>(filteredList.Distinct());
return availabilitytList;
}
private ObservableCollection<string> FetchSizeClassList(string ResourceFileName, string WoodSpecies, string CommercialGradeId)
{
List<string> filteredList = new List<string>();
if ( ResourceFileName != null)
{
string resourceName = string.Format("KodestructDynamoUI.Resources.{0}.txt", ResourceFileName);
var assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
string line;
using (TextReader tr = new StreamReader(stream))
{
//read full list of reference values
List<string> AllReferenceValues = new List<string>();
while ((line = tr.ReadLine()) != null)
{
AllReferenceValues.Add(line);
}
//Lookup
foreach (var sh in AllReferenceValues)
{
string[] Vals = sh.Split(',');
if (Vals.Length == 3)
{
if (Vals[0] == WoodSpecies && Vals[1] == CommercialGradeId)
{
filteredList.Add((string)Vals[2]);
}
}
}
}
}
}
ObservableCollection<string> availabilitytList = new ObservableCollection<string>(filteredList.Distinct());
return availabilitytList;
}
#region AvailableWoodSpecies Property
private ObservableCollection<string> _AvailableWoodSpecies;
public ObservableCollection<string> AvailableWoodSpecies
{
get { return _AvailableWoodSpecies; }
set
{
if (_AvailableWoodSpecies == null)
{
_AvailableWoodSpecies = new ObservableCollection<string>();
}
_AvailableWoodSpecies = value;
RaisePropertyChanged("AvailableWoodSpecies");
}
}
#endregion
#region CommercialGrades Property
private ObservableCollection<string> _CommercialGrades;
public ObservableCollection<string> CommercialGrades
{
get { return _CommercialGrades; }
set
{
if (_CommercialGrades == null)
{
_CommercialGrades = new ObservableCollection<string>();
}
_CommercialGrades = value;
RaisePropertyChanged("CommercialGrades");
}
}
#endregion
#region SizeClasses Property
private ObservableCollection<string> _SizeClasses;
public ObservableCollection<string> SizeClasses
{
get {
if (_SizeClasses == null)
{
_SizeClasses = new ObservableCollection<string>();
}
return _SizeClasses; }
set
{
_SizeClasses = value;
RaisePropertyChanged("SizeClasses");
}
}
#endregion
void UpdateView()
{
if (RefreshView == true)
{
ClearAllAvailableData();
//TODO search
}
}
private void ClearAllAvailableData()
{
AvailableWoodSpecies = null;
CommercialGrades = null;
SizeClasses = null;
}
#endregion
#region Serialization
/// <summary>
///Saves property values to be retained when opening the node
/// </summary>
protected override void SerializeCore(XmlElement nodeElement, SaveContext context)
{
base.SerializeCore(nodeElement, context);
//nodeElement.SetAttribute("ReportEntry",ReportEntry);
nodeElement.SetAttribute("WoodSpeciesId", WoodSpeciesId);
nodeElement.SetAttribute("CommercialGradeId", CommercialGradeId);
nodeElement.SetAttribute("SizeClassId", SizeClassId);
nodeElement.SetAttribute("WoodMemberType", WoodMemberType);
}
/// <summary>
///Retrieved property values when opening the node
/// </summary>
protected override void DeserializeCore(XmlElement nodeElement, SaveContext context)
{
base.DeserializeCore(nodeElement, context);
var WoodSpeciesId_attrib = nodeElement.Attributes["WoodSpeciesId"]; if (WoodSpeciesId_attrib != null) { WoodSpeciesId = WoodSpeciesId_attrib.Value; }
var CommercialGradeId_attrib = nodeElement.Attributes["CommercialGradeId"]; if (CommercialGradeId_attrib != null) { CommercialGradeId = CommercialGradeId_attrib.Value; }
var SizeClassId_attrib = nodeElement.Attributes["SizeClassId"]; if (SizeClassId_attrib != null) { SizeClassId = SizeClassId_attrib.Value; }
var WoodMemberType_attrib = nodeElement.Attributes["WoodMemberType"]; if (WoodMemberType_attrib != null) { WoodMemberType = WoodMemberType_attrib.Value; }
}
#endregion
/// <summary>
///Customization of WPF view in Dynamo UI
/// </summary>
public class AiscShapeSelectionViewCustomization : UiNodeBaseViewCustomization,
INodeViewCustomization<WoodSpeciesAndGradeSelection>
{
public void CustomizeView(WoodSpeciesAndGradeSelection model, NodeView nodeView)
{
base.CustomizeView(model, nodeView);
WoodSpeciesAndGradeSelectionView control = new WoodSpeciesAndGradeSelectionView();
control.DataContext = model;
nodeView.inputGrid.Children.Add(control);
base.CustomizeView(model, nodeView);
}
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.Extensions.Internal;
using Microsoft.Extensions.ProjectModel.Graph;
using Microsoft.Extensions.ProjectModel.Resolution;
using NuGet.Frameworks;
namespace Microsoft.Extensions.ProjectModel
{
public class ProjectContextBuilder
{
private Project Project { get; set; }
private LockFile LockFile { get; set; }
private GlobalSettings GlobalSettings { get; set; }
private NuGetFramework TargetFramework { get; set; }
private IEnumerable<string> RuntimeIdentifiers { get; set; } = Enumerable.Empty<string>();
private string RootDirectory { get; set; }
private string ProjectDirectory { get; set; }
private string PackagesDirectory { get; set; }
private string ReferenceAssembliesPath { get; set; }
public ProjectContextBuilder WithLockFile(LockFile lockFile)
{
LockFile = lockFile;
return this;
}
public ProjectContextBuilder WithProject(Project project)
{
Project = project;
return this;
}
public ProjectContextBuilder WithProjectDirectory(string projectDirectory)
{
ProjectDirectory = projectDirectory;
return this;
}
public ProjectContextBuilder WithTargetFramework(NuGetFramework targetFramework)
{
TargetFramework = targetFramework;
return this;
}
public ProjectContextBuilder WithTargetFramework(string targetFramework)
{
TargetFramework = NuGetFramework.Parse(targetFramework);
return this;
}
public ProjectContextBuilder WithRuntimeIdentifiers(IEnumerable<string> runtimeIdentifiers)
{
RuntimeIdentifiers = runtimeIdentifiers;
return this;
}
public ProjectContextBuilder WithReferenceAssembliesPath(string referenceAssembliesPath)
{
ReferenceAssembliesPath = referenceAssembliesPath;
return this;
}
public ProjectContextBuilder WithPackagesDirectory(string packagesDirectory)
{
PackagesDirectory = packagesDirectory;
return this;
}
public ProjectContextBuilder WithRootDirectory(string rootDirectory)
{
RootDirectory = rootDirectory;
return this;
}
public ProjectContext Build()
{
ProjectDirectory = Project?.ProjectDirectory ?? ProjectDirectory;
if (GlobalSettings == null)
{
RootDirectory = ProjectRootResolver.ResolveRootDirectory(ProjectDirectory);
GlobalSettings globalSettings;
if (GlobalSettings.TryGetGlobalSettings(RootDirectory, out globalSettings))
{
GlobalSettings = globalSettings;
}
}
RootDirectory = GlobalSettings?.DirectoryPath ?? RootDirectory;
PackagesDirectory = PackagesDirectory ?? PackageDependencyProvider.ResolvePackagesPath(RootDirectory, GlobalSettings);
ReferenceAssembliesPath = ReferenceAssembliesPath ?? GetDefaultReferenceAssembliesPath();
LockFileLookup lockFileLookup = null;
EnsureProjectLoaded();
var projectLockJsonPath = Path.Combine(ProjectDirectory, LockFile.FileName);
if (LockFile == null && File.Exists(projectLockJsonPath))
{
LockFile = LockFileReader.Read(projectLockJsonPath);
}
var validLockFile = true;
string lockFileValidationMessage = null;
if (LockFile != null)
{
validLockFile = LockFile.IsValidForProject(Project, out lockFileValidationMessage);
lockFileLookup = new LockFileLookup(LockFile);
}
var libraries = new Dictionary<LibraryKey, LibraryDescription>();
var projectResolver = new ProjectDependencyProvider();
var mainProject = projectResolver.GetDescription(TargetFramework, Project);
// Add the main project
libraries.Add(new LibraryKey(mainProject.Identity.Name), mainProject);
LockFileTarget target = null;
if (lockFileLookup != null)
{
target = SelectTarget(LockFile);
if (target != null)
{
var packageResolver = new PackageDependencyProvider(PackagesDirectory);
ScanLibraries(target, lockFileLookup, libraries, packageResolver, projectResolver);
}
}
var frameworkReferenceResolver = new FrameworkReferenceResolver(ReferenceAssembliesPath);
var referenceAssemblyDependencyResolver = new ReferenceAssemblyDependencyResolver(frameworkReferenceResolver);
bool requiresFrameworkAssemblies;
// Resolve the dependencies
ResolveDependencies(libraries, referenceAssemblyDependencyResolver, out requiresFrameworkAssemblies);
var diagnostics = new List<DiagnosticMessage>();
// REVIEW: Should this be in NuGet (possibly stored in the lock file?)
if (LockFile == null)
{
diagnostics.Add(new DiagnosticMessage(
ErrorCodes.NU1009,
$"The expected lock file doesn't exist. Please run \"dotnet restore\" to generate a new lock file.",
Path.Combine(Project.ProjectDirectory, LockFile.FileName),
DiagnosticMessageSeverity.Error));
}
if (!validLockFile)
{
diagnostics.Add(new DiagnosticMessage(
ErrorCodes.NU1006,
$"{lockFileValidationMessage}. Please run \"dotnet restore\" to generate a new lock file.",
Path.Combine(Project.ProjectDirectory, LockFile.FileName),
DiagnosticMessageSeverity.Warning));
}
if (requiresFrameworkAssemblies)
{
var frameworkInfo = Project.GetTargetFramework(TargetFramework);
if (string.IsNullOrEmpty(ReferenceAssembliesPath))
{
// If there was an attempt to use reference assemblies but they were not installed
// report an error
diagnostics.Add(new DiagnosticMessage(
ErrorCodes.DOTNET1012,
$"The reference assemblies directory was not specified. You can set the location using the DOTNET_REFERENCE_ASSEMBLIES_PATH environment variable.",
filePath: Project.ProjectFilePath,
severity: DiagnosticMessageSeverity.Error,
startLine: frameworkInfo.Line,
startColumn: frameworkInfo.Column
));
}
else if (!frameworkReferenceResolver.IsInstalled(TargetFramework))
{
// If there was an attempt to use reference assemblies but they were not installed
// report an error
diagnostics.Add(new DiagnosticMessage(
ErrorCodes.DOTNET1011,
$"Framework not installed: {TargetFramework.DotNetFrameworkName} in {ReferenceAssembliesPath}",
filePath: Project.ProjectFilePath,
severity: DiagnosticMessageSeverity.Error,
startLine: frameworkInfo.Line,
startColumn: frameworkInfo.Column
));
}
}
// Create a library manager
var libraryManager = new LibraryManager(libraries.Values.ToList(), diagnostics, Project.ProjectFilePath);
return new ProjectContext(
GlobalSettings,
mainProject,
TargetFramework,
target?.RuntimeIdentifier,
PackagesDirectory,
libraryManager);
}
private void ResolveDependencies(Dictionary<LibraryKey, LibraryDescription> libraries,
ReferenceAssemblyDependencyResolver referenceAssemblyDependencyResolver,
out bool requiresFrameworkAssemblies)
{
requiresFrameworkAssemblies = false;
foreach (var library in libraries.Values.ToList())
{
if (Equals(library.Identity.Type, LibraryType.Package) &&
!Directory.Exists(library.Path))
{
// If the package path doesn't exist then mark this dependency as unresolved
library.Resolved = false;
}
library.Framework = library.Framework ?? TargetFramework;
foreach (var dependency in library.Dependencies)
{
var keyType = dependency.Target == LibraryType.ReferenceAssembly ? LibraryType.ReferenceAssembly : LibraryType.Unspecified;
var key = new LibraryKey(dependency.Name, keyType);
LibraryDescription dep;
if (!libraries.TryGetValue(key, out dep))
{
if (Equals(LibraryType.ReferenceAssembly, dependency.Target))
{
requiresFrameworkAssemblies = true;
dep = referenceAssemblyDependencyResolver.GetDescription(dependency, TargetFramework) ??
UnresolvedDependencyProvider.GetDescription(dependency, TargetFramework);
dep.Framework = TargetFramework;
libraries[key] = dep;
}
else
{
dep = UnresolvedDependencyProvider.GetDescription(dependency, TargetFramework);
libraries[key] = dep;
}
}
dep.RequestedRanges.Add(dependency);
dep.Parents.Add(library);
}
}
}
private void ScanLibraries(LockFileTarget target, LockFileLookup lockFileLookup, Dictionary<LibraryKey, LibraryDescription> libraries, PackageDependencyProvider packageResolver, ProjectDependencyProvider projectResolver)
{
foreach (var library in target.Libraries)
{
LibraryDescription description = null;
var type = LibraryType.Unspecified;
if (string.Equals(library.Type, "project"))
{
var projectLibrary = lockFileLookup.GetProject(library.Name);
if (projectLibrary != null)
{
var path = Path.GetFullPath(Path.Combine(ProjectDirectory, projectLibrary.Path));
description = projectResolver.GetDescription(library.Name, path, library);
}
type = LibraryType.Project;
}
else
{
var packageEntry = lockFileLookup.GetPackage(library.Name, library.Version);
if (packageEntry != null)
{
description = packageResolver.GetDescription(packageEntry, library);
}
type = LibraryType.Package;
}
description = description ?? UnresolvedDependencyProvider.GetDescription(new LibraryRange(library.Name, type), target.TargetFramework);
libraries.Add(new LibraryKey(library.Name), description);
}
}
public static string GetDefaultReferenceAssembliesPath()
{
// Allow setting the reference assemblies path via an environment variable
var referenceAssembliesPath = Environment.GetEnvironmentVariable("DOTNET_REFERENCE_ASSEMBLIES_PATH");
if (!string.IsNullOrEmpty(referenceAssembliesPath))
{
return referenceAssembliesPath;
}
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
{
// There is no reference assemblies path outside of windows
// The enviorment variable can be used to specify one
return null;
}
// References assemblies are in %ProgramFiles(x86)% on
// 64 bit machines
var programFiles = Environment.GetEnvironmentVariable("ProgramFiles(x86)");
if (string.IsNullOrEmpty(programFiles))
{
// On 32 bit machines they are in %ProgramFiles%
programFiles = Environment.GetEnvironmentVariable("ProgramFiles");
}
if (string.IsNullOrEmpty(programFiles))
{
// Reference assemblies aren't installed
return null;
}
return Path.Combine(
programFiles,
"Reference Assemblies", "Microsoft", "Framework");
}
private void EnsureProjectLoaded()
{
if (Project == null)
{
Project project;
if (ProjectReader.TryGetProject(ProjectDirectory, out project))
{
Project = project;
}
else
{
throw new InvalidOperationException($"Unable to resolve project from {ProjectDirectory}");
}
}
}
private LockFileTarget SelectTarget(LockFile lockFile)
{
foreach (var runtimeIdentifier in RuntimeIdentifiers)
{
foreach (var scanTarget in lockFile.Targets)
{
if (Equals(scanTarget.TargetFramework, TargetFramework) && string.Equals(scanTarget.RuntimeIdentifier, runtimeIdentifier, StringComparison.Ordinal))
{
return scanTarget;
}
}
}
foreach (var scanTarget in lockFile.Targets)
{
if (Equals(scanTarget.TargetFramework, TargetFramework) && string.IsNullOrEmpty(scanTarget.RuntimeIdentifier))
{
return scanTarget;
}
}
return null;
}
private struct LibraryKey
{
public LibraryKey(string name) : this(name, LibraryType.Unspecified)
{
}
public LibraryKey(string name, LibraryType libraryType)
{
Name = name;
LibraryType = libraryType;
}
public string Name { get; }
public LibraryType LibraryType { get; }
public override bool Equals(object obj)
{
var otherKey = (LibraryKey)obj;
return string.Equals(otherKey.Name, Name, StringComparison.Ordinal) &&
otherKey.LibraryType.Equals(LibraryType);
}
public override int GetHashCode()
{
var combiner = new HashCodeCombiner();
combiner.Add(Name);
combiner.Add(LibraryType);
return combiner.CombinedHash;
}
}
}
}
| |
// Generated by TinyPG v1.3 available at www.codeproject.com
using System;
using System.Collections.Generic;
namespace TinyPG
{
#region Parser
public partial class Parser
{
private Scanner scanner;
private ParseTree tree;
public Parser(Scanner scanner)
{
this.scanner = scanner;
}
public ParseTree Parse(string input)
{
tree = new ParseTree();
return Parse(input, tree);
}
public ParseTree Parse(string input, ParseTree tree)
{
scanner.Init(input);
this.tree = tree;
ParseStart(tree);
tree.Skipped = scanner.Skipped;
return tree;
}
private void ParseStart(ParseNode parent)
{
Token tok;
ParseNode n;
ParseNode node = parent.CreateNode(scanner.GetToken(TokenType.Start), "Start");
parent.Nodes.Add(node);
tok = scanner.LookAhead(TokenType.DELETE);
if (tok.Type == TokenType.DELETE)
{
ParseDeleteStatement(node);
tok = scanner.Scan(TokenType.SEP);
n = node.CreateNode(tok, tok.ToString() );
node.Token.UpdateRange(tok);
node.Nodes.Add(n);
if (tok.Type != TokenType.SEP) {
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found. Expected " + TokenType.SEP.ToString(), 0x1001, 0, tok.StartPos, tok.StartPos, tok.Length));
return;
}
}
tok = scanner.LookAhead(TokenType.OBSOLETE);
if (tok.Type == TokenType.OBSOLETE)
{
ParseObsoleteStatement(node);
tok = scanner.Scan(TokenType.SEP);
n = node.CreateNode(tok, tok.ToString() );
node.Token.UpdateRange(tok);
node.Nodes.Add(n);
if (tok.Type != TokenType.SEP) {
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found. Expected " + TokenType.SEP.ToString(), 0x1001, 0, tok.StartPos, tok.StartPos, tok.Length));
return;
}
}
tok = scanner.LookAhead(TokenType.WAS);
if (tok.Type == TokenType.WAS)
{
ParseRenameStatement(node);
tok = scanner.Scan(TokenType.SEP);
n = node.CreateNode(tok, tok.ToString() );
node.Token.UpdateRange(tok);
node.Nodes.Add(n);
if (tok.Type != TokenType.SEP) {
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found. Expected " + TokenType.SEP.ToString(), 0x1001, 0, tok.StartPos, tok.StartPos, tok.Length));
return;
}
}
ParseRulesStatement(node);
tok = scanner.LookAhead(TokenType.SEP);
while (tok.Type == TokenType.SEP)
{
tok = scanner.Scan(TokenType.SEP);
n = node.CreateNode(tok, tok.ToString() );
node.Token.UpdateRange(tok);
node.Nodes.Add(n);
if (tok.Type != TokenType.SEP) {
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found. Expected " + TokenType.SEP.ToString(), 0x1001, 0, tok.StartPos, tok.StartPos, tok.Length));
return;
}
tok = scanner.LookAhead(TokenType.SEP);
}
tok = scanner.Scan(TokenType.EOF);
n = node.CreateNode(tok, tok.ToString() );
node.Token.UpdateRange(tok);
node.Nodes.Add(n);
if (tok.Type != TokenType.EOF) {
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found. Expected " + TokenType.EOF.ToString(), 0x1001, 0, tok.StartPos, tok.StartPos, tok.Length));
return;
}
parent.Token.UpdateRange(node.Token);
}
private void ParseRenameStatement(ParseNode parent)
{
Token tok;
ParseNode n;
ParseNode node = parent.CreateNode(scanner.GetToken(TokenType.RenameStatement), "RenameStatement");
parent.Nodes.Add(node);
tok = scanner.Scan(TokenType.WAS);
n = node.CreateNode(tok, tok.ToString() );
node.Token.UpdateRange(tok);
node.Nodes.Add(n);
if (tok.Type != TokenType.WAS) {
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found. Expected " + TokenType.WAS.ToString(), 0x1001, 0, tok.StartPos, tok.StartPos, tok.Length));
return;
}
tok = scanner.Scan(TokenType.VALUE);
n = node.CreateNode(tok, tok.ToString() );
node.Token.UpdateRange(tok);
node.Nodes.Add(n);
if (tok.Type != TokenType.VALUE) {
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found. Expected " + TokenType.VALUE.ToString(), 0x1001, 0, tok.StartPos, tok.StartPos, tok.Length));
return;
}
parent.Token.UpdateRange(node.Token);
}
private void ParseDeleteStatement(ParseNode parent)
{
Token tok;
ParseNode n;
ParseNode node = parent.CreateNode(scanner.GetToken(TokenType.DeleteStatement), "DeleteStatement");
parent.Nodes.Add(node);
tok = scanner.Scan(TokenType.DELETE);
n = node.CreateNode(tok, tok.ToString() );
node.Token.UpdateRange(tok);
node.Nodes.Add(n);
if (tok.Type != TokenType.DELETE) {
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found. Expected " + TokenType.DELETE.ToString(), 0x1001, 0, tok.StartPos, tok.StartPos, tok.Length));
return;
}
parent.Token.UpdateRange(node.Token);
}
private void ParseObsoleteStatement(ParseNode parent)
{
Token tok;
ParseNode n;
ParseNode node = parent.CreateNode(scanner.GetToken(TokenType.ObsoleteStatement), "ObsoleteStatement");
parent.Nodes.Add(node);
tok = scanner.Scan(TokenType.OBSOLETE);
n = node.CreateNode(tok, tok.ToString() );
node.Token.UpdateRange(tok);
node.Nodes.Add(n);
if (tok.Type != TokenType.OBSOLETE) {
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found. Expected " + TokenType.OBSOLETE.ToString(), 0x1001, 0, tok.StartPos, tok.StartPos, tok.Length));
return;
}
parent.Token.UpdateRange(node.Token);
}
private void ParseRulesStatement(ParseNode parent)
{
Token tok;
ParseNode n;
ParseNode node = parent.CreateNode(scanner.GetToken(TokenType.RulesStatement), "RulesStatement");
parent.Nodes.Add(node);
tok = scanner.LookAhead(TokenType.NAME, TokenType.BROPEN);
switch (tok.Type)
{
case TokenType.NAME:
ParseSimpleRule(node);
break;
case TokenType.BROPEN:
ParseCompositeRule(node);
break;
default:
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found.", 0x0002, 0, tok.StartPos, tok.StartPos, tok.Length));
break;
}
tok = scanner.LookAhead(TokenType.AND, TokenType.OR);
while (tok.Type == TokenType.AND
|| tok.Type == TokenType.OR)
{
ParseCombineOperator(node);
tok = scanner.LookAhead(TokenType.NAME, TokenType.BROPEN);
switch (tok.Type)
{
case TokenType.NAME:
ParseSimpleRule(node);
break;
case TokenType.BROPEN:
ParseCompositeRule(node);
break;
default:
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found.", 0x0002, 0, tok.StartPos, tok.StartPos, tok.Length));
break;
}
tok = scanner.LookAhead(TokenType.AND, TokenType.OR);
}
parent.Token.UpdateRange(node.Token);
}
private void ParseMatchOperator(ParseNode parent)
{
Token tok;
ParseNode n;
ParseNode node = parent.CreateNode(scanner.GetToken(TokenType.MatchOperator), "MatchOperator");
parent.Nodes.Add(node);
tok = scanner.LookAhead(TokenType.EQ, TokenType.NEQ, TokenType.GT, TokenType.LT, TokenType.GTE, TokenType.LTE, TokenType.CONTAINS);
switch (tok.Type)
{
case TokenType.EQ:
tok = scanner.Scan(TokenType.EQ);
n = node.CreateNode(tok, tok.ToString() );
node.Token.UpdateRange(tok);
node.Nodes.Add(n);
if (tok.Type != TokenType.EQ) {
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found. Expected " + TokenType.EQ.ToString(), 0x1001, 0, tok.StartPos, tok.StartPos, tok.Length));
return;
}
break;
case TokenType.NEQ:
tok = scanner.Scan(TokenType.NEQ);
n = node.CreateNode(tok, tok.ToString() );
node.Token.UpdateRange(tok);
node.Nodes.Add(n);
if (tok.Type != TokenType.NEQ) {
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found. Expected " + TokenType.NEQ.ToString(), 0x1001, 0, tok.StartPos, tok.StartPos, tok.Length));
return;
}
break;
case TokenType.GT:
tok = scanner.Scan(TokenType.GT);
n = node.CreateNode(tok, tok.ToString() );
node.Token.UpdateRange(tok);
node.Nodes.Add(n);
if (tok.Type != TokenType.GT) {
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found. Expected " + TokenType.GT.ToString(), 0x1001, 0, tok.StartPos, tok.StartPos, tok.Length));
return;
}
break;
case TokenType.LT:
tok = scanner.Scan(TokenType.LT);
n = node.CreateNode(tok, tok.ToString() );
node.Token.UpdateRange(tok);
node.Nodes.Add(n);
if (tok.Type != TokenType.LT) {
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found. Expected " + TokenType.LT.ToString(), 0x1001, 0, tok.StartPos, tok.StartPos, tok.Length));
return;
}
break;
case TokenType.GTE:
tok = scanner.Scan(TokenType.GTE);
n = node.CreateNode(tok, tok.ToString() );
node.Token.UpdateRange(tok);
node.Nodes.Add(n);
if (tok.Type != TokenType.GTE) {
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found. Expected " + TokenType.GTE.ToString(), 0x1001, 0, tok.StartPos, tok.StartPos, tok.Length));
return;
}
break;
case TokenType.LTE:
tok = scanner.Scan(TokenType.LTE);
n = node.CreateNode(tok, tok.ToString() );
node.Token.UpdateRange(tok);
node.Nodes.Add(n);
if (tok.Type != TokenType.LTE) {
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found. Expected " + TokenType.LTE.ToString(), 0x1001, 0, tok.StartPos, tok.StartPos, tok.Length));
return;
}
break;
case TokenType.CONTAINS:
tok = scanner.Scan(TokenType.CONTAINS);
n = node.CreateNode(tok, tok.ToString() );
node.Token.UpdateRange(tok);
node.Nodes.Add(n);
if (tok.Type != TokenType.CONTAINS) {
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found. Expected " + TokenType.CONTAINS.ToString(), 0x1001, 0, tok.StartPos, tok.StartPos, tok.Length));
return;
}
break;
default:
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found.", 0x0002, 0, tok.StartPos, tok.StartPos, tok.Length));
break;
}
parent.Token.UpdateRange(node.Token);
}
private void ParseCombineOperator(ParseNode parent)
{
Token tok;
ParseNode n;
ParseNode node = parent.CreateNode(scanner.GetToken(TokenType.CombineOperator), "CombineOperator");
parent.Nodes.Add(node);
tok = scanner.LookAhead(TokenType.AND, TokenType.OR);
switch (tok.Type)
{
case TokenType.AND:
tok = scanner.Scan(TokenType.AND);
n = node.CreateNode(tok, tok.ToString() );
node.Token.UpdateRange(tok);
node.Nodes.Add(n);
if (tok.Type != TokenType.AND) {
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found. Expected " + TokenType.AND.ToString(), 0x1001, 0, tok.StartPos, tok.StartPos, tok.Length));
return;
}
break;
case TokenType.OR:
tok = scanner.Scan(TokenType.OR);
n = node.CreateNode(tok, tok.ToString() );
node.Token.UpdateRange(tok);
node.Nodes.Add(n);
if (tok.Type != TokenType.OR) {
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found. Expected " + TokenType.OR.ToString(), 0x1001, 0, tok.StartPos, tok.StartPos, tok.Length));
return;
}
break;
default:
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found.", 0x0002, 0, tok.StartPos, tok.StartPos, tok.Length));
break;
}
parent.Token.UpdateRange(node.Token);
}
private void ParseSimpleRule(ParseNode parent)
{
Token tok;
ParseNode n;
ParseNode node = parent.CreateNode(scanner.GetToken(TokenType.SimpleRule), "SimpleRule");
parent.Nodes.Add(node);
tok = scanner.Scan(TokenType.NAME);
n = node.CreateNode(tok, tok.ToString() );
node.Token.UpdateRange(tok);
node.Nodes.Add(n);
if (tok.Type != TokenType.NAME) {
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found. Expected " + TokenType.NAME.ToString(), 0x1001, 0, tok.StartPos, tok.StartPos, tok.Length));
return;
}
ParseMatchOperator(node);
tok = scanner.Scan(TokenType.VALUE);
n = node.CreateNode(tok, tok.ToString() );
node.Token.UpdateRange(tok);
node.Nodes.Add(n);
if (tok.Type != TokenType.VALUE) {
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found. Expected " + TokenType.VALUE.ToString(), 0x1001, 0, tok.StartPos, tok.StartPos, tok.Length));
return;
}
parent.Token.UpdateRange(node.Token);
}
private void ParseCompositeRule(ParseNode parent)
{
Token tok;
ParseNode n;
ParseNode node = parent.CreateNode(scanner.GetToken(TokenType.CompositeRule), "CompositeRule");
parent.Nodes.Add(node);
tok = scanner.Scan(TokenType.BROPEN);
n = node.CreateNode(tok, tok.ToString() );
node.Token.UpdateRange(tok);
node.Nodes.Add(n);
if (tok.Type != TokenType.BROPEN) {
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found. Expected " + TokenType.BROPEN.ToString(), 0x1001, 0, tok.StartPos, tok.StartPos, tok.Length));
return;
}
tok = scanner.LookAhead(TokenType.NAME, TokenType.BROPEN);
switch (tok.Type)
{
case TokenType.NAME:
ParseSimpleRule(node);
break;
case TokenType.BROPEN:
ParseCompositeRule(node);
break;
default:
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found.", 0x0002, 0, tok.StartPos, tok.StartPos, tok.Length));
break;
}
tok = scanner.LookAhead(TokenType.AND, TokenType.OR);
while (tok.Type == TokenType.AND
|| tok.Type == TokenType.OR)
{
ParseCombineOperator(node);
tok = scanner.LookAhead(TokenType.NAME, TokenType.BROPEN);
switch (tok.Type)
{
case TokenType.NAME:
ParseSimpleRule(node);
break;
case TokenType.BROPEN:
ParseCompositeRule(node);
break;
default:
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found.", 0x0002, 0, tok.StartPos, tok.StartPos, tok.Length));
break;
}
tok = scanner.LookAhead(TokenType.AND, TokenType.OR);
}
tok = scanner.Scan(TokenType.BRCLOSE);
n = node.CreateNode(tok, tok.ToString() );
node.Token.UpdateRange(tok);
node.Nodes.Add(n);
if (tok.Type != TokenType.BRCLOSE) {
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found. Expected " + TokenType.BRCLOSE.ToString(), 0x1001, 0, tok.StartPos, tok.StartPos, tok.Length));
return;
}
parent.Token.UpdateRange(node.Token);
}
private void ParseRule(ParseNode parent)
{
Token tok;
ParseNode n;
ParseNode node = parent.CreateNode(scanner.GetToken(TokenType.Rule), "Rule");
parent.Nodes.Add(node);
tok = scanner.LookAhead(TokenType.NAME, TokenType.BROPEN);
switch (tok.Type)
{
case TokenType.NAME:
ParseSimpleRule(node);
break;
case TokenType.BROPEN:
ParseCompositeRule(node);
break;
default:
tree.Errors.Add(new ParseError("Unexpected token '" + tok.Text.Replace("\n", "") + "' found.", 0x0002, 0, tok.StartPos, tok.StartPos, tok.Length));
break;
}
parent.Token.UpdateRange(node.Token);
}
}
#endregion Parser
}
| |
// 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: The structure for holding all of the data needed
** for object serialization and deserialization.
**
**
===========================================================*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Globalization;
using System.Diagnostics;
using System.Security;
using System.Runtime.CompilerServices;
namespace System.Runtime.Serialization
{
public sealed class SerializationInfo
{
private const int defaultSize = 4;
private const string s_mscorlibAssemblySimpleName = System.CoreLib.Name;
private const string s_mscorlibFileName = s_mscorlibAssemblySimpleName + ".dll";
// Even though we have a dictionary, we're still keeping all the arrays around for back-compat.
// Otherwise we may run into potentially breaking behaviors like GetEnumerator() not returning entries in the same order they were added.
internal String[] m_members;
internal Object[] m_data;
internal Type[] m_types;
private Dictionary<string, int> m_nameToIndex;
internal int m_currMember;
internal IFormatterConverter m_converter;
private String m_fullTypeName;
private String m_assemName;
private Type objectType;
private bool isFullTypeNameSetExplicit;
private bool isAssemblyNameSetExplicit;
private bool requireSameTokenInPartialTrust;
[CLSCompliant(false)]
public SerializationInfo(Type type, IFormatterConverter converter)
: this(type, converter, false)
{
}
[CLSCompliant(false)]
public SerializationInfo(Type type, IFormatterConverter converter, bool requireSameTokenInPartialTrust)
{
if ((object)type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (converter == null)
{
throw new ArgumentNullException(nameof(converter));
}
objectType = type;
m_fullTypeName = type.FullName;
m_assemName = type.Module.Assembly.FullName;
m_members = new String[defaultSize];
m_data = new Object[defaultSize];
m_types = new Type[defaultSize];
m_nameToIndex = new Dictionary<string, int>();
m_converter = converter;
this.requireSameTokenInPartialTrust = requireSameTokenInPartialTrust;
}
public String FullTypeName
{
get
{
return m_fullTypeName;
}
set
{
if (null == value)
{
throw new ArgumentNullException(nameof(value));
}
m_fullTypeName = value;
isFullTypeNameSetExplicit = true;
}
}
public String AssemblyName
{
get
{
return m_assemName;
}
set
{
if (null == value)
{
throw new ArgumentNullException(nameof(value));
}
if (requireSameTokenInPartialTrust)
{
DemandForUnsafeAssemblyNameAssignments(m_assemName, value);
}
m_assemName = value;
isAssemblyNameSetExplicit = true;
}
}
public void SetType(Type type)
{
if ((object)type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (requireSameTokenInPartialTrust)
{
DemandForUnsafeAssemblyNameAssignments(this.ObjectType.Assembly.FullName, type.Assembly.FullName);
}
if (!Object.ReferenceEquals(objectType, type))
{
objectType = type;
m_fullTypeName = type.FullName;
m_assemName = type.Module.Assembly.FullName;
isFullTypeNameSetExplicit = false;
isAssemblyNameSetExplicit = false;
}
}
internal static void DemandForUnsafeAssemblyNameAssignments(string originalAssemblyName, string newAssemblyName)
{
}
public int MemberCount
{
get
{
return m_currMember;
}
}
public Type ObjectType
{
get
{
return objectType;
}
}
public bool IsFullTypeNameSetExplicit
{
get
{
return isFullTypeNameSetExplicit;
}
}
public bool IsAssemblyNameSetExplicit
{
get
{
return isAssemblyNameSetExplicit;
}
}
public SerializationInfoEnumerator GetEnumerator()
{
return new SerializationInfoEnumerator(m_members, m_data, m_types, m_currMember);
}
private void ExpandArrays()
{
int newSize;
Debug.Assert(m_members.Length == m_currMember, "[SerializationInfo.ExpandArrays]m_members.Length == m_currMember");
newSize = (m_currMember * 2);
//
// In the pathological case, we may wrap
//
if (newSize < m_currMember)
{
if (Int32.MaxValue > m_currMember)
{
newSize = Int32.MaxValue;
}
}
//
// Allocate more space and copy the data
//
String[] newMembers = new String[newSize];
Object[] newData = new Object[newSize];
Type[] newTypes = new Type[newSize];
Array.Copy(m_members, newMembers, m_currMember);
Array.Copy(m_data, newData, m_currMember);
Array.Copy(m_types, newTypes, m_currMember);
//
// Assign the new arrys back to the member vars.
//
m_members = newMembers;
m_data = newData;
m_types = newTypes;
}
public void AddValue(String name, Object value, Type type)
{
if (null == name)
{
throw new ArgumentNullException(nameof(name));
}
if ((object)type == null)
{
throw new ArgumentNullException(nameof(type));
}
AddValueInternal(name, value, type);
}
public void AddValue(String name, Object value)
{
if (null == value)
{
AddValue(name, value, typeof(Object));
}
else
{
AddValue(name, value, value.GetType());
}
}
public void AddValue(String name, bool value)
{
AddValue(name, (Object)value, typeof(bool));
}
public void AddValue(String name, char value)
{
AddValue(name, (Object)value, typeof(char));
}
[CLSCompliant(false)]
public void AddValue(String name, sbyte value)
{
AddValue(name, (Object)value, typeof(sbyte));
}
public void AddValue(String name, byte value)
{
AddValue(name, (Object)value, typeof(byte));
}
public void AddValue(String name, short value)
{
AddValue(name, (Object)value, typeof(short));
}
[CLSCompliant(false)]
public void AddValue(String name, ushort value)
{
AddValue(name, (Object)value, typeof(ushort));
}
public void AddValue(String name, int value)
{
AddValue(name, (Object)value, typeof(int));
}
[CLSCompliant(false)]
public void AddValue(String name, uint value)
{
AddValue(name, (Object)value, typeof(uint));
}
public void AddValue(String name, long value)
{
AddValue(name, (Object)value, typeof(long));
}
[CLSCompliant(false)]
public void AddValue(String name, ulong value)
{
AddValue(name, (Object)value, typeof(ulong));
}
public void AddValue(String name, float value)
{
AddValue(name, (Object)value, typeof(float));
}
public void AddValue(String name, double value)
{
AddValue(name, (Object)value, typeof(double));
}
public void AddValue(String name, decimal value)
{
AddValue(name, (Object)value, typeof(decimal));
}
public void AddValue(String name, DateTime value)
{
AddValue(name, (Object)value, typeof(DateTime));
}
internal void AddValueInternal(String name, Object value, Type type)
{
if (m_nameToIndex.ContainsKey(name))
{
throw new SerializationException(SR.Serialization_SameNameTwice);
}
m_nameToIndex.Add(name, m_currMember);
//
// If we need to expand the arrays, do so.
//
if (m_currMember >= m_members.Length)
{
ExpandArrays();
}
//
// Add the data and then advance the counter.
//
m_members[m_currMember] = name;
m_data[m_currMember] = value;
m_types[m_currMember] = type;
m_currMember++;
}
/*=================================UpdateValue==================================
**Action: Finds the value if it exists in the current data. If it does, we replace
** the values, if not, we append it to the end. This is useful to the
** ObjectManager when it's performing fixups.
**Returns: void
**Arguments: name -- the name of the data to be updated.
** value -- the new value.
** type -- the type of the data being added.
**Exceptions: None. All error checking is done with asserts. Although public in coreclr,
** it's not exposed in a contract and is only meant to be used by corefx.
==============================================================================*/
// This should not be used by clients: exposing out this functionality would allow children
// to overwrite their parent's values. It is public in order to give corefx access to it for
// its ObjectManager implementation, but it should not be exposed out of a contract.
public void UpdateValue(String name, Object value, Type type)
{
Debug.Assert(null != name, "[SerializationInfo.UpdateValue]name!=null");
Debug.Assert(null != value, "[SerializationInfo.UpdateValue]value!=null");
Debug.Assert(null != (object)type, "[SerializationInfo.UpdateValue]type!=null");
int index = FindElement(name);
if (index < 0)
{
AddValueInternal(name, value, type);
}
else
{
m_data[index] = value;
m_types[index] = type;
}
}
private int FindElement(String name)
{
if (null == name)
{
throw new ArgumentNullException(nameof(name));
}
int index;
if (m_nameToIndex.TryGetValue(name, out index))
{
return index;
}
return -1;
}
/*==================================GetElement==================================
**Action: Use FindElement to get the location of a particular member and then return
** the value of the element at that location. The type of the member is
** returned in the foundType field.
**Returns: The value of the element at the position associated with name.
**Arguments: name -- the name of the element to find.
** foundType -- the type of the element associated with the given name.
**Exceptions: None. FindElement does null checking and throws for elements not
** found.
==============================================================================*/
private Object GetElement(String name, out Type foundType)
{
int index = FindElement(name);
if (index == -1)
{
throw new SerializationException(SR.Format(SR.Serialization_NotFound, name));
}
Debug.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length");
Debug.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length");
foundType = m_types[index];
Debug.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null");
return m_data[index];
}
private Object GetElementNoThrow(String name, out Type foundType)
{
int index = FindElement(name);
if (index == -1)
{
foundType = null;
return null;
}
Debug.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length");
Debug.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length");
foundType = m_types[index];
Debug.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null");
return m_data[index];
}
//
// The user should call one of these getters to get the data back in the
// form requested.
//
public Object GetValue(String name, Type type)
{
if ((object)type == null)
{
throw new ArgumentNullException(nameof(type));
}
RuntimeType rt = type as RuntimeType;
if (rt == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType);
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null)
{
return value;
}
Debug.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null");
return m_converter.Convert(value, type);
}
internal Object GetValueNoThrow(String name, Type type)
{
Type foundType;
Object value;
Debug.Assert((object)type != null, "[SerializationInfo.GetValue]type ==null");
Debug.Assert(type is RuntimeType, "[SerializationInfo.GetValue]type is not a runtime type");
value = GetElementNoThrow(name, out foundType);
if (value == null)
return null;
if (Object.ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null)
{
return value;
}
Debug.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null");
return m_converter.Convert(value, type);
}
public bool GetBoolean(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(bool)))
{
return (bool)value;
}
return m_converter.ToBoolean(value);
}
public char GetChar(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(char)))
{
return (char)value;
}
return m_converter.ToChar(value);
}
[CLSCompliant(false)]
public sbyte GetSByte(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(sbyte)))
{
return (sbyte)value;
}
return m_converter.ToSByte(value);
}
public byte GetByte(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(byte)))
{
return (byte)value;
}
return m_converter.ToByte(value);
}
public short GetInt16(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(short)))
{
return (short)value;
}
return m_converter.ToInt16(value);
}
[CLSCompliant(false)]
public ushort GetUInt16(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(ushort)))
{
return (ushort)value;
}
return m_converter.ToUInt16(value);
}
public int GetInt32(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(int)))
{
return (int)value;
}
return m_converter.ToInt32(value);
}
[CLSCompliant(false)]
public uint GetUInt32(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(uint)))
{
return (uint)value;
}
return m_converter.ToUInt32(value);
}
public long GetInt64(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(long)))
{
return (long)value;
}
return m_converter.ToInt64(value);
}
[CLSCompliant(false)]
public ulong GetUInt64(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(ulong)))
{
return (ulong)value;
}
return m_converter.ToUInt64(value);
}
public float GetSingle(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(float)))
{
return (float)value;
}
return m_converter.ToSingle(value);
}
public double GetDouble(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(double)))
{
return (double)value;
}
return m_converter.ToDouble(value);
}
public decimal GetDecimal(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(decimal)))
{
return (decimal)value;
}
return m_converter.ToDecimal(value);
}
public DateTime GetDateTime(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(DateTime)))
{
return (DateTime)value;
}
return m_converter.ToDateTime(value);
}
public String GetString(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(String)) || value == null)
{
return (String)value;
}
return m_converter.ToString(value);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace NetController.Web.UI.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ActionDescriptor.ReturnType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright (c) 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 Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Roslyn.Test.Utilities;
using Xunit;
using Microsoft.CodeAnalysis.CSharp;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class InvocationExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
internal override ISignatureHelpProvider CreateSignatureHelpProvider()
{
return new InvocationExpressionSignatureHelpProvider();
}
#region "Regular tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationAfterCloseParen()
{
var markup = @"
class C
{
int Foo(int x)
{
[|Foo(Foo(x)$$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int C.Foo(int x)", currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationInsideLambda()
{
var markup = @"
using System;
class C
{
void Foo(Action<int> f)
{
[|Foo(i => Console.WriteLine(i)$$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(Action<int> f)", currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationInsideLambda2()
{
var markup = @"
using System;
class C
{
void Foo(Action<int> f)
{
[|Foo(i => Con$$sole.WriteLine(i)|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(Action<int> f)", currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutParameters()
{
var markup = @"
class C
{
void Foo()
{
[|Foo($$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutParametersMethodXmlComments()
{
var markup = @"
class C
{
/// <summary>
/// Summary for foo
/// </summary>
void Foo()
{
[|Foo($$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", "Summary for foo", null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersOn1()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo($$a, b|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersXmlCommentsOn1()
{
var markup = @"
class C
{
/// <summary>
/// Summary for Foo
/// </summary>
/// <param name=" + "\"a\">Param a</param>" + @"
/// <param name=" + "\"b\">Param b</param>" + @"
void Foo(int a, int b)
{
[|Foo($$a, b|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", "Summary for Foo", "Param a", currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersOn2()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo(a, $$b|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersXmlComentsOn2()
{
var markup = @"
class C
{
/// <summary>
/// Summary for Foo
/// </summary>
/// <param name=" + "\"a\">Param a</param>" + @"
/// <param name=" + "\"b\">Param b</param>" + @"
void Foo(int a, int b)
{
[|Foo(a, $$b|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", "Summary for Foo", "Param b", currentParameterIndex: 1));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutClosingParen()
{
var markup = @"
class C
{
void Foo()
{
[|Foo($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutClosingParenWithParameters()
{
var markup =
@"class C
{
void Foo(int a, int b)
{
[|Foo($$a, b
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutClosingParenWithParametersOn2()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo(a, $$b
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnLambda()
{
var markup = @"
using System;
class C
{
void Foo()
{
Action<int> f = (i) => Console.WriteLine(i);
[|f($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Action<int>(int obj)", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnMemberAccessExpression()
{
var markup = @"
class C
{
static void Bar(int a)
{
}
void Foo()
{
[|C.Bar($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Bar(int a)", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestExtensionMethod1()
{
var markup = @"
using System;
class C
{
void Method()
{
string s = ""Text"";
[|s.ExtensionMethod($$
|]}
}
public static class MyExtension
{
public static int ExtensionMethod(this string s, int x)
{
return s.Length;
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpEditorResources.Extension}) int string.ExtensionMethod(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
// TODO: Once we do the work to allow extension methods in nested types, we should change this.
Test(markup, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestOptionalParameters()
{
var markup = @"
class Class1
{
void Test()
{
Foo($$
}
void Foo(int a = 42)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Class1.Foo([int a = 42])", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestNoInvocationOnEventNotInCurrentClass()
{
var markup = @"
using System;
class C
{
void Foo()
{
D d;
[|d.evt($$
|]}
}
public class D
{
public event Action evt;
}";
Test(markup);
}
[WorkItem(539712)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnNamedType()
{
var markup = @"
class Program
{
void Main()
{
C.Foo($$
}
}
class C
{
public static double Foo(double x)
{
return x;
}
public double Foo(double x, double y)
{
return x + y;
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("double C.Foo(double x)", string.Empty, string.Empty, currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(539712)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnInstance()
{
var markup = @"
class Program
{
void Main()
{
new C().Foo($$
}
}
class C
{
public static double Foo(double x)
{
return x;
}
public double Foo(double x, double y)
{
return x + y;
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("double C.Foo(double x, double y)", string.Empty, string.Empty, currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(545118)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestStatic1()
{
var markup = @"
class C
{
static void Foo()
{
Bar($$
}
static void Bar()
{
}
void Bar(int i)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void C.Bar()", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(545118)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestStatic2()
{
var markup = @"
class C
{
void Foo()
{
Bar($$
}
static void Bar()
{
}
void Bar(int i)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void C.Bar()", currentParameterIndex: 0),
new SignatureHelpTestItem("void C.Bar(int i)", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(543117)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnAnonymousType()
{
var markup = @"
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
var foo = new { Name = string.Empty, Age = 30 };
Foo(foo).Add($$);
}
static List<T> Foo<T>(T t)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
$@"void List<'a>.Add('a item)
{FeaturesResources.AnonymousTypes}
'a {FeaturesResources.Is} new {{ string Name, int Age }}",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: $@"
{FeaturesResources.AnonymousTypes}
'a {FeaturesResources.Is} new {{ string Name, int Age }}")
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnBaseExpression_ProtectedAccessibility()
{
var markup = @"
using System;
public class Base
{
protected virtual void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
base.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnBaseExpression_AbstractBase()
{
var markup = @"
using System;
public abstract class Base
{
protected abstract void Foo(int x);
}
public class Derived : Base
{
void Test()
{
base.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnThisExpression_ProtectedAccessibility()
{
var markup = @"
using System;
public class Base
{
protected virtual void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
this.Foo($$);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnThisExpression_ProtectedAccessibility_Overridden()
{
var markup = @"
using System;
public class Base
{
protected virtual void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
this.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Derived.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnThisExpression_ProtectedAccessibility_AbstractBase()
{
var markup = @"
using System;
public abstract class Base
{
protected abstract void Foo(int x);
}
public class Derived : Base
{
void Test()
{
this.Foo($$);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnThisExpression_ProtectedAccessibility_AbstractBase_Overridden()
{
var markup = @"
using System;
public abstract class Base
{
protected abstract void Foo(int x);
}
public class Derived : Base
{
void Test()
{
this.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Derived.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnBaseExpression_ProtectedInternalAccessibility()
{
var markup = @"
using System;
public class Base
{
protected internal void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
base.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnBaseMember_ProtectedAccessibility_ThroughType()
{
var markup = @"
using System;
public class Base
{
protected virtual void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
new Base().Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
Test(markup, null);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnBaseExpression_PrivateAccessibility()
{
var markup = @"
using System;
public class Base
{
private void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
base.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
Test(markup, null);
}
#endregion
#region "Current Parameter Name"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestCurrentParameterName()
{
var markup = @"
class C
{
void Foo(int someParameter, bool something)
{
Foo(something: false, someParameter: $$)
}
}";
VerifyCurrentParameterName(markup, "someParameter");
}
#endregion
#region "Trigger tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnTriggerParens()
{
var markup = @"
class C
{
void Foo()
{
[|Foo($$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnTriggerComma()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo(23,$$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1));
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestNoInvocationOnSpace()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo(23, $$|]);
}
}";
Test(markup, 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 void EditorBrowsable_Method_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
Foo.Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(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 void EditorBrowsable_Method_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
Foo.Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Method_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
new Foo().Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public void Bar()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
TestSignatureHelpInEditorBrowsableContexts(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 void EditorBrowsable_Method_Overloads_OneBrowsableAlways_OneBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new Foo().Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public void Bar()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Bar(int x)
{
}
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(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 void EditorBrowsable_Method_Overloads_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new Foo().Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Bar()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Bar(int x)
{
}
}";
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void OverriddenSymbolsFilteredFromSigHelp()
{
var markup = @"
class Program
{
void M()
{
new D().Foo($$
}
}";
var referencedCode = @"
public class B
{
public virtual void Foo(int original)
{
}
}
public class D : B
{
public override void Foo(int derived)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void D.Foo(int derived)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(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 void EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverClass()
{
var markup = @"
class Program
{
void M()
{
new C().Foo($$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public class C
{
public void Foo()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(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 void EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverBaseClass()
{
var markup = @"
class Program
{
void M()
{
new D().Foo($$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public class B
{
public void Foo()
{
}
}
public class D : B
{
public void Foo(int x)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void B.Foo()", string.Empty, null, currentParameterIndex: 0),
new SignatureHelpTestItem("void D.Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0),
};
TestSignatureHelpInEditorBrowsableContexts(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 void EditorBrowsable_BrowsableStateNeverMethodsInBaseClass()
{
var markup = @"
class Program : B
{
void M()
{
Foo($$
}
}";
var referencedCode = @"
public class B
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void B.Foo()", string.Empty, null, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new C<int>().Foo($$
}
}";
var referencedCode = @"
public class C<T>
{
public void Foo(T t) { }
public void Foo(int i) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(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 void EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed1()
{
var markup = @"
class Program
{
void M()
{
new C<int>().Foo($$
}
}";
var referencedCode = @"
public class C<T>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(T t) { }
public void Foo(int i) { }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(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 void EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed2()
{
var markup = @"
class Program
{
void M()
{
new C<int>().Foo($$
}
}";
var referencedCode = @"
public class C<T>
{
public void Foo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(int i) { }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(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 void EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new C<int>().Foo($$
}
}";
var referencedCode = @"
public class C<T>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(int i) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new C<int, int>().Foo($$
}
}";
var referencedCode = @"
public class C<T, U>
{
public void Foo(T t) { }
public void Foo(U u) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(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 void EditorBrowsable_GenericType2CausingMethodSignatureEquality_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
new C<int, int>().Foo($$
}
}";
var referencedCode = @"
public class C<T, U>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(T t) { }
public void Foo(U u) { }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(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 void EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new C<int, int>().Foo($$
}
}";
var referencedCode = @"
public class C<T, U>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(U u) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
#endregion
#region "Awaitable tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void AwaitableMethod()
{
var markup = @"
using System.Threading.Tasks;
class C
{
async Task Foo()
{
[|Foo($$|]);
}
}";
var description = $@"
{WorkspacesResources.Usage}
await Foo();";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpEditorResources.Awaitable}) Task C.Foo()", methodDocumentation: description, currentParameterIndex: 0));
TestSignatureHelpWithMscorlib45(markup, expectedOrderedItems, "C#");
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void AwaitableMethod2()
{
var markup = @"
using System.Threading.Tasks;
class C
{
async Task<Task<int>> Foo()
{
[|Foo($$|]);
}
}";
var description = $@"
{WorkspacesResources.Usage}
Task<int> x = await Foo();";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpEditorResources.Awaitable}) Task<Task<int>> C.Foo()", methodDocumentation: description, currentParameterIndex: 0));
TestSignatureHelpWithMscorlib45(markup, expectedOrderedItems, "C#");
}
#endregion
[WorkItem(13849, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestSpecificity1()
{
var markup = @"
class Class1
{
static void Main()
{
var obj = new C<int>();
[|obj.M($$|])
}
}
class C<T>
{
/// <param name=""t"">Generic t</param>
public void M(T t) { }
/// <param name=""t"">Real t</param>
public void M(int t) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void C<int>.M(int t)", string.Empty, "Real t", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(530017)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void LongSignature()
{
var markup = @"
class C
{
void Foo(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j, string k, string l, string m, string n, string o, string p, string q, string r, string s, string t, string u, string v, string w, string x, string y, string z)
{
[|Foo($$|])
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
signature: "void C.Foo(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j, string k, string l, string m, string n, string o, string p, string q, string r, string s, string t, string u, string v, string w, string x, string y, string z)",
prettyPrintedSignature: @"void C.Foo(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j,
string k, string l, string m, string n, string o, string p, string q, string r, string s, string t, string u,
string v, string w, string x, string y, string z)",
currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void GenericExtensionMethod()
{
var markup = @"
interface IFoo
{
void Bar<T>();
}
static class FooExtensions
{
public static void Bar<T1, T2>(this IFoo foo) { }
}
class Program
{
static void Main()
{
IFoo f = null;
[|f.Bar($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void IFoo.Bar<T>()", currentParameterIndex: 0),
new SignatureHelpTestItem($"({CSharpEditorResources.Extension}) void IFoo.Bar<T1, T2>()", currentParameterIndex: 0),
};
// Extension methods are supported in Interactive/Script (yet).
Test(markup, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithCrefXmlComments()
{
var markup = @"
class C
{
/// <summary>
/// Summary for foo. See method <see cref=""Bar"" />
/// </summary>
void Foo()
{
[|Foo($$|]);
}
void Bar() { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", "Summary for foo. See method C.Bar()", null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
void bar()
{
}
#endif
void foo()
{
bar($$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"void C.bar()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj2", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0);
VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
void bar()
{
}
#endif
#if BAR
void foo()
{
bar($$
}
#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($"void C.bar()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj3", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0);
VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false);
}
[WorkItem(768697)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InstanceAndStaticMethodsShown1()
{
var markup = @"
class C
{
Foo Foo;
void M()
{
Foo.Bar($$
}
}
class Foo
{
public void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void Foo.Bar(int x)", currentParameterIndex: 0),
new SignatureHelpTestItem("void Foo.Bar(string s)", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(768697)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InstanceAndStaticMethodsShown2()
{
var markup = @"
class C
{
Foo Foo;
void M()
{
Foo.Bar($$"");
}
}
class Foo
{
public void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void Foo.Bar(int x)", currentParameterIndex: 0),
new SignatureHelpTestItem("void Foo.Bar(string s)", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(768697)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InstanceAndStaticMethodsShown3()
{
var markup = @"
class C
{
Foo Foo;
void M()
{
Foo.Bar($$
}
}
class Foo
{
public static void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void Foo.Bar(int x)", currentParameterIndex: 0),
new SignatureHelpTestItem("void Foo.Bar(string s)", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(768697)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InstanceAndStaticMethodsShown4()
{
var markup = @"
class C
{
void M()
{
Foo x;
x.Bar($$
}
}
class Foo
{
public static void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
Test(markup, expectedOrderedItems);
}
[WorkItem(768697)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InstanceAndStaticMethodsShown5()
{
var markup = @"
class C
{
void M()
{
Foo x;
x.Bar($$
}
}
class x { }
class Foo
{
public static void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
Test(markup, expectedOrderedItems);
}
[WorkItem(1067933)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InvokedWithNoToken()
{
var markup = @"
// foo($$";
Test(markup);
}
}
}
| |
/*
Copyright 2007-2013 The NGenerics Team
(https://github.com/ngenerics/ngenerics/wiki/Team)
This program is licensed under the GNU Lesser General Public License (LGPL). You should
have received a copy of the license along with the source code. If not, an online copy
of the license can be found at http://www.gnu.org/copyleft/lesser.html.
*/
/*
* The insertion and deletion code is based on the code found at http://eternallyconfuzzled.com/tuts/redblack.htm.
* It's an excellent tutorial - if you want to understand Red Black trees, look there first.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using NGenerics.Comparers;
using NGenerics.Patterns.Visitor;
namespace NGenerics.DataStructures.Trees
{
/// <summary>
/// An implementation of a Red-Black tree.
/// </summary>
/// <typeparam name="TKey">The type of the keys in the <see cref="RedBlackTree{TKey,TValue}"/>.</typeparam>
/// <typeparam name="TValue">The type of the values in the <see cref="RedBlackTree{TKey,TValue}"/>.</typeparam>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
#if (!SILVERLIGHT && !WINDOWSPHONE)
//[Serializable]
#endif
public class RedBlackTree<TKey, TValue> : RedBlackTree<KeyValuePair<TKey, TValue>>, IDictionary<TKey, TValue> // BinarySearchTreeBase<TKey, TValue>
{
#region Construction
/// <inheritdoc />
public RedBlackTree() : base(new KeyValuePairComparer<TKey, TValue>())
{
// Do nothing - the default Comparer will be used by the base class.
}
/// <inheritdoc/>
public RedBlackTree(IComparer<TKey> comparer)
: base(new KeyValuePairComparer<TKey, TValue>(comparer))
{
// Do nothing else.
}
/// <inheritdoc/>
public RedBlackTree(Comparison<TKey> comparison)
: base(new KeyValuePairComparer<TKey, TValue>(comparison))
{
// Do nothing else.
}
#endregion
#region Private Members
private RedBlackTreeNode<KeyValuePair<TKey, TValue>> FindNode(TKey key)
{
return base.FindNode(new KeyValuePair<TKey, TValue>(key, default(TValue))) as RedBlackTreeNode<KeyValuePair<TKey, TValue>>;
}
private bool Contains(KeyValuePair<TKey, TValue> item, bool checkValue) {
var node = FindNode(item);
if ((node != null) && !checkValue) {
return true;
}
return node != null && Equals(item.Value, node.Data.Value);
}
#endregion
#region IDictionary<TKey,TValue> Members
/// <summary>
/// Removes the element with the specified key from the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
/// <returns>
/// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="key"/> is null.
/// </exception>
/// <exception cref="T:System.NotSupportedException">
/// The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.
/// </exception>
public bool Remove(TKey key) {
return Remove(new KeyValuePair<TKey, TValue>(key, default(TValue)));
}
/// <summary>
/// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <param name="key">The object to use as the key of the element to add.</param>
/// <param name="value">The object to use as the value of the element to add.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="key"/> is null.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// An element with the same key already exists in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </exception>
/// <exception cref="T:System.NotSupportedException">
/// The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.
/// </exception>
public void Add(TKey key, TValue value) {
if (Equals(key, null))
{
throw new ArgumentNullException("key");
}
Add(new KeyValuePair<TKey,TValue>(key, value));
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.</param>
/// <returns>
/// true if the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the key; otherwise, false.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="key"/> is null.
/// </exception>
public bool ContainsKey(TKey key) {
return Contains(new KeyValuePair<TKey, TValue>(key, default(TValue)), false);
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <value></value>
/// <example>
/// <code source="..\..\Source\Examples\ExampleLibraryCSharp\DataStructures\Trees\BinarySearchTreeBaseExamples.cs" region="Keys" lang="cs" title="The following example shows how to use the Keys property."/>
/// <code source="..\..\Source\Examples\ExampleLibraryVB\DataStructures\Trees\BinarySearchTreeBaseExamples.vb" region="Keys" lang="vbnet" title="The following example shows how to use the Keys property."/>
/// </example>
public ICollection<TKey> Keys
{
get
{
// Get the keys in sorted order
var visitor = new KeyTrackingVisitor<TKey, TValue>();
var inOrderVisitor = new InOrderVisitor<KeyValuePair<TKey, TValue>>(visitor);
DepthFirstTraversal(inOrderVisitor);
return new ReadOnlyCollection<TKey>(visitor.TrackingList);
}
}
/// <inheritdoc />
/// <example>
/// <code source="..\..\Source\Examples\ExampleLibraryCSharp\DataStructures\Trees\BinarySearchTreeBaseExamples.cs" region="TryGetValue" lang="cs" title="The following example shows how to use the TryGetValue method."/>
/// <code source="..\..\Source\Examples\ExampleLibraryVB\DataStructures\Trees\BinarySearchTreeBaseExamples.vb" region="TryGetValue" lang="vbnet" title="The following example shows how to use the TryGetValue method."/>
/// </example>
public bool TryGetValue(TKey key, out TValue value)
{
var node = FindNode(new KeyValuePair<TKey, TValue>(key, default(TValue)));
if (node == null)
{
value = default(TValue);
return false;
}
value = node.Data.Value;
return true;
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <value></value>
/// <example>
/// <code source="..\..\Source\Examples\ExampleLibraryCSharp\DataStructures\Trees\BinarySearchTreeBaseExamples.cs" region="Values" lang="cs" title="The following example shows how to use the Values property."/>
/// <code source="..\..\Source\Examples\ExampleLibraryVB\DataStructures\Trees\BinarySearchTreeBaseExamples.vb" region="Values" lang="vbnet" title="The following example shows how to use the Values property."/>
/// </example>
public ICollection<TValue> Values
{
get
{
var visitor = new ValueTrackingVisitor<TKey, TValue>();
var inOrderVisitor = new InOrderVisitor<KeyValuePair<TKey, TValue>>(visitor);
DepthFirstTraversal(inOrderVisitor);
return new ReadOnlyCollection<TValue>(visitor.TrackingList);
}
}
/// <summary>
/// Gets or sets the value with the specified key.
/// </summary>
/// <value>The key of the item to set or get.</value>
public TValue this[TKey key]
{
get
{
var node = FindNode(key);
if (node == null)
{
throw new KeyNotFoundException("key");
}
return node.Data.Value;
}
set
{
var node = FindNode(key);
if (node == null)
{
throw new KeyNotFoundException("key");
}
node.Data = new KeyValuePair<TKey,TValue>(key, value);
}
}
#endregion
#region ICollection<KeyValuePair<TKey,TValue>> Members
/// <inheritdoc />
/// <example>
/// <code source="..\..\Source\Examples\ExampleLibraryCSharp\DataStructures\Trees\BinarySearchTreeBaseExamples.cs" region="Contains" lang="cs" title="The following example shows how to use the Contains method."/>
/// <code source="..\..\Source\Examples\ExampleLibraryVB\DataStructures\Trees\BinarySearchTreeBaseExamples.vb" region="Contains" lang="vbnet" title="The following example shows how to use the Contains method."/>
/// </example>
public override bool Contains(KeyValuePair<TKey, TValue> item) {
return Contains(item, true);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace HearthyWebApi.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using C1.Win.C1FlexGrid;
using PCSComUtils.Admin.BO;
using PCSComUtils.Admin.DS;
using PCSComUtils.Common;
using PCSComUtils.DataContext;
using PCSComUtils.PCSExc;
using PCSUtils.Log;
using PCSUtils.Utils;
namespace PCSUtils.Admin
{
/// <summary>
/// This class uses to manage all system menu.
/// </summary>
public class ManageMenu : Form
{
#region Controls
private Button btnClose;
private Button btnCopy;
private Button btnDelete;
private Button btnEdit;
private Button btnHelp;
private Button btnSave;
private ContextMenu cMenu;
private C1FlexGrid dgrdMenu;
private GroupBox grbDetails;
private GroupBox grbFunctions;
private Label lblCaptionDefault;
private Label lblCaptionJP;
private Label lblCaptionUS;
private Label lblCaptionVN;
private Label lblCopyFrom;
private Label lblFormat;
private Label lblMenuName;
private Label lblPrefix;
private Label lblShortcut;
private MenuItem miCopy;
private MenuItem miDelete;
private MenuItem miEdit;
private TextBox txtCaptionEN;
private TextBox txtCaptionJP;
private TextBox txtCaptionVN;
private TextBox txtFormat;
private TextBox txtMenuName;
private TextBox txtPrefix;
private TextBox txtShortcut;
#endregion
private const string THIS = "PCSUtils.Admin.ManageMenu";
/// <summary>
/// Required designer variable.
/// </summary>
private Container components;
#region Members
private const string FORMAT_COL = "colFormat";
private const int INT_POS_TREE = 1;
private const string IS_TRANSACTION_COL = "colIsTransaction";
private const string IS_USER_CREATED_COL = "colIsUserCreated";
private const string MAIN = "MAIN";
private const int MAX_LENGTH_CAPTION = 1000;
private const int MAX_LENGTH_DEFAULT = 1000;
private const string MENU_ENTRY_COL = "colMenuID";
private const string OPEN_QUOTE = " (";
private const string PREFIX_COL = "colPrefix";
private List<Sys_Menu_Entry> list = new List<Sys_Menu_Entry>();
private bool blnIsChanged;
private int intCurrentRow;
private EnumAction mFormMode = EnumAction.Default;
private Sys_Menu_Entry _sys_Menu_Entry;
public EnumAction FormMode
{
get { return mFormMode; }
set { mFormMode = value; }
}
public Sys_Menu_Entry Sys_Menu_Entry
{
get { return _sys_Menu_Entry; }
set { _sys_Menu_Entry = value; }
}
#endregion
public ManageMenu()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
/// <summary>
/// Load data from a sys_menu_entry to form
/// </summary>
/// <param name="pvoMenuEntry">Sys_Menu_EntryVO object</param>
/// private void LoadDataToForm(Sys_Menu_EntryVO pvoMenuEntry)
private void LoadDataToForm(Sys_Menu_Entry objMenuEntry)
{
if (objMenuEntry != null)
{
txtMenuName.Text = objMenuEntry.Text_CaptionDefault;
txtCaptionEN.Text = objMenuEntry.Text_Caption_EN_US;
txtCaptionVN.Text = objMenuEntry.Text_Caption_VI_VN;
txtCaptionJP.Text = objMenuEntry.Text_Caption_JA_JP;
txtShortcut.Text = objMenuEntry.Shortcut;
txtPrefix.Text = objMenuEntry.Prefix;
txtFormat.Text = objMenuEntry.TransFormat;
btnCopy.Enabled = true;
}
}
/// <summary>
/// Enable/Disable button based on selected menu
/// </summary>
private void EnableControls(bool pblnEnable)
{
btnSave.Enabled = txtFormat.Enabled = txtPrefix.Enabled = pblnEnable;
txtMenuName.Enabled = txtCaptionEN.Enabled = txtCaptionVN.Enabled = pblnEnable;
}
/// <summary>
/// Set width column, column number, set styte for c1FlexGridProtect
/// this function will be executed only one time when the form is loaded.
/// </summary>
private void SetProtectFormat()
{
// Set Tree column
dgrdMenu.Tree.Column = INT_POS_TREE;
//dgrdMenu.Cols[0].Width = COLUMN_WIDTH_BASE;
//dgrdMenu.Cols[INT_POS_TREE].Width = COLUMN_WIDTH_BASE * 10;
}
/// <summary>
/// Load data from arrList into TreeProtect, This function
/// will build the tree, get data from collection arrStorePermission.
/// RoleProtectionForm_Load and c1FlexGridRole_AfterRowColChange will call this function.
/// </summary>
/// <param name="c1FlexGridProtect"></param>
/// <param name="pstrShortcut"></param>
/// <param name="pintLevel"></param>
/// <Author> Son HT, Dec 30, 2004</Author>
private void LoadTreeProtect(ref C1FlexGrid c1FlexGridProtect, string pstrShortcut, int pintLevel)
{
// Scan all rows in Sys_Menu_Entry table to build tree
//arrSysMenuEntry.Sort(this);
foreach (Sys_Menu_Entry voMenu in list)
{
// if this item is child node of current
// as well as if it is a function with no form loaded or the formloaded is not right depended
if ((voMenu.Parent_Shortcut != null && voMenu.Parent_Shortcut.Equals(pstrShortcut)))
// && (voMenu.Parent_Child != (int)MenuParentChildEnum.SpecialLeafMenu))
{
// Root Node
intCurrentRow++;
Node objNode = c1FlexGridProtect.Rows.InsertNode(intCurrentRow, pintLevel);
string strLangName = CultureInfo.CurrentUICulture.Name;
string strText = voMenu.Text_CaptionDefault;
switch (strLangName)
{
case Constants.CULTURE_VN:
strText = voMenu.Text_Caption_VI_VN;
break;
case Constants.CULTURE_JP:
strText = voMenu.Text_Caption_JA_JP;
break;
default:
strText = voMenu.Text_CaptionDefault;
break;
}
// Set Text for tree node
c1FlexGridProtect[intCurrentRow, INT_POS_TREE] = strText;
c1FlexGridProtect[intCurrentRow, PREFIX_COL] = voMenu.Prefix;
c1FlexGridProtect[intCurrentRow, FORMAT_COL] = voMenu.TransFormat;
c1FlexGridProtect[intCurrentRow, MENU_ENTRY_COL] = voMenu.Menu_EntryID;
c1FlexGridProtect[intCurrentRow, IS_TRANSACTION_COL] = voMenu.IsTransaction;
c1FlexGridProtect[intCurrentRow, IS_USER_CREATED_COL] = voMenu.IsUserCreated;
// Recursion build child node
LoadTreeProtect(ref c1FlexGridProtect, voMenu.Shortcut, pintLevel + 1);
if (objNode.Level == 0)
{
objNode.Collapsed = true;
}
//objNode.Data = voMenuEntry;
}
}
}
/// <summary>
/// Validate data before save
/// </summary>
/// <returns>True if succeed, False if failure</returns>
private bool ValidateData()
{
if (lblPrefix.ForeColor == Color.Maroon && txtPrefix.Text.Trim() == string.Empty)
{
string[] strMsg = { lblPrefix.Text };
PCSMessageBox.Show(ErrorCode.MESSAGE_MANDATORY_FIELD_REQUIRED, MessageBoxIcon.Error, strMsg);
txtPrefix.Focus();
return false;
}
if (dgrdMenu.Rows[dgrdMenu.Row].Node == null)
return false;
return true;
}
/// <summary>
/// Save data to database
/// </summary>
/// <returns>True if succeed. False if failure</returns>
private bool SaveData()
{
Node objSelectedNode = null;
try
{
objSelectedNode = dgrdMenu.Rows[intCurrentRow].Node;
}
catch
{
return false;
}
if (objSelectedNode == null)
{
return false;
}
var boManageMenu = new ManageMenuBO();
Sys_Menu_Entry menu = new Sys_Menu_Entry();
string strPrefix = txtPrefix.Text.Trim();
string strFormat = txtFormat.Text.Trim();
if (strPrefix != string.Empty)
{
switch (mFormMode)
{
case EnumAction.Add:
menu.Text_CaptionDefault = string.Format("{0} ({1})", txtMenuName.Text.Trim(), strPrefix);
menu.Text_Caption_EN_US = string.Format("{0} ({1})", txtCaptionEN.Text.Trim(), strPrefix);
menu.Text_Caption_JA_JP = string.Format("{0} ({1})", txtCaptionEN.Text.Trim(), strPrefix);
menu.Text_Caption_VI_VN = string.Format("{0} ({1})", txtCaptionVN.Text.Trim(), strPrefix);
menu.Shortcut = string.Format("{0} ({1})", txtShortcut.Text, strPrefix);
break;
case EnumAction.Edit:
#region Text_CaptionDefault
int intPos = txtMenuName.Text.Trim().IndexOf(OPEN_QUOTE);
Sys_Menu_Entry.Text_CaptionDefault = intPos > 0 ? txtMenuName.Text.Trim().Remove(intPos, txtMenuName.Text.Trim().Length - intPos).Trim() : txtMenuName.Text.Trim();
Sys_Menu_Entry.Text_CaptionDefault = string.Format("{0} ({1})", Sys_Menu_Entry.Text_CaptionDefault, strPrefix);
menu.Text_CaptionDefault = Sys_Menu_Entry.Text_CaptionDefault;
#endregion
#region Text_Caption_EN_US
intPos = txtCaptionEN.Text.Trim().IndexOf(OPEN_QUOTE);
Sys_Menu_Entry.Text_Caption_EN_US = intPos > 0 ? txtCaptionEN.Text.Trim().Remove(intPos, txtCaptionEN.Text.Trim().Length - intPos).Trim() : txtCaptionEN.Text.Trim();
Sys_Menu_Entry.Text_Caption_EN_US = string.Format("{0} ({1})", Sys_Menu_Entry.Text_Caption_EN_US, strPrefix);
menu.Text_Caption_EN_US = Sys_Menu_Entry.Text_Caption_EN_US;
#endregion
#region Text_Caption_JA_JP
intPos = Sys_Menu_Entry.Text_Caption_JA_JP.IndexOf(OPEN_QUOTE);
Sys_Menu_Entry.Text_Caption_JA_JP = intPos > 0 ? Sys_Menu_Entry.Text_Caption_JA_JP.Remove(intPos, Sys_Menu_Entry.Text_Caption_JA_JP.Length - intPos).Trim() : Sys_Menu_Entry.Text_Caption_JA_JP;
Sys_Menu_Entry.Text_Caption_EN_US = string.Format("{0} ({1})", Sys_Menu_Entry.Text_Caption_EN_US, strPrefix);
menu.Text_Caption_JA_JP = Sys_Menu_Entry.Text_Caption_JA_JP;
#endregion
#region Text_Caption_Vi_VN
intPos = txtCaptionVN.Text.Trim().IndexOf(OPEN_QUOTE);
Sys_Menu_Entry.Text_Caption_VI_VN = intPos > 0 ? txtCaptionVN.Text.Trim().Remove(intPos, txtCaptionVN.Text.Trim().Length - intPos).Trim() : txtCaptionVN.Text.Trim();
Sys_Menu_Entry.Text_Caption_VI_VN = string.Format("{0} ({1})", Sys_Menu_Entry.Text_Caption_VI_VN, strPrefix);
menu.Text_Caption_VI_VN = Sys_Menu_Entry.Text_Caption_VI_VN;
#endregion
#region Shortcut
intPos = Sys_Menu_Entry.Shortcut.IndexOf(OPEN_QUOTE);
if (intPos > 0)
{
Sys_Menu_Entry.Shortcut = Sys_Menu_Entry.Shortcut.Remove(intPos, Sys_Menu_Entry.Shortcut.Length - intPos).Trim();
}
Sys_Menu_Entry.Shortcut = string.Format("{0} ({1})", Sys_Menu_Entry.Shortcut, strPrefix);
menu.Shortcut = Sys_Menu_Entry.Shortcut;
#endregion
menu.Menu_EntryID = Sys_Menu_Entry.Menu_EntryID;
break;
}
}
if (Sys_Menu_Entry.Text_CaptionDefault.Length > MAX_LENGTH_CAPTION)
{
string[] strMsg = { lblCaptionDefault.Text };
PCSMessageBox.Show(ErrorCode.MESSAGE_VALUE_TOO_LONG, MessageBoxIcon.Exclamation, strMsg);
return false;
}
if (Sys_Menu_Entry.Text_Caption_EN_US.Length > MAX_LENGTH_CAPTION)
{
string[] strMsg = { lblCaptionUS.Text };
PCSMessageBox.Show(ErrorCode.MESSAGE_VALUE_TOO_LONG, MessageBoxIcon.Exclamation, strMsg);
return false;
}
if (Sys_Menu_Entry.Text_Caption_JA_JP.Length > MAX_LENGTH_DEFAULT)
{
string[] strMsg = { lblCaptionJP.Text };
PCSMessageBox.Show(ErrorCode.MESSAGE_VALUE_TOO_LONG, MessageBoxIcon.Exclamation, strMsg);
return false;
}
if (Sys_Menu_Entry.Text_Caption_VI_VN.Length > MAX_LENGTH_CAPTION)
{
string[] strMsg = { lblCaptionVN.Text };
PCSMessageBox.Show(ErrorCode.MESSAGE_VALUE_TOO_LONG, MessageBoxIcon.Exclamation, strMsg);
return false;
}
Sys_Menu_Entry.Prefix = strPrefix;
menu.Prefix = strPrefix;
Sys_Menu_Entry.TransFormat = strFormat;
menu.TransFormat = strFormat;
menu.Parent_Shortcut = Sys_Menu_Entry.Parent_Shortcut;
menu.IsTransaction = Sys_Menu_Entry.IsTransaction;
menu.IsUserCreated = Sys_Menu_Entry.IsUserCreated;
menu.Type = Sys_Menu_Entry.Type;
menu.FormLoad = Sys_Menu_Entry.FormLoad;
menu.Text_Caption_Language_Default = Sys_Menu_Entry.Text_Caption_Language_Default;
menu.Button_Caption = Sys_Menu_Entry.Button_Caption;
switch (mFormMode)
{
case EnumAction.Add:
Sys_Menu_Entry.IsUserCreated = 1;
menu.IsUserCreated = 1;
Sys_Menu_Entry.Menu_EntryID = boManageMenu.AddAndReturnID(menu, SystemProperty.RoleID);
intCurrentRow += 1;
// insert new node to grid
dgrdMenu.Rows.InsertNode(intCurrentRow, objSelectedNode.Level);
// sets Text for tree node
dgrdMenu[intCurrentRow, INT_POS_TREE] = menu.Text_CaptionDefault;
dgrdMenu[intCurrentRow, PREFIX_COL] = menu.Prefix;
dgrdMenu[intCurrentRow, FORMAT_COL] = menu.TransFormat;
dgrdMenu[intCurrentRow, MENU_ENTRY_COL] = menu.Menu_EntryID;
dgrdMenu[intCurrentRow, IS_TRANSACTION_COL] = menu.IsTransaction;
dgrdMenu[intCurrentRow, IS_USER_CREATED_COL] = menu.IsUserCreated;
break;
case EnumAction.Edit:
menu.Menu_EntryID = Sys_Menu_Entry.Menu_EntryID;
boManageMenu.UpdateTrans(menu, SystemProperty.RoleID);
// sets Text for tree node
dgrdMenu[intCurrentRow, PREFIX_COL] = menu.Prefix;
dgrdMenu[intCurrentRow, FORMAT_COL] = menu.TransFormat;
dgrdMenu[intCurrentRow, INT_POS_TREE] = menu.Text_CaptionDefault;
break;
}
return true;
}
/// <summary>
/// Check securtiy and load all menu to the tree
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ManageMenu_Load(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".ManageMenu_Load()";
try
{
#region Security
//Set authorization for user
var objSecurity = new Security();
Name = THIS;
if (objSecurity.SetRightForUserOnForm(this, SystemProperty.UserName) == 0)
{
Close();
// You don't have the right to view this item
PCSMessageBox.Show(ErrorCode.MESSAGE_YOU_HAVE_NO_RIGHT_TO_VIEW, MessageBoxIcon.Warning);
return;
}
#endregion
ManageMenuBO bo = new ManageMenuBO();
list = bo.GetMenuAll();
// set table Protect format
SetProtectFormat();
// Current row that system create row when Load tree data
intCurrentRow = 0;
LoadTreeProtect(ref dgrdMenu, MAIN, intCurrentRow);
// invisible unneeded column
dgrdMenu.Cols[MENU_ENTRY_COL].Visible = false;
dgrdMenu.Cols[IS_USER_CREATED_COL].Visible = false;
EnableControls(false);
txtPrefix.CharacterCasing = CharacterCasing.Upper;
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Make a copy of selected menu
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void miCopy_Click(object sender, EventArgs e)
{
// Code Inserted Automatically
#region Code Inserted Automatically
Cursor = Cursors.WaitCursor;
#endregion Code Inserted Automatically
btnCopy_Click(null, null);
// Code Inserted Automatically
#region Code Inserted Automatically
Cursor = Cursors.Default;
#endregion Code Inserted Automatically
}
/// <summary>
/// Edit selected menu information
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void miEdit_Click(object sender, EventArgs e)
{
// Code Inserted Automatically
#region Code Inserted Automatically
Cursor = Cursors.WaitCursor;
#endregion Code Inserted Automatically
btnEdit_Click(null, null);
// Code Inserted Automatically
#region Code Inserted Automatically
Cursor = Cursors.Default;
#endregion Code Inserted Automatically
}
/// <summary>
/// Delete selected menu
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void miDelete_Click(object sender, EventArgs e)
{
// Code Inserted Automatically
#region Code Inserted Automatically
Cursor = Cursors.WaitCursor;
#endregion Code Inserted Automatically
btnDelete_Click(null, null);
// Code Inserted Automatically
#region Code Inserted Automatically
Cursor = Cursors.Default;
#endregion Code Inserted Automatically
}
/// <summary>
/// Make a copy of selected menu
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCopy_Click(object sender, EventArgs e)
{
// Code Inserted Automatically
#region Code Inserted Automatically
Cursor = Cursors.WaitCursor;
#endregion Code Inserted Automatically
const string METHOD_NAME = THIS + ".btnCopy_Click()";
try
{
int intSelectedID = 0;
try
{
intSelectedID = int.Parse(dgrdMenu[intCurrentRow, MENU_ENTRY_COL].ToString());
}
catch
{
}
if (intSelectedID == 0 || Sys_Menu_Entry == null)
{
// Code Inserted Automatically
#region Code Inserted Automatically
Cursor = Cursors.Default;
#endregion Code Inserted Automatically
return;
}
mFormMode = EnumAction.Add;
// load data to form
LoadDataToForm(Sys_Menu_Entry);
// enable controls
EnableControls(true);
btnDelete.Enabled = btnCopy.Enabled = btnEdit.Enabled = false;
lblCopyFrom.Visible = true;
lblMenuName.Visible = false;
// focus on Prefix TextBox
txtPrefix.Focus();
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// Code Inserted Automatically
#region Code Inserted Automatically
Cursor = Cursors.Default;
#endregion Code Inserted Automatically
}
/// <summary>
/// Edit selected menu information
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnEdit_Click(object sender, EventArgs e)
{
// Code Inserted Automatically
#region Code Inserted Automatically
Cursor = Cursors.WaitCursor;
#endregion Code Inserted Automatically
const string METHOD_NAME = THIS + ".btnEdit_Click()";
try
{
int intSelectedID = 0;
try
{
intSelectedID = int.Parse(dgrdMenu[dgrdMenu.Row, MENU_ENTRY_COL].ToString());
}
catch
{
}
if (intSelectedID == 0 || Sys_Menu_Entry == null)
{
// Code Inserted Automatically
#region Code Inserted Automatically
Cursor = Cursors.Default;
#endregion Code Inserted Automatically
return;
}
mFormMode = EnumAction.Edit;
// load data to form
LoadDataToForm(Sys_Menu_Entry);
// enable controls
EnableControls(true);
txtMenuName.ReadOnly = txtCaptionEN.ReadOnly = txtCaptionVN.ReadOnly = (Sys_Menu_Entry.IsUserCreated <= 0);
lblCopyFrom.Visible = false;
lblMenuName.Visible = true;
btnDelete.Enabled = btnCopy.Enabled = btnEdit.Enabled = false;
// focus on Prefix TextBox
txtPrefix.Focus();
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// Code Inserted Automatically
#region Code Inserted Automatically
Cursor = Cursors.Default;
#endregion Code Inserted Automatically
}
/// <summary>
/// Delete selected menu
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDelete_Click(object sender, EventArgs e)
{
// Code Inserted Automatically
#region Code Inserted Automatically
Cursor = Cursors.WaitCursor;
#endregion Code Inserted Automatically
const string METHOD_NAME = THIS + ".btnDelete_Click()";
try
{
int intSelectedID = 0;
try
{
intSelectedID = int.Parse(dgrdMenu[dgrdMenu.Row, MENU_ENTRY_COL].ToString());
}
catch
{
}
if (intSelectedID == 0 )
{
// Code Inserted Automatically
#region Code Inserted Automatically
Cursor = Cursors.Default;
#endregion Code Inserted Automatically
return;
}
// ask user to confirm
DialogResult dlgResult = PCSMessageBox.Show(ErrorCode.MESSAGE_DELETE_RECORD, MessageBoxButtons.OKCancel,
MessageBoxIcon.Question);
if (dlgResult == DialogResult.OK)
{
var boManageMenu = new ManageMenuBO();
boManageMenu.Delete(intSelectedID);
FormControlComponents.ClearForm(this);
// reload the form
int intIndex = dgrdMenu.Row;
dgrdMenu.Rows.Remove(intIndex);
dgrdMenu.Row = intIndex;
dgrdMenu_RowColChange(null, null);
blnIsChanged = true;
}
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// Code Inserted Automatically
#region Code Inserted Automatically
Cursor = Cursors.Default;
#endregion Code Inserted Automatically
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnHelp_Click(object sender, EventArgs e)
{
// Code Inserted Automatically
#region Code Inserted Automatically
Cursor = Cursors.WaitCursor;
#endregion Code Inserted Automatically
// Code Inserted Automatically
#region Code Inserted Automatically
Cursor = Cursors.Default;
#endregion Code Inserted Automatically
}
/// <summary>
/// Close the form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnClose_Click(object sender, EventArgs e)
{
// Code Inserted Automatically
#region Code Inserted Automatically
Cursor = Cursors.WaitCursor;
#endregion Code Inserted Automatically
Close();
// Code Inserted Automatically
#region Code Inserted Automatically
Cursor = Cursors.Default;
#endregion Code Inserted Automatically
}
/// <summary>
/// Validate data and save changes to database
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSave_Click(object sender, EventArgs e)
{
// Code Inserted Automatically
#region Code Inserted Automatically
Cursor = Cursors.WaitCursor;
#endregion Code Inserted Automatically
const string METHOD_NAME = THIS + ".btnSave_Click()";
try
{
if (!ValidateData())
{
// Code Inserted Automatically
#region Code Inserted Automatically
Cursor = Cursors.Default;
#endregion Code Inserted Automatically
return;
}
if (SaveData())
{
PCSMessageBox.Show(ErrorCode.MESSAGE_AFTER_SAVE_DATA);
mFormMode = EnumAction.Default;
// disable control
EnableControls(false);
dgrdMenu.Row = intCurrentRow;
btnEdit.Enabled = true;
btnCopy.Enabled = (Sys_Menu_Entry.IsTransaction > 0 && Sys_Menu_Entry.IsUserCreated == 0);
btnDelete.Enabled = (Sys_Menu_Entry.IsUserCreated > 0);
dgrdMenu_RowColChange(null, null);
blnIsChanged = true;
}
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// Code Inserted Automatically
#region Code Inserted Automatically
Cursor = Cursors.Default;
#endregion Code Inserted Automatically
}
/// <summary>
/// When user change the selection, get the selecetd object
/// in order to enable/disable related buttons
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dgrdMenu_RowColChange(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".dgrdMenu_RowColChange()";
try
{
int intIsTransaction = 0;
int intIsUserCreated = 0;
try
{
if (dgrdMenu[dgrdMenu.Row, IS_USER_CREATED_COL] != DBNull.Value)
{
intIsUserCreated = int.Parse(dgrdMenu[dgrdMenu.Row, IS_USER_CREATED_COL].ToString());
}
}
catch
{
}
try
{
intIsTransaction =
Convert.ToInt32(Convert.ToBoolean(dgrdMenu[dgrdMenu.Row, IS_TRANSACTION_COL].ToString()));
}
catch
{
}
if (intIsUserCreated > 0)
{
// allows user to delete copied menu
btnDelete.Enabled = miDelete.Enabled = true;
// prefix is mandatory
lblPrefix.ForeColor = Color.Maroon;
}
else
{
// not allows user to delete original menu
btnDelete.Enabled = miDelete.Enabled = false;
// prefix is not mandatory
lblPrefix.ForeColor = Color.Black;
}
// selected menu is the transaction menu
// allows user to copy/edit this menu
btnEdit.Enabled = miEdit.Enabled = (intIsTransaction > 0);
btnCopy.Enabled = miCopy.Enabled = (intIsTransaction > 0 && intIsUserCreated == 0);
// get the selected menu
int intSelectedID = 0;
try
{
intSelectedID = int.Parse(dgrdMenu[dgrdMenu.Row, MENU_ENTRY_COL].ToString());
}
catch
{
}
if (intSelectedID == 0)
return;
var boManageMenu = new ManageMenuBO();
Sys_Menu_Entry = boManageMenu.GetMenu(intSelectedID);
LoadDataToForm(Sys_Menu_Entry);
lblCopyFrom.Visible = false;
lblMenuName.Visible = true;
EnableControls(false);
btnEdit.Enabled = true;
btnDelete.Enabled = true;
intCurrentRow = dgrdMenu.Row;
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// When the form is closing, if user made any changes, ask them to confirm
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ManageMenu_Closing(object sender, CancelEventArgs e)
{
const string METHOD_NAME = THIS + ".ManageMenu_Closing()";
try
{
if (mFormMode != EnumAction.Default)
{
DialogResult confirmDialog = PCSMessageBox.Show(ErrorCode.MESSAGE_QUESTION_STORE_INTO_DATABASE,
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Question);
switch (confirmDialog)
{
case DialogResult.Yes:
try
{
if (!ValidateData())
{
txtPrefix.Focus();
e.Cancel = true;
}
else if (!SaveData())
{
txtPrefix.Focus();
e.Cancel = true;
}
else
{
PCSMessageBox.Show(ErrorCode.MESSAGE_AFTER_SAVE_DATA);
mFormMode = EnumAction.Default;
// disable control
EnableControls(false);
btnEdit.Enabled = true;
btnCopy.Enabled = (Sys_Menu_Entry.IsTransaction > 0 && Sys_Menu_Entry.IsUserCreated == 0);
btnDelete.Enabled = (Sys_Menu_Entry.IsUserCreated > 0);
blnIsChanged = true;
}
}
catch
{
txtPrefix.Focus();
e.Cancel = true;
}
break;
case DialogResult.Cancel:
txtPrefix.Focus();
e.Cancel = true;
break;
}
}
// check if user made any changes to the menu
// ask them to re-login to get new menu
if (blnIsChanged && !e.Cancel)
{
// display alert message
PCSMessageBox.Show(ErrorCode.MESSAGE_APPLY_NEW_MENU, MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Sets the selected row and col for grid
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dgrdMenu_MouseDown(object sender, MouseEventArgs e)
{
try
{
if (e.Button == MouseButtons.Right)
{
HitTestInfo hiClicked = dgrdMenu.HitTest(e.X, e.Y);
intCurrentRow = dgrdMenu.Row = hiClicked.Row;
dgrdMenu.Col = hiClicked.Column;
}
}
catch
{
}
}
/// <summary>
/// Before move to another row, check the form mode to ask user want to save the changes
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dgrdMenu_BeforeRowColChange(object sender, RangeEventArgs e)
{
const string METHOD_NAME = THIS + ".dgrdMenu_BeforeRowColChange()";
try
{
if (mFormMode != EnumAction.Default)
{
DialogResult confirmDialog = PCSMessageBox.Show(ErrorCode.MESSAGE_QUESTION_STORE_INTO_DATABASE,
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Question);
switch (confirmDialog)
{
case DialogResult.Yes:
try
{
if (!ValidateData())
{
txtPrefix.Focus();
e.Cancel = true;
}
else if (!SaveData())
{
txtPrefix.Focus();
e.Cancel = true;
}
else
{
PCSMessageBox.Show(ErrorCode.MESSAGE_AFTER_SAVE_DATA);
mFormMode = EnumAction.Default;
// disable control
EnableControls(false);
btnEdit.Enabled = true;
btnCopy.Enabled = (Sys_Menu_Entry.IsTransaction > 0 && Sys_Menu_Entry.IsUserCreated == 0);
btnDelete.Enabled = (Sys_Menu_Entry.IsUserCreated > 0);
blnIsChanged = true;
}
}
catch
{
txtPrefix.Focus();
e.Cancel = true;
}
break;
case DialogResult.No:
// clear the form
FormControlComponents.ClearForm(this);
mFormMode = EnumAction.Default;
break;
case DialogResult.Cancel:
txtPrefix.Focus();
e.Cancel = true;
break;
}
}
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ManageMenu));
this.btnCopy = new System.Windows.Forms.Button();
this.btnEdit = new System.Windows.Forms.Button();
this.btnHelp = new System.Windows.Forms.Button();
this.btnDelete = new System.Windows.Forms.Button();
this.btnClose = new System.Windows.Forms.Button();
this.grbFunctions = new System.Windows.Forms.GroupBox();
this.dgrdMenu = new C1.Win.C1FlexGrid.C1FlexGrid();
this.cMenu = new System.Windows.Forms.ContextMenu();
this.miCopy = new System.Windows.Forms.MenuItem();
this.miEdit = new System.Windows.Forms.MenuItem();
this.miDelete = new System.Windows.Forms.MenuItem();
this.btnSave = new System.Windows.Forms.Button();
this.grbDetails = new System.Windows.Forms.GroupBox();
this.lblCaptionDefault = new System.Windows.Forms.Label();
this.txtMenuName = new System.Windows.Forms.TextBox();
this.txtFormat = new System.Windows.Forms.TextBox();
this.txtPrefix = new System.Windows.Forms.TextBox();
this.txtCaptionEN = new System.Windows.Forms.TextBox();
this.txtCaptionJP = new System.Windows.Forms.TextBox();
this.txtShortcut = new System.Windows.Forms.TextBox();
this.txtCaptionVN = new System.Windows.Forms.TextBox();
this.lblFormat = new System.Windows.Forms.Label();
this.lblPrefix = new System.Windows.Forms.Label();
this.lblCaptionUS = new System.Windows.Forms.Label();
this.lblCaptionVN = new System.Windows.Forms.Label();
this.lblMenuName = new System.Windows.Forms.Label();
this.lblCopyFrom = new System.Windows.Forms.Label();
this.lblCaptionJP = new System.Windows.Forms.Label();
this.lblShortcut = new System.Windows.Forms.Label();
this.grbFunctions.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dgrdMenu)).BeginInit();
this.grbDetails.SuspendLayout();
this.SuspendLayout();
//
// btnCopy
//
resources.ApplyResources(this.btnCopy, "btnCopy");
this.btnCopy.Name = "btnCopy";
this.btnCopy.Click += new System.EventHandler(this.btnCopy_Click);
//
// btnEdit
//
resources.ApplyResources(this.btnEdit, "btnEdit");
this.btnEdit.Name = "btnEdit";
this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click);
//
// btnHelp
//
resources.ApplyResources(this.btnHelp, "btnHelp");
this.btnHelp.Name = "btnHelp";
this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click);
//
// btnDelete
//
resources.ApplyResources(this.btnDelete, "btnDelete");
this.btnDelete.Name = "btnDelete";
this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
//
// btnClose
//
resources.ApplyResources(this.btnClose, "btnClose");
this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnClose.Name = "btnClose";
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// grbFunctions
//
resources.ApplyResources(this.grbFunctions, "grbFunctions");
this.grbFunctions.Controls.Add(this.dgrdMenu);
this.grbFunctions.Name = "grbFunctions";
this.grbFunctions.TabStop = false;
//
// dgrdMenu
//
this.dgrdMenu.AllowEditing = false;
this.dgrdMenu.AllowSorting = C1.Win.C1FlexGrid.AllowSortingEnum.None;
resources.ApplyResources(this.dgrdMenu, "dgrdMenu");
this.dgrdMenu.ContextMenu = this.cMenu;
this.dgrdMenu.Name = "dgrdMenu";
this.dgrdMenu.Rows.Count = 1;
this.dgrdMenu.Rows.DefaultSize = 17;
this.dgrdMenu.StyleInfo = resources.GetString("dgrdMenu.StyleInfo");
this.dgrdMenu.Tree.Column = 1;
this.dgrdMenu.Tree.Indent = 10;
this.dgrdMenu.BeforeRowColChange += new C1.Win.C1FlexGrid.RangeEventHandler(this.dgrdMenu_BeforeRowColChange);
this.dgrdMenu.RowColChange += new System.EventHandler(this.dgrdMenu_RowColChange);
this.dgrdMenu.MouseDown += new System.Windows.Forms.MouseEventHandler(this.dgrdMenu_MouseDown);
//
// cMenu
//
this.cMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.miCopy,
this.miEdit,
this.miDelete});
//
// miCopy
//
this.miCopy.Index = 0;
resources.ApplyResources(this.miCopy, "miCopy");
this.miCopy.Click += new System.EventHandler(this.miCopy_Click);
//
// miEdit
//
this.miEdit.Index = 1;
resources.ApplyResources(this.miEdit, "miEdit");
this.miEdit.Click += new System.EventHandler(this.miEdit_Click);
//
// miDelete
//
this.miDelete.Index = 2;
resources.ApplyResources(this.miDelete, "miDelete");
this.miDelete.Click += new System.EventHandler(this.miDelete_Click);
//
// btnSave
//
resources.ApplyResources(this.btnSave, "btnSave");
this.btnSave.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnSave.Name = "btnSave";
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// grbDetails
//
resources.ApplyResources(this.grbDetails, "grbDetails");
this.grbDetails.Controls.Add(this.lblCaptionDefault);
this.grbDetails.Controls.Add(this.txtMenuName);
this.grbDetails.Controls.Add(this.txtFormat);
this.grbDetails.Controls.Add(this.txtPrefix);
this.grbDetails.Controls.Add(this.txtCaptionEN);
this.grbDetails.Controls.Add(this.txtCaptionJP);
this.grbDetails.Controls.Add(this.txtShortcut);
this.grbDetails.Controls.Add(this.txtCaptionVN);
this.grbDetails.Controls.Add(this.lblFormat);
this.grbDetails.Controls.Add(this.lblPrefix);
this.grbDetails.Controls.Add(this.lblCaptionUS);
this.grbDetails.Controls.Add(this.lblCaptionVN);
this.grbDetails.Controls.Add(this.lblMenuName);
this.grbDetails.Controls.Add(this.lblCopyFrom);
this.grbDetails.Controls.Add(this.lblCaptionJP);
this.grbDetails.Name = "grbDetails";
this.grbDetails.TabStop = false;
//
// lblCaptionDefault
//
resources.ApplyResources(this.lblCaptionDefault, "lblCaptionDefault");
this.lblCaptionDefault.Name = "lblCaptionDefault";
//
// txtMenuName
//
resources.ApplyResources(this.txtMenuName, "txtMenuName");
this.txtMenuName.Name = "txtMenuName";
//
// txtFormat
//
resources.ApplyResources(this.txtFormat, "txtFormat");
this.txtFormat.Name = "txtFormat";
//
// txtPrefix
//
resources.ApplyResources(this.txtPrefix, "txtPrefix");
this.txtPrefix.Name = "txtPrefix";
//
// txtCaptionEN
//
resources.ApplyResources(this.txtCaptionEN, "txtCaptionEN");
this.txtCaptionEN.Name = "txtCaptionEN";
//
// txtCaptionJP
//
resources.ApplyResources(this.txtCaptionJP, "txtCaptionJP");
this.txtCaptionJP.Name = "txtCaptionJP";
this.txtCaptionJP.ReadOnly = true;
//
// txtShortcut
//
resources.ApplyResources(this.txtShortcut, "txtShortcut");
this.txtShortcut.Name = "txtShortcut";
this.txtShortcut.ReadOnly = true;
//
// txtCaptionVN
//
resources.ApplyResources(this.txtCaptionVN, "txtCaptionVN");
this.txtCaptionVN.Name = "txtCaptionVN";
//
// lblFormat
//
resources.ApplyResources(this.lblFormat, "lblFormat");
this.lblFormat.Name = "lblFormat";
//
// lblPrefix
//
this.lblPrefix.ForeColor = System.Drawing.Color.Maroon;
resources.ApplyResources(this.lblPrefix, "lblPrefix");
this.lblPrefix.Name = "lblPrefix";
//
// lblCaptionUS
//
resources.ApplyResources(this.lblCaptionUS, "lblCaptionUS");
this.lblCaptionUS.Name = "lblCaptionUS";
//
// lblCaptionVN
//
resources.ApplyResources(this.lblCaptionVN, "lblCaptionVN");
this.lblCaptionVN.Name = "lblCaptionVN";
//
// lblMenuName
//
resources.ApplyResources(this.lblMenuName, "lblMenuName");
this.lblMenuName.Name = "lblMenuName";
//
// lblCopyFrom
//
resources.ApplyResources(this.lblCopyFrom, "lblCopyFrom");
this.lblCopyFrom.Name = "lblCopyFrom";
//
// lblCaptionJP
//
resources.ApplyResources(this.lblCaptionJP, "lblCaptionJP");
this.lblCaptionJP.Name = "lblCaptionJP";
//
// lblShortcut
//
resources.ApplyResources(this.lblShortcut, "lblShortcut");
this.lblShortcut.Name = "lblShortcut";
//
// ManageMenu
//
resources.ApplyResources(this, "$this");
this.CancelButton = this.btnClose;
this.Controls.Add(this.grbDetails);
this.Controls.Add(this.btnSave);
this.Controls.Add(this.grbFunctions);
this.Controls.Add(this.btnHelp);
this.Controls.Add(this.btnDelete);
this.Controls.Add(this.btnEdit);
this.Controls.Add(this.btnCopy);
this.Controls.Add(this.btnClose);
this.Controls.Add(this.lblShortcut);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.KeyPreview = true;
this.Name = "ManageMenu";
this.Closing += new System.ComponentModel.CancelEventHandler(this.ManageMenu_Closing);
this.Load += new System.EventHandler(this.ManageMenu_Load);
this.grbFunctions.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dgrdMenu)).EndInit();
this.grbDetails.ResumeLayout(false);
this.grbDetails.PerformLayout();
this.ResumeLayout(false);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using Encoding = System.Text.Encoding;
using Microsoft.Reflection;
#if ES_BUILD_STANDALONE
using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment;
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
/// <summary>
/// TraceLogging: Constants and utility functions.
/// </summary>
internal static class Statics
{
#region Constants
public const byte DefaultLevel = 5;
public const byte TraceLoggingChannel = 0xb;
public const byte InTypeMask = 31;
public const byte InTypeFixedCountFlag = 32;
public const byte InTypeVariableCountFlag = 64;
public const byte InTypeCustomCountFlag = 96;
public const byte InTypeCountMask = 96;
public const byte InTypeChainFlag = 128;
public const byte OutTypeMask = 127;
public const byte OutTypeChainFlag = 128;
public const EventTags EventTagsMask = (EventTags)0xfffffff;
public static readonly TraceLoggingDataType IntPtrType = IntPtr.Size == 8
? TraceLoggingDataType.Int64
: TraceLoggingDataType.Int32;
public static readonly TraceLoggingDataType UIntPtrType = IntPtr.Size == 8
? TraceLoggingDataType.UInt64
: TraceLoggingDataType.UInt32;
public static readonly TraceLoggingDataType HexIntPtrType = IntPtr.Size == 8
? TraceLoggingDataType.HexInt64
: TraceLoggingDataType.HexInt32;
#endregion
#region Metadata helpers
/// <summary>
/// A complete metadata chunk can be expressed as:
/// length16 + prefix + null-terminated-utf8-name + suffix + additionalData.
/// We assume that excludedData will be provided by some other means,
/// but that its size is known. This function returns a blob containing
/// length16 + prefix + name + suffix, with prefix and suffix initialized
/// to 0's. The length16 value is initialized to the length of the returned
/// blob plus additionalSize, so that the concatenation of the returned blob
/// plus a blob of size additionalSize constitutes a valid metadata blob.
/// </summary>
/// <param name="name">
/// The name to include in the blob.
/// </param>
/// <param name="prefixSize">
/// Amount of space to reserve before name. For provider or field blobs, this
/// should be 0. For event blobs, this is used for the tags field and will vary
/// from 1 to 4, depending on how large the tags field needs to be.
/// </param>
/// <param name="suffixSize">
/// Amount of space to reserve after name. For example, a provider blob with no
/// traits would reserve 0 extra bytes, but a provider blob with a single GroupId
/// field would reserve 19 extra bytes.
/// </param>
/// <param name="additionalSize">
/// Amount of additional data in another blob. This value will be counted in the
/// blob's length field, but will not be included in the returned byte[] object.
/// The complete blob would then be the concatenation of the returned byte[] object
/// with another byte[] object of length additionalSize.
/// </param>
/// <returns>
/// A byte[] object with the length and name fields set, with room reserved for
/// prefix and suffix. If additionalSize was 0, the byte[] object is a complete
/// blob. Otherwise, another byte[] of size additionalSize must be concatenated
/// with this one to form a complete blob.
/// </returns>
public static byte[] MetadataForString(
string name,
int prefixSize,
int suffixSize,
int additionalSize)
{
Statics.CheckName(name);
int metadataSize = Encoding.UTF8.GetByteCount(name) + 3 + prefixSize + suffixSize;
var metadata = new byte[metadataSize];
ushort totalSize = checked((ushort)(metadataSize + additionalSize));
metadata[0] = unchecked((byte)totalSize);
metadata[1] = unchecked((byte)(totalSize >> 8));
Encoding.UTF8.GetBytes(name, 0, name.Length, metadata, 2 + prefixSize);
return metadata;
}
/// <summary>
/// Serialize the low 28 bits of the tags value into the metadata stream,
/// starting at the index given by pos. Updates pos. Writes 1 to 4 bytes,
/// depending on the value of the tags variable. Usable for event tags and
/// field tags.
///
/// Note that 'metadata' can be null, in which case it only updates 'pos'.
/// This is useful for a two pass approach where you figure out how big to
/// make the array, and then you fill it in.
/// </summary>
public static void EncodeTags(int tags, ref int pos, byte[] metadata)
{
// We transmit the low 28 bits of tags, high bits first, 7 bits at a time.
var tagsLeft = tags & 0xfffffff;
bool more;
do
{
byte current = (byte)((tagsLeft >> 21) & 0x7f);
more = (tagsLeft & 0x1fffff) != 0;
current |= (byte)(more ? 0x80 : 0x00);
tagsLeft = tagsLeft << 7;
if (metadata != null)
{
metadata[pos] = current;
}
pos += 1;
}
while (more);
}
public static byte Combine(
int settingValue,
byte defaultValue)
{
unchecked
{
return (byte)settingValue == settingValue
? (byte)settingValue
: defaultValue;
}
}
public static byte Combine(
int settingValue1,
int settingValue2,
byte defaultValue)
{
unchecked
{
return (byte)settingValue1 == settingValue1
? (byte)settingValue1
: (byte)settingValue2 == settingValue2
? (byte)settingValue2
: defaultValue;
}
}
public static int Combine(
int settingValue1,
int settingValue2)
{
unchecked
{
return (byte)settingValue1 == settingValue1
? settingValue1
: settingValue2;
}
}
public static void CheckName(string name)
{
if (name != null && 0 <= name.IndexOf('\0'))
{
throw new ArgumentOutOfRangeException(nameof(name));
}
}
public static bool ShouldOverrideFieldName(string fieldName)
{
return (fieldName.Length <= 2 && fieldName[0] == '_');
}
public static TraceLoggingDataType MakeDataType(
TraceLoggingDataType baseType,
EventFieldFormat format)
{
return (TraceLoggingDataType)(((int)baseType & 0x1f) | ((int)format << 8));
}
/// <summary>
/// Adjusts the native type based on format.
/// - If format is default, return native.
/// - If format is recognized, return the canonical type for that format.
/// - Otherwise remove existing format from native and apply the requested format.
/// </summary>
public static TraceLoggingDataType Format8(
EventFieldFormat format,
TraceLoggingDataType native)
{
switch (format)
{
case EventFieldFormat.Default:
return native;
case EventFieldFormat.String:
return TraceLoggingDataType.Char8;
case EventFieldFormat.Boolean:
return TraceLoggingDataType.Boolean8;
case EventFieldFormat.Hexadecimal:
return TraceLoggingDataType.HexInt8;
#if false
case EventSourceFieldFormat.Signed:
return TraceLoggingDataType.Int8;
case EventSourceFieldFormat.Unsigned:
return TraceLoggingDataType.UInt8;
#endif
default:
return MakeDataType(native, format);
}
}
/// <summary>
/// Adjusts the native type based on format.
/// - If format is default, return native.
/// - If format is recognized, return the canonical type for that format.
/// - Otherwise remove existing format from native and apply the requested format.
/// </summary>
public static TraceLoggingDataType Format16(
EventFieldFormat format,
TraceLoggingDataType native)
{
switch (format)
{
case EventFieldFormat.Default:
return native;
case EventFieldFormat.String:
return TraceLoggingDataType.Char16;
case EventFieldFormat.Hexadecimal:
return TraceLoggingDataType.HexInt16;
#if false
case EventSourceFieldFormat.Port:
return TraceLoggingDataType.Port;
case EventSourceFieldFormat.Signed:
return TraceLoggingDataType.Int16;
case EventSourceFieldFormat.Unsigned:
return TraceLoggingDataType.UInt16;
#endif
default:
return MakeDataType(native, format);
}
}
/// <summary>
/// Adjusts the native type based on format.
/// - If format is default, return native.
/// - If format is recognized, return the canonical type for that format.
/// - Otherwise remove existing format from native and apply the requested format.
/// </summary>
public static TraceLoggingDataType Format32(
EventFieldFormat format,
TraceLoggingDataType native)
{
switch (format)
{
case EventFieldFormat.Default:
return native;
case EventFieldFormat.Boolean:
return TraceLoggingDataType.Boolean32;
case EventFieldFormat.Hexadecimal:
return TraceLoggingDataType.HexInt32;
#if false
case EventSourceFieldFormat.Ipv4Address:
return TraceLoggingDataType.Ipv4Address;
case EventSourceFieldFormat.ProcessId:
return TraceLoggingDataType.ProcessId;
case EventSourceFieldFormat.ThreadId:
return TraceLoggingDataType.ThreadId;
case EventSourceFieldFormat.Win32Error:
return TraceLoggingDataType.Win32Error;
case EventSourceFieldFormat.NTStatus:
return TraceLoggingDataType.NTStatus;
#endif
case EventFieldFormat.HResult:
return TraceLoggingDataType.HResult;
#if false
case EventSourceFieldFormat.Signed:
return TraceLoggingDataType.Int32;
case EventSourceFieldFormat.Unsigned:
return TraceLoggingDataType.UInt32;
#endif
default:
return MakeDataType(native, format);
}
}
/// <summary>
/// Adjusts the native type based on format.
/// - If format is default, return native.
/// - If format is recognized, return the canonical type for that format.
/// - Otherwise remove existing format from native and apply the requested format.
/// </summary>
public static TraceLoggingDataType Format64(
EventFieldFormat format,
TraceLoggingDataType native)
{
switch (format)
{
case EventFieldFormat.Default:
return native;
case EventFieldFormat.Hexadecimal:
return TraceLoggingDataType.HexInt64;
#if false
case EventSourceFieldFormat.FileTime:
return TraceLoggingDataType.FileTime;
case EventSourceFieldFormat.Signed:
return TraceLoggingDataType.Int64;
case EventSourceFieldFormat.Unsigned:
return TraceLoggingDataType.UInt64;
#endif
default:
return MakeDataType(native, format);
}
}
/// <summary>
/// Adjusts the native type based on format.
/// - If format is default, return native.
/// - If format is recognized, return the canonical type for that format.
/// - Otherwise remove existing format from native and apply the requested format.
/// </summary>
public static TraceLoggingDataType FormatPtr(
EventFieldFormat format,
TraceLoggingDataType native)
{
switch (format)
{
case EventFieldFormat.Default:
return native;
case EventFieldFormat.Hexadecimal:
return HexIntPtrType;
#if false
case EventSourceFieldFormat.Signed:
return IntPtrType;
case EventSourceFieldFormat.Unsigned:
return UIntPtrType;
#endif
default:
return MakeDataType(native, format);
}
}
#endregion
#region Reflection helpers
/*
All TraceLogging use of reflection APIs should go through wrappers here.
This helps with portability, and it also makes it easier to audit what
kinds of reflection operations are being done.
*/
public static object CreateInstance(Type type, params object[] parameters)
{
return Activator.CreateInstance(type, parameters);
}
public static bool IsValueType(Type type)
{
bool result = type.IsValueType();
return result;
}
public static bool IsEnum(Type type)
{
bool result = type.IsEnum();
return result;
}
public static IEnumerable<PropertyInfo> GetProperties(Type type)
{
IEnumerable<PropertyInfo> result = type.GetProperties();
return result;
}
public static MethodInfo GetGetMethod(PropertyInfo propInfo)
{
MethodInfo result = propInfo.GetGetMethod();
return result;
}
public static MethodInfo GetDeclaredStaticMethod(Type declaringType, string name)
{
MethodInfo result;
#if (ES_BUILD_PCL || ES_BUILD_PN)
result = declaringType.GetTypeInfo().GetDeclaredMethod(name);
#else
result = declaringType.GetMethod(
name,
BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.NonPublic);
#endif
return result;
}
public static bool HasCustomAttribute(
PropertyInfo propInfo,
Type attributeType)
{
bool result;
#if (ES_BUILD_PCL || ES_BUILD_PN)
result = propInfo.IsDefined(attributeType);
#else
var attributes = propInfo.GetCustomAttributes(
attributeType,
false);
result = attributes.Length != 0;
#endif
return result;
}
public static AttributeType GetCustomAttribute<AttributeType>(PropertyInfo propInfo)
where AttributeType : Attribute
{
AttributeType result = null;
#if (ES_BUILD_PCL || ES_BUILD_PN)
foreach (var attrib in propInfo.GetCustomAttributes<AttributeType>(false))
{
result = attrib;
break;
}
#else
var attributes = propInfo.GetCustomAttributes(typeof(AttributeType), false);
if (attributes.Length != 0)
{
result = (AttributeType)attributes[0];
}
#endif
return result;
}
public static AttributeType GetCustomAttribute<AttributeType>(Type type)
where AttributeType : Attribute
{
AttributeType result = null;
#if (ES_BUILD_PCL || ES_BUILD_PN)
foreach (var attrib in type.GetTypeInfo().GetCustomAttributes<AttributeType>(false))
{
result = attrib;
break;
}
#else
var attributes = type.GetCustomAttributes(typeof(AttributeType), false);
if (attributes.Length != 0)
{
result = (AttributeType)attributes[0];
}
#endif
return result;
}
public static Type[] GetGenericArguments(Type type)
{
return type.GetGenericArguments();
}
public static Type FindEnumerableElementType(Type type)
{
Type elementType = null;
if (IsGenericMatch(type, typeof(IEnumerable<>)))
{
elementType = GetGenericArguments(type)[0];
}
else
{
#if (ES_BUILD_PCL || ES_BUILD_PN)
var ifaceTypes = type.GetTypeInfo().ImplementedInterfaces;
#else
var ifaceTypes = type.FindInterfaces(IsGenericMatch, typeof(IEnumerable<>));
#endif
foreach (var ifaceType in ifaceTypes)
{
#if (ES_BUILD_PCL || ES_BUILD_PN)
if (!IsGenericMatch(ifaceType, typeof(IEnumerable<>)))
{
continue;
}
#endif
if (elementType != null)
{
// ambiguous match. report no match at all.
elementType = null;
break;
}
elementType = GetGenericArguments(ifaceType)[0];
}
}
return elementType;
}
public static bool IsGenericMatch(Type type, object openType)
{
return type.IsGenericType() && type.GetGenericTypeDefinition() == (Type)openType;
}
public static Delegate CreateDelegate(Type delegateType, MethodInfo methodInfo)
{
Delegate result;
#if (ES_BUILD_PCL || ES_BUILD_PN)
result = methodInfo.CreateDelegate(
delegateType);
#else
result = Delegate.CreateDelegate(
delegateType,
methodInfo);
#endif
return result;
}
public static TraceLoggingTypeInfo CreateDefaultTypeInfo(
Type dataType,
List<Type> recursionCheck)
{
TraceLoggingTypeInfo result;
if (recursionCheck.Contains(dataType))
{
throw new NotSupportedException(Resources.GetResourceString("EventSource_RecursiveTypeDefinition"));
}
recursionCheck.Add(dataType);
var eventAttrib = Statics.GetCustomAttribute<EventDataAttribute>(dataType);
if (eventAttrib != null ||
Statics.GetCustomAttribute<CompilerGeneratedAttribute>(dataType) != null ||
IsGenericMatch(dataType, typeof(KeyValuePair<,>)))
{
var analysis = new TypeAnalysis(dataType, eventAttrib, recursionCheck);
result = new InvokeTypeInfo(dataType, analysis);
}
else if (dataType.IsArray)
{
var elementType = dataType.GetElementType();
if (elementType == typeof(Boolean))
{
result = ScalarArrayTypeInfo.Boolean();
}
else if (elementType == typeof(Byte))
{
result = ScalarArrayTypeInfo.Byte();
}
else if (elementType == typeof(SByte))
{
result = ScalarArrayTypeInfo.SByte();
}
else if (elementType == typeof(Int16))
{
result = ScalarArrayTypeInfo.Int16();
}
else if (elementType == typeof(UInt16))
{
result = ScalarArrayTypeInfo.UInt16();
}
else if (elementType == typeof(Int32))
{
result = ScalarArrayTypeInfo.Int32();
}
else if (elementType == typeof(UInt32))
{
result = ScalarArrayTypeInfo.UInt32();
}
else if (elementType == typeof(Int64))
{
result = ScalarArrayTypeInfo.Int64();
}
else if (elementType == typeof(UInt64))
{
result = ScalarArrayTypeInfo.UInt64();
}
else if (elementType == typeof(Char))
{
result = ScalarArrayTypeInfo.Char();
}
else if (elementType == typeof(Double))
{
result = ScalarArrayTypeInfo.Double();
}
else if (elementType == typeof(Single))
{
result = ScalarArrayTypeInfo.Single();
}
else if (elementType == typeof(IntPtr))
{
result = ScalarArrayTypeInfo.IntPtr();
}
else if (elementType == typeof(UIntPtr))
{
result = ScalarArrayTypeInfo.UIntPtr();
}
else if (elementType == typeof(Guid))
{
result = ScalarArrayTypeInfo.Guid();
}
else
{
result = new ArrayTypeInfo(dataType, TraceLoggingTypeInfo.GetInstance(elementType, recursionCheck));
}
}
else
{
if (Statics.IsEnum(dataType))
dataType = Enum.GetUnderlyingType(dataType);
if (dataType == typeof(String))
{
result = new StringTypeInfo();
}
else if (dataType == typeof(Boolean))
{
result = ScalarTypeInfo.Boolean();
}
else if (dataType == typeof(Byte))
{
result = ScalarTypeInfo.Byte();
}
else if (dataType == typeof(SByte))
{
result = ScalarTypeInfo.SByte();
}
else if (dataType == typeof(Int16))
{
result = ScalarTypeInfo.Int16();
}
else if (dataType == typeof(UInt16))
{
result = ScalarTypeInfo.UInt16();
}
else if (dataType == typeof(Int32))
{
result = ScalarTypeInfo.Int32();
}
else if (dataType == typeof(UInt32))
{
result = ScalarTypeInfo.UInt32();
}
else if (dataType == typeof(Int64))
{
result = ScalarTypeInfo.Int64();
}
else if (dataType == typeof(UInt64))
{
result = ScalarTypeInfo.UInt64();
}
else if (dataType == typeof(Char))
{
result = ScalarTypeInfo.Char();
}
else if (dataType == typeof(Double))
{
result = ScalarTypeInfo.Double();
}
else if (dataType == typeof(Single))
{
result = ScalarTypeInfo.Single();
}
else if (dataType == typeof(DateTime))
{
result = new DateTimeTypeInfo();
}
else if (dataType == typeof(Decimal))
{
result = new DecimalTypeInfo();
}
else if (dataType == typeof(IntPtr))
{
result = ScalarTypeInfo.IntPtr();
}
else if (dataType == typeof(UIntPtr))
{
result = ScalarTypeInfo.UIntPtr();
}
else if (dataType == typeof(Guid))
{
result = ScalarTypeInfo.Guid();
}
else if (dataType == typeof(TimeSpan))
{
result = new TimeSpanTypeInfo();
}
else if (dataType == typeof(DateTimeOffset))
{
result = new DateTimeOffsetTypeInfo();
}
else if (dataType == typeof(EmptyStruct))
{
result = new NullTypeInfo();
}
else if (IsGenericMatch(dataType, typeof(Nullable<>)))
{
result = new NullableTypeInfo(dataType, recursionCheck);
}
else
{
var elementType = FindEnumerableElementType(dataType);
if (elementType != null)
{
result = new EnumerableTypeInfo(dataType, TraceLoggingTypeInfo.GetInstance(elementType, recursionCheck));
}
else
{
throw new ArgumentException(Resources.GetResourceString("EventSource_NonCompliantTypeError", dataType.Name));
}
}
}
return result;
}
#endregion
}
}
| |
/*
Copyright (c) 2006 Tomas Matousek.
Copyright (c) 2003-2005 Vaclav Novak.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using PHP.Core.AST;
using PHP.Core.Emit;
using PHP.Core.Parsers;
using PHP.Core.Reflection;
using PHP.Core.Compiler;
using PHP.Core.Compiler.AST;
using System.Reflection.Emit;
#if SILVERLIGHT
using PHP.CoreCLR;
#endif
namespace PHP.Core
{
/// <summary>
/// A set of possible types that an expression can result to.
/// </summary>
/// <remarks>
/// <para>This type is used to annotate <see cref="Expression"/>.
/// If an element is annotated with this information, we can emit more efficient code.</para>
/// </remarks>
public interface IExTypeInfo
{
/// <summary>
/// Enumeration of possible types.
/// If one of them is <see cref="PhpTypeCode.Object"/>,
/// then <see cref="Types"/> contains a collection of
/// possible types of the object.
/// </summary>
IEnumerable<PhpTypeCode> TypeCodes { get; }
/// <summary>
/// If <see cref="TypeCodes"/> contains <see cref="PhpTypeCode.Object"/>,
/// then this enumerates all the possible types of the object reference.
/// </summary>
IEnumerable<TypeRef> Types { get; }
/// <summary>
/// If <c>true</c>, then we do not know anything about the type for sure and
/// <see cref="TypeCodes"/> and <see cref="Types"/> contain undefined data.
/// </summary>
bool IsAnyType { get; }
/// <summary>
/// If <c>true</c>, then we don't know anything about this type,
/// like if <see cref="IsAnyType"/> was <c>true</c>,
/// but <see cref="TypeCodes"/> and <see cref="Types"/> contain type hints.
/// </summary>
/// <remarks>Value of this property really makes sense once <see cref="IsAnyType"/> is <c>true</c>,
/// otherwise value of <see cref="IsTypeHint"/> should always be <c>false</c>.</remarks>
bool IsTypeHint { get; }
/// <summary>
/// If <c>true</c>, then for all the <see cref="TypeRef"/> returned by <see cref="Types"/> we
/// have to consider all their subclasses too.
/// </summary>
/// <remarks>
/// Value of this only makes sense when <see cref="TypeCodes"/> contain <see cref="PhpTypeCode.Object"/>.
/// </remarks>
bool IncludesSubclasses { get; }
/// <summary>
/// This is a shortcut for checking whether <see cref="TypeCodes"/>
/// collection contains given element. Due to internal implementation details,
/// using this method might be faster, then constructing the collection in
/// <see cref="TypeCodes"/> getter.
/// </summary>
bool HasTypeCode(PhpTypeCode typeCode);
/// <summary>
/// This is a shortcut for checking whether <see cref="Types"/>
/// collection contains given element. Due to internal implementation details,
/// using this method might be faster, then constructing the collection in
/// <see cref="Types"/> getter.
/// </summary>
bool HasType(TypeRef type);
/// <summary>
/// Returns <c>true</c> if both <see cref="IsAnyType"/> and <see cref="IsTypeHint"/>
/// are <c>false</c> and <see cref="TypeCodes"/> contains only the given type.
/// </summary>
bool IsOfType(PhpTypeCode typeCode);
/// <summary>
/// Returns <c>true</c> if both <see cref="IsAnyType"/> and <see cref="IsTypeHint"/>
/// are <c>false</c>, <see cref="TypeCodes"/> contains only object and <see cref="Types"/>
/// contains only the given object type. Does not take into account
/// class hierarchy (<see cref="IncludesSubclasses"/>).
/// </summary>
bool IsOfType(TypeRef type);
}
internal interface IPostAnalyzable
{
void PostAnalyze(Analyzer/*!*/ analyzer);
}
#region Evaluation
internal struct Evaluation
{
public object Value;
public bool HasValue;
public Expression Expression;
public Evaluation(Expression/*!*/ expression)
: this(expression, null, false)
{
}
public Evaluation(Expression/*!*/ expression, object value)
: this(expression, value, true)
{
}
public Evaluation(Expression/*!*/ expression, object value, bool hasValue)
{
this.Expression = expression;
this.Value = value;
this.HasValue = hasValue;
}
/// <summary>
/// Converts the expression to a literal if we have a value and the expression is not yet a literal.
/// Returns the converted expression.
/// Used when the evaluation cannot continue as some other part of the operation is not evaluable.
/// </summary>
public Expression/*!*/ Literalize()
{
if (HasValue && !Expression.HasValue())
return Expression = LiteralUtils.Create(Expression.Span, Value, Expression.NodeCompiler<IExpressionCompiler>().Access);
else
return Expression;
}
internal Evaluation Evaluate(Expression/*!*/ parent, out Expression/*!*/ expr)
{
if (HasValue)
{
expr = Expression;
return new Evaluation(parent, parent.Evaluate(Value));
}
expr = Literalize();
return new Evaluation(parent);
}
internal static Evaluation Evaluate(Expression/*!*/ parent,
Evaluation eval1, out Expression/*!*/ expr1,
Evaluation eval2, out Expression/*!*/ expr2)
{
if (eval1.HasValue && eval2.HasValue)
{
expr1 = eval1.Expression;
expr2 = eval2.Expression;
return new Evaluation(parent, parent.Evaluate(eval1.Value, eval2.Value));
}
expr1 = eval1.Literalize();
expr2 = eval2.Literalize();
return new Evaluation(parent);
}
internal Evaluation ReadOnlyEvaluate(Expression/*!*/ parent)
{
if (HasValue)
return new Evaluation(parent, parent.Evaluate(Value));
return new Evaluation(parent);
}
internal static Evaluation ReadOnlyEvaluate(Expression/*!*/ parent, Evaluation eval1, Evaluation eval2)
{
if (eval1.HasValue && eval2.HasValue)
return new Evaluation(parent, parent.Evaluate(eval1.Value, eval2.Value));
return new Evaluation(parent);
}
}
#endregion
/// <summary>
/// Analyzes the AST previously built by the Parser.
/// Evaluates node attributes that can't be evaluated from down to up during building AST.
/// Fills tables.
/// Does some basic optimizations like constant expressions evaluating
/// and unreachable code eliminating.
/// Calls compiling of included source files.
/// </summary>
public sealed class Analyzer : AstVisitor
{
internal enum States
{
Initial,
PreAnalysisStarted,
MemberAnalysisStarted,
FullAnalysisStarted,
PostAnalysisStarted,
}
internal States State { get { return state; } }
private States state;
#region Fields and Properties
/// <summary>
/// Analyzed AST.
/// Must be internally modifiable in order to allow partial class declaration to change the sourceUnit during the analysis
/// </summary>
public CompilationSourceUnit SourceUnit { get { return sourceUnit; } internal set { sourceUnit = value; } }
private CompilationSourceUnit sourceUnit;
/// <summary>
/// Current scope. Available only during full analysis.
/// </summary>
public Scope CurrentScope { get { return currentScope; } set { currentScope = value; } }
private Scope currentScope = Scope.Invalid;
/// <summary>
/// The current compilation context.
/// </summary>
public override CompilationContext Context { get { return context; } }
private CompilationContext context;
/// <summary>
/// The current error sink.
/// </summary>
internal ErrorSink ErrorSink { get { return context.Errors; } }
internal List<IPostAnalyzable>/*!*/ PostAnalyzed { get { return postAnalyzed; } }
private List<IPostAnalyzable>/*!*/ postAnalyzed = new List<IPostAnalyzable>();
#endregion
#region Construction
internal Analyzer(CompilationContext/*!*/ context)
{
this.context = context;
condLevel = 0;
loopNestingLevel = 0;
state = States.Initial;
}
#endregion
#region Analysis Entry Points
internal void PreAnalyze(IEnumerable<Declaration>/*!*/ declarations)
{
state = States.PreAnalysisStarted;
foreach (Declaration decl in declarations)
{
this.sourceUnit = decl.SourceUnit;
if (decl.Node != null)
decl.Node.PreAnalyze(this);
}
}
internal void AnalyzeMembers(IEnumerable<Declaration>/*!*/ declarations)
{
state = States.MemberAnalysisStarted;
foreach (Declaration decl in declarations)
{
this.sourceUnit = decl.SourceUnit;
if (decl.Node != null)
decl.Node.AnalyzeMembers(this);
}
}
/// <summary>
/// Analyzes the AST of the source unit.
/// </summary>
internal void Analyze(CompilationSourceUnit/*!*/ sourceUnit)
{
state = States.FullAnalysisStarted;
this.sourceUnit = sourceUnit;
this.currentNamespace = sourceUnit.CurrentNamespace;
this.currentScope = Scope.Global;
sourceUnit.Ast.Analyze(this);
this.currentScope = Scope.Invalid;
}
internal void PostAnalyze()
{
state = States.PostAnalysisStarted;
foreach (IPostAnalyzable node in postAnalyzed)
node.PostAnalyze(this);
postAnalyzed = null;
}
private Parser AstBuilder
{
get
{
if (_astBuilder == null)
{
_astBuilder = new Parser();
_astBuilder.AllowGlobalCode = true;
}
return _astBuilder;
}
}
private Parser _astBuilder;
/// <summary>
/// Builds AST from the given source code string.
/// Returns <B>null</B> if the AST cannot be built (new declarations appears in the code).
/// </summary>
internal Statement[] BuildAst(int positionShift, string/*!*/ sourceCode)
{
Parser.ReductionsCounter counter = new Parser.ReductionsCounter();
var ast = BuildAst(positionShift, sourceCode, counter);
if (counter.FunctionCount + counter.TypeCount + counter.ConstantCount > 0)
return null;
return ast.Statements;
}
/// <summary>
/// Builds AST from the given source code string. Does not check for declarations in the source code.
/// </summary>
public AST.GlobalCode BuildAst(int positionShift, string/*!*/ sourceCode, Parser.ReductionsCounter counter)
{
StringReader source_reader = new StringReader(sourceCode);
AST.GlobalCode ast = AstBuilder.Parse(sourceUnit, source_reader, ErrorSink, counter,
Lexer.LexicalStates.ST_IN_SCRIPTING, context.Config.Compiler.LanguageFeatures, positionShift);
return ast;
}
#endregion
#region Nested Types: Locations
internal enum Locations
{
GlobalCode,
FunctionDecl,
MethodDecl,
TypeDecl,
ActualParam,
Switch
}
private abstract class Location
{
public abstract Locations Kind { get; }
}
#region DeclLocation
private abstract class DeclLocation : Location
{
internal int NestingLevel { get { return nestingLevel; } }
private int nestingLevel;
internal DeclLocation(int nestingLevel)
{
this.nestingLevel = nestingLevel;
}
}
#endregion
#region RoutineDeclLoc
private class RoutineDeclLoc : DeclLocation
{
internal PhpRoutine/*!*/ Routine { get { return routine; } }
private PhpRoutine/*!*/ routine;
public override Locations Kind
{
get { return routine.IsFunction ? Locations.FunctionDecl : Locations.MethodDecl; }
}
internal RoutineDeclLoc(PhpRoutine/*!*/ routine, int nestingLevel)
: base(nestingLevel)
{
this.routine = routine;
}
}
#endregion
#region TypeDeclLocation
private class TypeDeclLocation : DeclLocation
{
public override Locations Kind
{
get { return Locations.TypeDecl; }
}
public PhpType/*!*/ Type { get { return type; } }
private PhpType/*!*/ type;
internal TypeDeclLocation(PhpType/*!*/ type, int nestingLevel)
: base(nestingLevel)
{
this.type = type;
}
}
#endregion
#region ActParamsLoc
/// <summary>
/// Represents location in some actual parameter in function call.
/// </summary>
/// <remarks>
/// It maintains information about formal parameters
/// declaration and currently analyzed actual parameter index to answer if the
/// actual parameter shall be passed by reference or not.
/// </remarks>
private class ActualParamsLocation : Location
{
public override Locations Kind
{
get { return Locations.ActualParam; }
}
private int currentParam;
/// <summary>
/// Says which parameter shall be passed by reference.
/// </summary>
private RoutineSignature/*!*/ signature;
/// <summary>
/// Actual parameters count (needn't equal to the signature's size).
/// </summary>
private int actualParamCount;
internal ActualParamsLocation(RoutineSignature/*!*/ signature, int actualParamCount)
{
this.currentParam = -1;
this.signature = signature;
this.actualParamCount = actualParamCount;
}
/// <summary>
/// Updates information about location.
/// </summary>
internal void MoveToNextParam()
{
currentParam++;
Debug.Assert(currentParam < actualParamCount);
}
/// <summary>
/// Says if the just now analyzed actual parameter shall be passed be reference
/// </summary>
/// <returns>
/// <B>true</B> if the just now analyzed actual parameter shall be passed be reference
/// </returns>
internal bool ActParamPassedByRef()
{
Debug.Assert(!signature.IsUnknown);
return signature.IsAlias(currentParam);
}
internal bool ActParamDeclIsUnknown()
{
return signature.IsUnknown;
}
}
#endregion
#region SwitchLoc
/// <summary>
/// Represents location in switch statement
/// </summary>
/// <remarks>
/// <B>SwitchLoc</B> is used to store information about compile-time known case values
/// and used default section. That is used to report some warnings.
/// </remarks>
private class SwitchLocation : Location
{
public override Locations Kind
{
get { return Locations.Switch; }
}
internal ArrayList ConstCases;
internal bool ContainsDefault;
internal SwitchLocation()
{
ConstCases = new ArrayList();
ContainsDefault = false;
}
}
#endregion
#endregion
#region Locations
/// <summary>
/// Stack of locations.
/// </summary>
/// <remarks>
/// Used to maintain information on the actual position
/// of the analyzer in the AST. It says "what I am analyzing now".
/// </remarks>
private readonly Stack<Location>/*!*/ locationStack = new Stack<Location>();
/// <summary>
/// Stack of <see cref="TypeDeclLocation"/> instances.
/// </summary>
/// <remarks>
/// Represents (direct or indirect) nesting of classes declarations.
/// </remarks>
private readonly Stack<TypeDeclLocation>/*!*/ typeDeclStack = new Stack<TypeDeclLocation>();
/// <summary>
/// Routine stack.
/// </summary>
/// <remarks>
/// Represents (direct or indirect) nesting of functions/method declarations.
/// </remarks>
private readonly Stack<RoutineDeclLoc>/*!*/ routineDeclStack = new Stack<RoutineDeclLoc>();
public QualifiedName? CurrentNamespace { get { return currentNamespace; } }
private QualifiedName? currentNamespace;
/// <summary>
/// Level of code conditionality (zero means an unconditional code).
/// </summary>
private int condLevel;
/// <summary>
/// Gets level of right now analyzed piece of code nesting in loops
/// </summary>
internal int LoopNestingLevel { get { return loopNestingLevel; } }
private int loopNestingLevel;
/// <summary>
/// Is currently analyzed code unreachable? (TODO: too simple analysis, needs to be improved due to introduction of goto's)
/// </summary>
private bool unreachableCode;
/// <summary>
/// This field serves to ensure, that unreachable code warning is not reported on every
/// statement in unreachable block od statements, but only once
/// </summary>
private bool unreachableCodeReported;
private Location CurrentLocation
{
get
{
return locationStack.Peek();
}
}
internal PhpType CurrentType
{
get
{
return (typeDeclStack.Count > 0) ? typeDeclStack.Peek().Type : null;
}
}
internal PhpRoutine CurrentRoutine
{
get
{
return (routineDeclStack.Count > 0) ? routineDeclStack.Peek().Routine : null;
}
}
/// <summary>
/// Checks whether any of the classes that contains the code is in complete -
/// this is used for resolving whether function can be declared (in incomplete class
/// it must be declared later at runtime)
/// </summary>
/// <returns></returns>
public bool IsInsideIncompleteClass()
{
foreach (TypeDeclLocation loc in typeDeclStack)
{
if (!loc.Type.IsComplete) return true;
}
return false;
}
internal void AddCurrentRoutineProperty(RoutineProperties property)
{
if (CurrentRoutine != null)
CurrentRoutine.Properties |= property;
}
/// <summary>
/// Whether the argument passing semantics is by-ref.
/// </summary>
internal bool ActParamPassedByRef()
{
return ((ActualParamsLocation)CurrentLocation).ActParamPassedByRef();
}
/// <summary>
/// Whether the argument passing semantics is known for the current actual argument.
/// </summary>
internal bool ActParamDeclIsUnknown()
{
return ((ActualParamsLocation)CurrentLocation).ActParamDeclIsUnknown();
}
#endregion
#region Conditional code
/// <summary>
/// Notices the analyzer, that conditional code is entered.
/// </summary>
internal void EnterConditionalCode()
{
condLevel++;
}
/// <summary>
/// Notices the analyzer, that conditional code is leaved.
/// </summary>
internal void LeaveConditionalCode()
{
condLevel--;
// because the unreachable code is not analyzed, this will unset unreachableCode
// at the end of conditional block of code
LeaveUnreachableCode();
Debug.Assert(condLevel >= 0);
}
/// <summary>
/// Says if right now analyzed code is part of conditional block
/// </summary>
/// <returns>
/// <B>true</B> if right now analyzed code is part of conditional block
/// </returns>
internal bool IsThisCodeConditional()
{
return condLevel > 0;
}
#endregion
#region Unreachable code
/// <summary>
/// Says if the right now analyzed AST node represents part of conditional code
/// </summary>
/// <returns>
/// <B>true</B> if the right now analyzed AST node represents part of conditional code
/// </returns>
internal bool IsThisCodeUnreachable()
{
return unreachableCode;
}
/// <summary>
/// Notices the Analyzer that unreachable code has been entered
/// </summary>
/// <remarks>
/// Unreachable code is code behind <see cref="JumpStmt"/> in the same conditional block
/// but only if it is not declaration in global code.
/// Unreachable code is also code in while(false) body and if(false) then statement,
/// if(true)... else statement etc.
/// </remarks>
internal void EnterUnreachableCode()
{
unreachableCode = true;
unreachableCodeReported = false;
}
/// <summary>
/// Notices the Analyzer that unreachable code has been leaved
/// </summary>
/// <remarks>
/// This method is called only from <see cref="LeaveConditionalCode"/> because unreachable code ends
/// at the end of conditional block and from <see cref="GlobalCode"/>.<c>Analyze</c>.
/// because unreachable declarations in global code are valid.
/// </remarks>
internal void LeaveUnreachableCode()
{
unreachableCode = false;
}
internal void ReportUnreachableCode(Text.Span position)
{
if (!unreachableCodeReported)
{
ErrorSink.Add(Warnings.UnreachableCodeDetected, SourceUnit, position);
unreachableCodeReported = true;
}
}
#endregion
#region Variables and Labels
/// <summary>
/// Gets the variables table for the right now analyzed scope.
/// </summary>
internal VariablesTable CurrentVarTable
{
get
{
if (CurrentRoutine != null)
return CurrentRoutine.Builder.LocalVariables;
else
return sourceUnit.Ast.GetVarTable();
}
}
/// <summary>
/// Gets the variables table for the right now analyzed scope.
/// </summary>
internal Dictionary<VariableName, Statement> CurrentLabels
{
get
{
if (CurrentRoutine != null)
return CurrentRoutine.Builder.Labels;
else
return sourceUnit.Ast.GetLabels();
}
}
#endregion
#region ConstructedTypes
// TODO: Should ConstructedTypes be moved to CompilationUnitBase?
// + DefineConstructedTypesBuilders will be called in DefineBuilders of the CU
// + if persisted in any way, it should be persisted per CU
// - duplicates among CUs
/// <summary>
/// Stores all constructed types found in the source codes.
/// </summary>
private readonly Dictionary<DTypeDescs, ConstructedType>/*!*/ constructedTypes = new Dictionary<DTypeDescs, ConstructedType>();
internal ConstructedType/*!*/ CreateConstructedType(DTypeDesc/*!*/ genericType, DTypeDesc[]/*!!*/ arguments, int argCount)
{
ConstructedType result;
if (genericType.IsUnknown)
{
Array.Resize(ref arguments, argCount);
result = new ConstructedType(genericType, arguments);
}
else
{
DTypeDescs tuple = new DTypeDescs(genericType, arguments, argCount);
if (!constructedTypes.TryGetValue(tuple, out result))
{
Array.Resize(ref arguments, argCount);
result = new ConstructedType(genericType, arguments);
constructedTypes.Add(tuple, result);
}
}
return result;
}
/// <summary>
/// Should be called on types which are created during full analysis.
/// </summary>
internal ConstructedType AnalyzeConstructedType(DType type)
{
ConstructedType cted = type as ConstructedType;
if (cted != null)
{
cted.Analyze(this);
}
return cted;
}
internal void DefineConstructedTypeBuilders()
{
foreach (ConstructedType type in constructedTypes.Values)
{
// perform the analysis on the type if it hasn't been performed previously:
type.Analyze(this);
// define builders:
type.DefineBuilders();
}
}
#endregion
#region Enter/Leave functions
internal void EnterNamespace(NamespaceDecl ns)
{
Debug.Assert(!currentNamespace.HasValue, "Namespace nesting not supported");
currentNamespace = ns.QualifiedName;
}
internal void LeaveNamespace()
{
currentNamespace = null;
}
/// <summary>
/// Notices the analyzer that function declaration is entered.
/// </summary>
internal void EnterFunctionDeclaration(PhpRoutine/*!*/ function)
{
Debug.Assert(function.IsFunction);
RoutineDeclLoc f = new RoutineDeclLoc(function, locationStack.Count);
routineDeclStack.Push(f);
locationStack.Push(f);
EnterConditionalCode();
}
internal void LeaveFunctionDeclaration()
{
Debug.Assert(routineDeclStack.Count > 0);
Debug.Assert(locationStack.Count > 0);
Debug.Assert(locationStack.Peek() is RoutineDeclLoc);
Debug.Assert(routineDeclStack.Peek() == locationStack.Peek());
routineDeclStack.Pop();
locationStack.Pop();
LeaveConditionalCode();
}
/// <summary>
/// Notices the analyzer that method declaration is entered.
/// </summary>
internal void EnterMethodDeclaration(PhpMethod/*!*/ method)
{
//function declared within a method is global function
//=> method is only declared direct within a class declaration
Debug.Assert(locationStack.Peek().Kind == Locations.TypeDecl);
RoutineDeclLoc m = new RoutineDeclLoc(method, locationStack.Count);
routineDeclStack.Push(m);
locationStack.Push(m);
EnterConditionalCode();
}
internal void LeaveMethodDeclaration()
{
Debug.Assert(routineDeclStack.Count > 0);
Debug.Assert(locationStack.Count > 0);
Debug.Assert(locationStack.Peek() is RoutineDeclLoc);
Debug.Assert(routineDeclStack.Peek() == locationStack.Peek());
routineDeclStack.Pop();
locationStack.Pop();
LeaveConditionalCode();
}
/// <summary>
/// Notices the analyzer that class declaration is entered.
/// </summary>
internal void EnterTypeDecl(PhpType type)
{
TypeDeclLocation c = new TypeDeclLocation(type, locationStack.Count);
typeDeclStack.Push(c);
locationStack.Push(c);
}
internal void LeaveTypeDecl()
{
Debug.Assert(typeDeclStack.Count > 0);
Debug.Assert(locationStack.Count > 0);
Debug.Assert(locationStack.Peek() is TypeDeclLocation);
Debug.Assert(typeDeclStack.Peek() == locationStack.Peek());
typeDeclStack.Pop();
locationStack.Pop();
}
internal void EnterActualParams(RoutineSignature/*!*/ signature, int actualParamCount)
{
locationStack.Push(new ActualParamsLocation(signature, actualParamCount));
}
internal void LeaveActualParams()
{
Debug.Assert(locationStack.Peek() is ActualParamsLocation);
locationStack.Pop();
}
internal void EnterActParam()
{
((ActualParamsLocation)CurrentLocation).MoveToNextParam();
}
internal void LeaveActParam()
{
//do nothing
}
internal void EnterLoopBody()
{
EnterConditionalCode();
loopNestingLevel++;
}
internal void LeaveLoopBody()
{
LeaveConditionalCode();
loopNestingLevel--;
Debug.Assert(loopNestingLevel > -1);
}
#endregion
#region Switch Statement Handling
internal void EnterSwitchBody()
{
loopNestingLevel++;
locationStack.Push(new SwitchLocation());
}
internal void LeaveSwitchBody()
{
loopNestingLevel--;
Debug.Assert(loopNestingLevel > -1);
Debug.Assert(locationStack.Peek() is SwitchLocation);
locationStack.Pop();
}
internal void AddConstCaseToCurrentSwitch(object value, Text.Span position)
{
SwitchLocation current_switch = (SwitchLocation)CurrentLocation;
if (current_switch.ConstCases.IndexOf(value) > -1)
ErrorSink.Add(Warnings.MultipleSwitchCasesWithSameValue, SourceUnit, position, value);
else
current_switch.ConstCases.Add(value);
}
internal void AddDefaultToCurrentSwitch(Text.Span position)
{
SwitchLocation current_switch = (SwitchLocation)CurrentLocation;
if (current_switch.ContainsDefault)
ErrorSink.Add(Warnings.MoreThenOneDefaultInSwitch, SourceUnit, position);
else
current_switch.ContainsDefault = true;
}
#endregion
#region Name Resolving
private Scope GetReferringScope(PhpType referringType, PhpRoutine referringRoutine)
{
if (referringType != null) return referringType.Declaration.Scope;
if (referringRoutine is PhpFunction) return ((PhpFunction)referringRoutine).Declaration.Scope;
//if (referringRoutine is PhpLambdaFunction) ...
// used for global statements during full analysis:
Debug.Assert(currentScope.IsValid, "Scope is available only during full analysis.");
return currentScope;
}
public DRoutine/*!*/ ResolveFunctionName(QualifiedName qualifiedName, Text.Span position)
{
Debug.Assert(currentScope.IsValid, "Scope is available only during full analysis.");
QualifiedName? alias;
DRoutine result = sourceUnit.ResolveFunctionName(qualifiedName, currentScope, out alias, ErrorSink, position, false);
if (result.IsUnknown)
{
if (alias.HasValue)
ErrorSink.Add(Warnings.UnknownFunctionUsedWithAlias, SourceUnit, position, qualifiedName, alias);
else
ErrorSink.Add(Warnings.UnknownFunctionUsed, SourceUnit, position, qualifiedName);
}
return result;
}
/// <summary>
/// Resolves type based on provided <paramref name="typeName"/>.
/// </summary>
/// <param name="typeName">Either <see cref="GenericQualifiedName"/> or <see cref="PrimitiveTypeName"/> or <c>null</c> reference.</param>
/// <param name="referringType"></param>
/// <param name="referringRoutine"></param>
/// <param name="position"></param>
/// <param name="mustResolve"></param>
/// <returns></returns>
internal DType ResolveType(object typeName, PhpType referringType, PhpRoutine referringRoutine,
Text.Span position, bool mustResolve)
{
DType result = null;
if (typeName != null)
{
if (typeName.GetType() == typeof(GenericQualifiedName))
{
result = ResolveTypeName((GenericQualifiedName)typeName,
referringType, referringRoutine, position, mustResolve);
}
else if (typeName.GetType() == typeof(PrimitiveTypeName))
{
result = PrimitiveType.GetByName((PrimitiveTypeName)typeName);
}
else
{
throw new ArgumentException("typeName");
}
}
return result;
}
public DType/*!*/ ResolveTypeName(QualifiedName qualifiedName, PhpType referringType,
PhpRoutine referringRoutine, Text.Span position, bool mustResolve)
{
DType result;
if (qualifiedName.IsSelfClassName)
{
if (referringType != null)
{
result = referringType;
}
else
{
// we are sure the self is used incorrectly in function:
if (referringRoutine != null)
ErrorSink.Add(Errors.SelfUsedOutOfClass, SourceUnit, position);
// global code can be included to the method:
result = UnknownType.UnknownSelf;
}
}
else if (qualifiedName.IsStaticClassName)
{
if (referringType != null)
{
if (referringType.IsFinal)
{
// we are sure the 'static' == 'self'
result = referringType;
}
else
{
if (referringRoutine != null)
referringRoutine.Properties |= RoutineProperties.LateStaticBinding;
result = StaticType.Singleton;
}
}
else
{
// we are sure the static is used incorrectly in function:
//if (referringRoutine != null) // do not allow 'static' in global code:
ErrorSink.Add(Errors.StaticUsedOutOfClass, SourceUnit, position);
// global code can be included to the method:
result = UnknownType.UnknownStatic;
}
}
else if (qualifiedName.IsParentClassName)
{
if (referringType != null)
{
if (referringType.IsInterface)
{
ErrorSink.Add(Errors.ParentUsedOutOfClass, SourceUnit, position);
result = UnknownType.UnknownParent;
}
else
{
DType base_type = referringType.Base;
if (base_type == null)
{
ErrorSink.Add(Errors.ClassHasNoParent, SourceUnit, position, referringType.FullName);
result = UnknownType.UnknownParent;
}
else
{
result = base_type;
}
}
}
else
{
// we are sure the self is used incorrectly when we are in a function:
if (referringRoutine != null)
ErrorSink.Add(Errors.ParentUsedOutOfClass, SourceUnit, position);
// global code can be included to the method:
result = UnknownType.UnknownParent;
}
}
else
{
// try resolve the name as a type parameter name:
if (qualifiedName.IsSimpleName)
{
result = ResolveTypeParameterName(qualifiedName.Name, referringType, referringRoutine);
if (result != null)
return result;
}
Scope referring_scope = GetReferringScope(referringType, referringRoutine);
QualifiedName? alias;
result = sourceUnit.ResolveTypeName(qualifiedName, referring_scope, out alias, ErrorSink, position, mustResolve);
ReportUnknownType(result, alias, position);
}
return result;
}
private GenericParameter ResolveTypeParameterName(Name name, PhpType referringType, PhpRoutine referringRoutine)
{
GenericParameter result = null;
if (referringRoutine != null)
{
result = referringRoutine.Signature.GetGenericParameter(name);
if (result != null)
return result;
}
if (referringType != null)
{
result = referringType.GetGenericParameter(name);
if (result != null)
return result;
}
return result;
}
private void ReportUnknownType(DType/*!*/ type, QualifiedName? alias, Text.Span position)
{
if (type.IsUnknown)
{
if (alias.HasValue)
ErrorSink.Add(Warnings.UnknownClassUsedWithAlias, SourceUnit, position, type.FullName, alias);
else
ErrorSink.Add(Warnings.UnknownClassUsed, SourceUnit, position, type.FullName);
}
}
public DType/*!*/ ResolveTypeName(GenericQualifiedName genericName, PhpType referringType,
PhpRoutine referringRoutine, Text.Span position, bool mustResolve)
{
DType type = ResolveTypeName(genericName.QualifiedName, referringType, referringRoutine, position, mustResolve);
DTypeDesc[] arguments;
if (genericName.IsGeneric)
{
arguments = new DTypeDesc[genericName.GenericParams.Length];
for (int i = 0; i < arguments.Length; i++)
{
arguments[i] = ResolveType(genericName.GenericParams[i], referringType, referringRoutine, position, mustResolve).TypeDesc;
}
}
else
{
arguments = DTypeDesc.EmptyArray;
}
return type.MakeConstructedType(this, arguments, position);
}
/// <summary>
/// Gets the type for specified attribute type name.
/// </summary>
public DType/*!*/ ResolveCustomAttributeType(QualifiedName qualifiedName, Scope referringScope, Text.Span position)
{
if (qualifiedName.IsAppStaticAttributeName)
{
return SpecialCustomAttribute.AppStaticAttribute;
}
else if (qualifiedName.IsExportAttributeName)
{
return SpecialCustomAttribute.ExportAttribute;
}
else if (qualifiedName.IsDllImportAttributeName)
{
return SpecialCustomAttribute.DllImportAttribute;
}
else if (qualifiedName.IsOutAttributeName)
{
return SpecialCustomAttribute.OutAttribute;
}
else
{
QualifiedName? alias;
string attrname = qualifiedName.Name.Value;
if (!attrname.EndsWith(Name.AttributeNameSuffix)) attrname += Name.AttributeNameSuffix;
QualifiedName name = new QualifiedName(new Name(attrname), qualifiedName.Namespaces);
DType type = sourceUnit.ResolveTypeName(name, referringScope, out alias, ErrorSink, position, true);
if (type.IsUnknown)
type = sourceUnit.ResolveTypeName(qualifiedName, referringScope, out alias, ErrorSink, position, true);
ReportUnknownType(type, alias, position);
return type;
}
}
/// <summary>
/// Resolves a method of given <see cref="DType"/> by its name.
/// </summary>
/// <param name="type">The type of routine being resolved.</param>
/// <param name="methodName">The name of routine to be resolved.</param>
/// <param name="position">Position of method call used for error reporting.</param>
/// <param name="referringType">The type where the seached routine is being called. Can be <c>null</c>.</param>
/// <param name="referringRoutine">The routine where the searched routine is being called. Can be <c>null</c>.</param>
/// <param name="calledStatically">True if the searched routine is called statically - if it uses static method call syntax.
/// This affects the __call or __callStatic method lookup.
/// It affects also the error reporting, where for instance method calls, the bad visibility error is
/// ignored and falls back to return <see cref="UnknownMethod"/>.</param>
/// <param name="checkVisibilityAtRuntime">Will determine if the routine call must be checked for visibility at runtime.</param>
/// <param name="isCallMethod">Will determine if __call or __callStatic magic methods were found instead.</param>
/// <returns>The resolved routine. Cannot return <c>null</c>.</returns>
public DRoutine/*!*/ ResolveMethod(DType/*!*/ type, Name methodName, Text.Span position,
PhpType referringType, PhpRoutine referringRoutine, bool calledStatically,
out bool checkVisibilityAtRuntime, out bool isCallMethod)
{
checkVisibilityAtRuntime = false;
isCallMethod = false;
// we cannot resolve a method unless we know the inherited members:
if (type.IsDefinite)
{
//// if the method is a constructor,
//KnownType known;
//if (methodName.IsConstructName || (known = type as KnownType) != null && methodName.Equals(known.QualifiedName.Name))
// return ResolveConstructor(type, position, referringType, referringRoutine, out checkVisibilityAtRuntime);
DRoutine routine;
GetMemberResult member_result;
member_result = type.GetMethod(methodName, referringType, out routine);
// Look for __call or __callStatic magic methods if no method was found:
// Note: __call when looking for instance method is disabled, since there can be the searched method in some future override.
if (member_result == GetMemberResult.NotFound && calledStatically)
{
// in PHP, it is possible to call instance methods statically if we are in instance method context.
// In such case we have to look for __call instead of __callStatic:
// determine the proper call method:
// use __call for instance method invocation, including static method invocation within the current type (e.g. A::foo(), parent::foo(), ...)
// use __callStatic for static method invocation
Name callMethodName =
(!calledStatically || // just to have complete condition here, always false
(referringRoutine != null && referringType != null && !referringRoutine.IsStatic && // in non-static method
type.TypeDesc.IsAssignableFrom(referringType.TypeDesc)) // {CurrentType} is inherited from or equal {type}
) ? Name.SpecialMethodNames.Call : Name.SpecialMethodNames.CallStatic;
member_result = type.GetMethod(callMethodName, referringType, out routine);
if (member_result != GetMemberResult.NotFound)
isCallMethod = true;
}
switch (member_result)
{
case GetMemberResult.OK:
return routine;
case GetMemberResult.NotFound:
{
// allow calling CLR constructor:
KnownType known;
if (/*methodName.IsConstructName || */(known = type as KnownType) != null && methodName.Equals(known.QualifiedName.Name))
return ResolveConstructor(type, position, referringType, referringRoutine, out checkVisibilityAtRuntime);
//
if (calledStatically) // throw an error only in we are looking for static method, instance method can be defined in some future inherited class
ErrorSink.Add(Errors.UnknownMethodCalled, SourceUnit, position, type.FullName, methodName);
return new UnknownMethod(type, methodName.Value);
}
case GetMemberResult.BadVisibility:
{
if (!calledStatically) // instance method will check the routine dynamically, there can be some override later
return new UnknownMethod(type, methodName.Value);
if (referringType == null && referringRoutine == null)
{
// visibility must be checked at run-time:
checkVisibilityAtRuntime = true;
return routine;
}
else
{
// definitive error:
if (routine.IsPrivate)
{
ErrorSink.Add(Errors.PrivateMethodCalled, SourceUnit, position, type.FullName, methodName.Value,
referringType.FullName);
}
else
{
ErrorSink.Add(Errors.ProtectedMethodCalled, SourceUnit, position, type.FullName, methodName.Value,
referringType.FullName);
}
return new UnknownMethod(type, methodName.Value);
}
}
default:
throw new InvalidOperationException();
}
}
else
{
// warning (if any) reported by the type resolver:
return new UnknownMethod(type, methodName.Value);
}
}
/// <summary>
/// Resolves constructor of the specified type within the current context (location).
/// </summary>
public DRoutine/*!*/ ResolveConstructor(DType/*!*/ type, Text.Span position, PhpType referringType,
PhpRoutine referringRoutine, out bool checkVisibilityAtRuntime)
{
checkVisibilityAtRuntime = false;
KnownRoutine ctor;
// Do resolve ctor despite of the indefiniteness of the type to make error reporting consistent
// when accessing the constructors thru the new operator.
switch (type.GetConstructor(referringType, out ctor))
{
case GetMemberResult.OK:
return ctor;
case GetMemberResult.NotFound:
// default ctor to be used:
return new UnknownMethod(type);
case GetMemberResult.BadVisibility:
if (referringType == null && referringRoutine == null)
{
// visibility must be checked at run-time:
checkVisibilityAtRuntime = true;
return ctor;
}
else
{
// definitive error:
if (ctor.IsPrivate)
{
ErrorSink.Add(Errors.PrivateCtorCalled, SourceUnit, position, type.FullName,
ctor.FullName, referringType.FullName);
}
else
{
ErrorSink.Add(Errors.ProtectedCtorCalled, SourceUnit, position, type.FullName,
ctor.FullName, referringType.FullName);
}
return new UnknownMethod(type);
}
default:
throw new InvalidOperationException();
}
}
/// <summary>
/// Resolves static properties.
/// </summary>
public DProperty/*!*/ ResolveProperty(DType/*!*/ type, VariableName propertyName, Text.Span position, bool staticOnly,
PhpType referringType, PhpRoutine referringRoutine, out bool checkVisibilityAtRuntime)
{
Debug.Assert(type != null);
checkVisibilityAtRuntime = false;
// we cannot resolve a property unless we know the inherited members:
if (type.IsDefinite)
{
DProperty property;
GetMemberResult member_result = type.GetProperty(propertyName, referringType, out property);
switch (member_result)
{
case GetMemberResult.OK:
if (staticOnly && !property.IsStatic) goto case GetMemberResult.NotFound;
return property;
case GetMemberResult.NotFound:
ErrorSink.Add(Errors.UnknownPropertyAccessed, SourceUnit, position, type.FullName, propertyName);
return new UnknownProperty(type, propertyName.Value);
case GetMemberResult.BadVisibility:
if (referringType == null && referringRoutine == null)
{
// visibility must be checked at run-time:
checkVisibilityAtRuntime = true;
return property;
}
else
{
// definitive error:
if (property.IsPrivate)
{
ErrorSink.Add(Errors.PrivatePropertyAccessed, SourceUnit, position, type.FullName, propertyName.Value,
referringType.FullName);
}
else
{
ErrorSink.Add(Errors.ProtectedPropertyAccessed, SourceUnit, position, type.FullName, propertyName.Value,
referringType.FullName);
}
return new UnknownProperty(type, propertyName.Value);
}
default:
throw new InvalidOperationException();
}
}
else
{
// warning (if any) reported by the type resolver:
return new UnknownProperty(type, propertyName.Value);
}
}
internal DConstant ResolveClassConstantName(DType/*!*/ type, VariableName constantName,
Text.Span position, PhpType referringType, PhpRoutine referringRoutine, out bool checkVisibilityAtRuntime)
{
checkVisibilityAtRuntime = false;
// we cannot resolve a class constant unless we know the inherited members:
if (type.IsDefinite)
{
ClassConstant constant;
GetMemberResult member_result = type.GetConstant(constantName, referringType, out constant);
switch (member_result)
{
case GetMemberResult.OK:
return constant;
case GetMemberResult.NotFound:
ErrorSink.Add(Errors.UnknownClassConstantAccessed, SourceUnit, position, type.FullName, constantName);
return new UnknownClassConstant(type, constantName.Value);
case GetMemberResult.BadVisibility:
if (referringType == null && referringRoutine == null)
{
// visibility must be checked at run-time:
checkVisibilityAtRuntime = true;
return constant;
}
else
{
// definitive error:
if (constant.IsPrivate)
{
ErrorSink.Add(Errors.PrivateConstantAccessed, SourceUnit, position, type.FullName, constantName.Value,
referringType.FullName);
}
else
{
ErrorSink.Add(Errors.ProtectedConstantAccessed, SourceUnit, position, type.FullName, constantName.Value,
referringType.FullName);
}
return new UnknownClassConstant(type, constantName.Value);
}
default:
throw new InvalidOperationException();
}
}
else
{
// warning (if any) reported by the type resolver:
return new UnknownClassConstant(type, constantName.Value);
}
}
internal DConstant ResolveGlobalConstantName(QualifiedName qualifiedName, Text.Span position)
{
Debug.Assert(currentScope.IsValid, "Scope is available only during full analysis.");
QualifiedName? alias;
DConstant result = sourceUnit.ResolveConstantName(qualifiedName, currentScope, out alias, ErrorSink, position, false);
if (result.IsUnknown)
{
if (alias.HasValue)
ErrorSink.Add(Warnings.UnknownConstantUsedWithAlias, SourceUnit, position, qualifiedName, alias);
else
{
// TODO:
// ErrorSink.Add(Warnings.UnknownConstantUsed, SourceUnit, position, qualifiedName);
// do not report unknown constants (they may be defined by define() as well as added at run-time by Phalanger)
// future feature: analyzed define()'s and check run-time added constants
}
}
return result;
}
#endregion
#region Miscellaneous
public void AddLambdaFcnDeclaration(FunctionDecl decl)
{
var ast = sourceUnit.Ast;
ast.Statements = ArrayUtils.Concat(ast.Statements, decl);
}
internal void SetEntryPoint(PhpRoutine/*!*/ routine, Text.Span position)
{
// pure entry point is a static parameterless "Main" method/function:
if (!sourceUnit.CompilationUnit.IsPure || !routine.Name.Equals(PureAssembly.EntryPointName)
|| !routine.IsStatic || routine.Signature.ParamCount > 0)
return;
PureCompilationUnit pcu = (PureCompilationUnit)sourceUnit.CompilationUnit;
if (pcu.EntryPoint != null)
{
ErrorSink.Add(Errors.EntryPointRedefined, SourceUnit, position);
ErrorSink.Add(Errors.RelatedLocation, pcu.EntryPoint.SourceUnit, pcu.EntryPoint.Span);
}
else
{
pcu.SetEntryPoint(routine);
}
}
internal static void ValidateLabels(ErrorSink/*!*/ errors, SourceUnit/*!*/ sourceUnit,
Dictionary<VariableName, Statement>/*!*/ labels)
{
foreach (KeyValuePair<VariableName, Statement> entry in labels)
{
LabelStmt label = entry.Value as LabelStmt;
if (label != null)
{
if (!label.IsReferred)
errors.Add(Warnings.UnusedLabel, sourceUnit, label.Span, entry.Key);
}
else
{
errors.Add(Errors.UndefinedLabel, sourceUnit, entry.Value.Span, entry.Key);
}
}
}
#endregion
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Catalog;
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.ADF.CATIDs;
namespace TextTab2008_CS
{
[Guid("67e3135b-116f-4f5b-ba5c-89c7fca09aee")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("TextTab2008_CS.TextView")]
public class TextView : ESRI.ArcGIS.CatalogUI.IGxView
{
#region COM Registration Function(s)
[ComRegisterFunction()]
[ComVisible(false)]
static void RegisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryRegistration(registerType);
//
// TODO: Add any COM registration code here
//
}
[ComUnregisterFunction()]
[ComVisible(false)]
static void UnregisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryUnregistration(registerType);
//
// TODO: Add any COM unregistration code here
//
}
#region ArcGIS Component Category Registrar generated code
/// <summary>
/// Required method for ArcGIS Component Category registration -
/// Do not modify the contents of this method with the code editor.
/// </summary>
private static void ArcGISCategoryRegistration(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
GxTabViews.Register(regKey);
}
/// <summary>
/// Required method for ArcGIS Component Category unregistration -
/// Do not modify the contents of this method with the code editor.
/// </summary>
private static void ArcGISCategoryUnregistration(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
GxTabViews.Unregister(regKey);
}
#endregion
#endregion
#region Member Variables
private GxSelection m_pSelection;
private FrmTextView frmTextView = new FrmTextView();
#endregion
private void OnSelectionChanged(IGxSelection Selection, ref object initiator)
{
//Refresh view
Refresh();
}
#region IGxView Implementations
public void Activate(ESRI.ArcGIS.CatalogUI.IGxApplication Application, ESRI.ArcGIS.Catalog.IGxCatalog Catalog)
{
m_pSelection = (GxSelection) Application.Selection;
m_pSelection.OnSelectionChanged += new IGxSelectionEvents_OnSelectionChangedEventHandler(OnSelectionChanged);
Refresh();
}
public bool Applies(ESRI.ArcGIS.Catalog.IGxObject Selection)
{
//Set applies
return (Selection != null) & (Selection is IGxTextFile);
}
public ESRI.ArcGIS.esriSystem.UID ClassID
{
get
{
//Set class ID
UID pUID = new UID();
pUID.Value = "TextTab2008_CS.TextView";
return pUID;
}
}
public void Deactivate()
{
//Prevent circular reference
if (m_pSelection != null)
m_pSelection = null;
}
public ESRI.ArcGIS.esriSystem.UID DefaultToolbarCLSID
{
get
{
return null;
}
}
public string Name
{
get
{
//Set view name
return "Text";
}
}
public void Refresh()
{
IGxSelection pGxSelection = null;
IGxObject pLocation = null;
pGxSelection = m_pSelection;
pLocation = pGxSelection.Location;
//Clean up
frmTextView.txtContents.Clear();
string fname = null;
fname = pLocation.Name.ToLower();
if (fname.IndexOf(".txt") != -1)
{
try
{
frmTextView.txtContents.Text = System.IO.File.ReadAllText(pLocation.FullName);
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
}
finally
{
pGxSelection = null;
pLocation = null;
}
}
}
public bool SupportsTools
{
get
{
return false;
}
}
public void SystemSettingChanged(int flag, string section)
{
// TODO: Add TextView.SystemSettingChanged implementation
}
public int hWnd
{
get
{
int temphWnd = 0;
try
{
//Set view handle to be the control handle
temphWnd = frmTextView.txtContents.Handle.ToInt32();
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
}
return temphWnd;
}
}
#endregion
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.Sync.V1.Service.SyncList
{
/// <summary>
/// FetchSyncListItemOptions
/// </summary>
public class FetchSyncListItemOptions : IOptions<SyncListItemResource>
{
/// <summary>
/// The SID of the Sync Service with the Sync List Item resource to fetch
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The SID of the Sync List with the Sync List Item resource to fetch
/// </summary>
public string PathListSid { get; }
/// <summary>
/// The index of the Sync List Item resource to fetch
/// </summary>
public int? PathIndex { get; }
/// <summary>
/// Construct a new FetchSyncListItemOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the Sync List Item resource to fetch </param>
/// <param name="pathListSid"> The SID of the Sync List with the Sync List Item resource to fetch </param>
/// <param name="pathIndex"> The index of the Sync List Item resource to fetch </param>
public FetchSyncListItemOptions(string pathServiceSid, string pathListSid, int? pathIndex)
{
PathServiceSid = pathServiceSid;
PathListSid = pathListSid;
PathIndex = pathIndex;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// DeleteSyncListItemOptions
/// </summary>
public class DeleteSyncListItemOptions : IOptions<SyncListItemResource>
{
/// <summary>
/// The SID of the Sync Service with the Sync List Item resource to delete
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The SID of the Sync List with the Sync List Item resource to delete
/// </summary>
public string PathListSid { get; }
/// <summary>
/// The index of the Sync List Item resource to delete
/// </summary>
public int? PathIndex { get; }
/// <summary>
/// The If-Match HTTP request header
/// </summary>
public string IfMatch { get; set; }
/// <summary>
/// Construct a new DeleteSyncListItemOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the Sync List Item resource to delete </param>
/// <param name="pathListSid"> The SID of the Sync List with the Sync List Item resource to delete </param>
/// <param name="pathIndex"> The index of the Sync List Item resource to delete </param>
public DeleteSyncListItemOptions(string pathServiceSid, string pathListSid, int? pathIndex)
{
PathServiceSid = pathServiceSid;
PathListSid = pathListSid;
PathIndex = pathIndex;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
/// <summary>
/// Generate the necessary header parameters
/// </summary>
public List<KeyValuePair<string, string>> GetHeaderParams()
{
var p = new List<KeyValuePair<string, string>>();
if (IfMatch != null)
{
p.Add(new KeyValuePair<string, string>("If-Match", IfMatch));
}
return p;
}
}
/// <summary>
/// CreateSyncListItemOptions
/// </summary>
public class CreateSyncListItemOptions : IOptions<SyncListItemResource>
{
/// <summary>
/// The SID of the Sync Service to create the List Item in
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The SID of the Sync List to add the new List Item to
/// </summary>
public string PathListSid { get; }
/// <summary>
/// A JSON string that represents an arbitrary, schema-less object that the List Item stores
/// </summary>
public object Data { get; }
/// <summary>
/// An alias for item_ttl
/// </summary>
public int? Ttl { get; set; }
/// <summary>
/// How long, in seconds, before the List Item expires
/// </summary>
public int? ItemTtl { get; set; }
/// <summary>
/// How long, in seconds, before the List Item's parent Sync List expires
/// </summary>
public int? CollectionTtl { get; set; }
/// <summary>
/// Construct a new CreateSyncListItemOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service to create the List Item in </param>
/// <param name="pathListSid"> The SID of the Sync List to add the new List Item to </param>
/// <param name="data"> A JSON string that represents an arbitrary, schema-less object that the List Item stores
/// </param>
public CreateSyncListItemOptions(string pathServiceSid, string pathListSid, object data)
{
PathServiceSid = pathServiceSid;
PathListSid = pathListSid;
Data = data;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Data != null)
{
p.Add(new KeyValuePair<string, string>("Data", Serializers.JsonObject(Data)));
}
if (Ttl != null)
{
p.Add(new KeyValuePair<string, string>("Ttl", Ttl.ToString()));
}
if (ItemTtl != null)
{
p.Add(new KeyValuePair<string, string>("ItemTtl", ItemTtl.ToString()));
}
if (CollectionTtl != null)
{
p.Add(new KeyValuePair<string, string>("CollectionTtl", CollectionTtl.ToString()));
}
return p;
}
}
/// <summary>
/// ReadSyncListItemOptions
/// </summary>
public class ReadSyncListItemOptions : ReadOptions<SyncListItemResource>
{
/// <summary>
/// The SID of the Sync Service with the List Item resources to read
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The SID of the Sync List with the List Items to read
/// </summary>
public string PathListSid { get; }
/// <summary>
/// The order to return the List Items
/// </summary>
public SyncListItemResource.QueryResultOrderEnum Order { get; set; }
/// <summary>
/// The index of the first Sync List Item resource to read
/// </summary>
public string From { get; set; }
/// <summary>
/// Whether to include the List Item referenced by the from parameter
/// </summary>
public SyncListItemResource.QueryFromBoundTypeEnum Bounds { get; set; }
/// <summary>
/// Construct a new ReadSyncListItemOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the List Item resources to read </param>
/// <param name="pathListSid"> The SID of the Sync List with the List Items to read </param>
public ReadSyncListItemOptions(string pathServiceSid, string pathListSid)
{
PathServiceSid = pathServiceSid;
PathListSid = pathListSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Order != null)
{
p.Add(new KeyValuePair<string, string>("Order", Order.ToString()));
}
if (From != null)
{
p.Add(new KeyValuePair<string, string>("From", From));
}
if (Bounds != null)
{
p.Add(new KeyValuePair<string, string>("Bounds", Bounds.ToString()));
}
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
/// <summary>
/// UpdateSyncListItemOptions
/// </summary>
public class UpdateSyncListItemOptions : IOptions<SyncListItemResource>
{
/// <summary>
/// The SID of the Sync Service with the Sync List Item resource to update
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The SID of the Sync List with the Sync List Item resource to update
/// </summary>
public string PathListSid { get; }
/// <summary>
/// The index of the Sync List Item resource to update
/// </summary>
public int? PathIndex { get; }
/// <summary>
/// A JSON string that represents an arbitrary, schema-less object that the List Item stores
/// </summary>
public object Data { get; set; }
/// <summary>
/// An alias for item_ttl
/// </summary>
public int? Ttl { get; set; }
/// <summary>
/// How long, in seconds, before the List Item expires
/// </summary>
public int? ItemTtl { get; set; }
/// <summary>
/// How long, in seconds, before the List Item's parent Sync List expires
/// </summary>
public int? CollectionTtl { get; set; }
/// <summary>
/// The If-Match HTTP request header
/// </summary>
public string IfMatch { get; set; }
/// <summary>
/// Construct a new UpdateSyncListItemOptions
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the Sync List Item resource to update </param>
/// <param name="pathListSid"> The SID of the Sync List with the Sync List Item resource to update </param>
/// <param name="pathIndex"> The index of the Sync List Item resource to update </param>
public UpdateSyncListItemOptions(string pathServiceSid, string pathListSid, int? pathIndex)
{
PathServiceSid = pathServiceSid;
PathListSid = pathListSid;
PathIndex = pathIndex;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Data != null)
{
p.Add(new KeyValuePair<string, string>("Data", Serializers.JsonObject(Data)));
}
if (Ttl != null)
{
p.Add(new KeyValuePair<string, string>("Ttl", Ttl.ToString()));
}
if (ItemTtl != null)
{
p.Add(new KeyValuePair<string, string>("ItemTtl", ItemTtl.ToString()));
}
if (CollectionTtl != null)
{
p.Add(new KeyValuePair<string, string>("CollectionTtl", CollectionTtl.ToString()));
}
return p;
}
/// <summary>
/// Generate the necessary header parameters
/// </summary>
public List<KeyValuePair<string, string>> GetHeaderParams()
{
var p = new List<KeyValuePair<string, string>>();
if (IfMatch != null)
{
p.Add(new KeyValuePair<string, string>("If-Match", IfMatch));
}
return p;
}
}
}
| |
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>
/// Controller class for LAB_SolicitudScreening
/// </summary>
[System.ComponentModel.DataObject]
public partial class LabSolicitudScreeningController
{
// Preload our schema..
LabSolicitudScreening thisSchemaLoad = new LabSolicitudScreening();
private string userName = String.Empty;
protected string UserName
{
get
{
if (userName.Length == 0)
{
if (System.Web.HttpContext.Current != null)
{
userName=System.Web.HttpContext.Current.User.Identity.Name;
}
else
{
userName=System.Threading.Thread.CurrentPrincipal.Identity.Name;
}
}
return userName;
}
}
[DataObjectMethod(DataObjectMethodType.Select, true)]
public LabSolicitudScreeningCollection FetchAll()
{
LabSolicitudScreeningCollection coll = new LabSolicitudScreeningCollection();
Query qry = new Query(LabSolicitudScreening.Schema);
coll.LoadAndCloseReader(qry.ExecuteReader());
return coll;
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public LabSolicitudScreeningCollection FetchByID(object IdSolicitudScreening)
{
LabSolicitudScreeningCollection coll = new LabSolicitudScreeningCollection().Where("idSolicitudScreening", IdSolicitudScreening).Load();
return coll;
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public LabSolicitudScreeningCollection FetchByQuery(Query qry)
{
LabSolicitudScreeningCollection coll = new LabSolicitudScreeningCollection();
coll.LoadAndCloseReader(qry.ExecuteReader());
return coll;
}
[DataObjectMethod(DataObjectMethodType.Delete, true)]
public bool Delete(object IdSolicitudScreening)
{
return (LabSolicitudScreening.Delete(IdSolicitudScreening) == 1);
}
[DataObjectMethod(DataObjectMethodType.Delete, false)]
public bool Destroy(object IdSolicitudScreening)
{
return (LabSolicitudScreening.Destroy(IdSolicitudScreening) == 1);
}
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
[DataObjectMethod(DataObjectMethodType.Insert, true)]
public void Insert(int IdPaciente,int IdEfectorSolicitante,int NumeroTarjeta,string MedicoSolicitante,string ApellidoMaterno,string ApellidoPaterno,string HoraNacimiento,int EdadGestacional,decimal Peso,bool PrimeraMuestra,int IdMotivoRepeticion,DateTime FechaExtraccion,string HoraExtraccion,bool IngestaLeche24Horas,int TipoAlimentacion,bool Antibiotico,bool Transfusion,bool Corticoides,bool Dopamina,bool EnfermedadTiroideaMaterna,string AntecedentesMaternos,bool CorticoidesMaterno,string Observaciones,string ObservacionesResultados,int Estado,int IdUsuarioRegistro,DateTime FechaRegistro,string IdUsuarioEnvio,DateTime FechaEnvio,string IdUsuarioRecibe,DateTime FechaRecibe,string IdUsuarioValida,DateTime FechaValida,int IdLugarControl,int? IdEfectorModifica,string Comentario,string Motivo)
{
LabSolicitudScreening item = new LabSolicitudScreening();
item.IdPaciente = IdPaciente;
item.IdEfectorSolicitante = IdEfectorSolicitante;
item.NumeroTarjeta = NumeroTarjeta;
item.MedicoSolicitante = MedicoSolicitante;
item.ApellidoMaterno = ApellidoMaterno;
item.ApellidoPaterno = ApellidoPaterno;
item.HoraNacimiento = HoraNacimiento;
item.EdadGestacional = EdadGestacional;
item.Peso = Peso;
item.PrimeraMuestra = PrimeraMuestra;
item.IdMotivoRepeticion = IdMotivoRepeticion;
item.FechaExtraccion = FechaExtraccion;
item.HoraExtraccion = HoraExtraccion;
item.IngestaLeche24Horas = IngestaLeche24Horas;
item.TipoAlimentacion = TipoAlimentacion;
item.Antibiotico = Antibiotico;
item.Transfusion = Transfusion;
item.Corticoides = Corticoides;
item.Dopamina = Dopamina;
item.EnfermedadTiroideaMaterna = EnfermedadTiroideaMaterna;
item.AntecedentesMaternos = AntecedentesMaternos;
item.CorticoidesMaterno = CorticoidesMaterno;
item.Observaciones = Observaciones;
item.ObservacionesResultados = ObservacionesResultados;
item.Estado = Estado;
item.IdUsuarioRegistro = IdUsuarioRegistro;
item.FechaRegistro = FechaRegistro;
item.IdUsuarioEnvio = IdUsuarioEnvio;
item.FechaEnvio = FechaEnvio;
item.IdUsuarioRecibe = IdUsuarioRecibe;
item.FechaRecibe = FechaRecibe;
item.IdUsuarioValida = IdUsuarioValida;
item.FechaValida = FechaValida;
item.IdLugarControl = IdLugarControl;
item.IdEfectorModifica = IdEfectorModifica;
item.Comentario = Comentario;
item.Motivo = Motivo;
item.Save(UserName);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
[DataObjectMethod(DataObjectMethodType.Update, true)]
public void Update(int IdSolicitudScreening,int IdPaciente,int IdEfectorSolicitante,int NumeroTarjeta,string MedicoSolicitante,string ApellidoMaterno,string ApellidoPaterno,string HoraNacimiento,int EdadGestacional,decimal Peso,bool PrimeraMuestra,int IdMotivoRepeticion,DateTime FechaExtraccion,string HoraExtraccion,bool IngestaLeche24Horas,int TipoAlimentacion,bool Antibiotico,bool Transfusion,bool Corticoides,bool Dopamina,bool EnfermedadTiroideaMaterna,string AntecedentesMaternos,bool CorticoidesMaterno,string Observaciones,string ObservacionesResultados,int Estado,int IdUsuarioRegistro,DateTime FechaRegistro,string IdUsuarioEnvio,DateTime FechaEnvio,string IdUsuarioRecibe,DateTime FechaRecibe,string IdUsuarioValida,DateTime FechaValida,int IdLugarControl,int? IdEfectorModifica,string Comentario,string Motivo)
{
LabSolicitudScreening item = new LabSolicitudScreening();
item.MarkOld();
item.IsLoaded = true;
item.IdSolicitudScreening = IdSolicitudScreening;
item.IdPaciente = IdPaciente;
item.IdEfectorSolicitante = IdEfectorSolicitante;
item.NumeroTarjeta = NumeroTarjeta;
item.MedicoSolicitante = MedicoSolicitante;
item.ApellidoMaterno = ApellidoMaterno;
item.ApellidoPaterno = ApellidoPaterno;
item.HoraNacimiento = HoraNacimiento;
item.EdadGestacional = EdadGestacional;
item.Peso = Peso;
item.PrimeraMuestra = PrimeraMuestra;
item.IdMotivoRepeticion = IdMotivoRepeticion;
item.FechaExtraccion = FechaExtraccion;
item.HoraExtraccion = HoraExtraccion;
item.IngestaLeche24Horas = IngestaLeche24Horas;
item.TipoAlimentacion = TipoAlimentacion;
item.Antibiotico = Antibiotico;
item.Transfusion = Transfusion;
item.Corticoides = Corticoides;
item.Dopamina = Dopamina;
item.EnfermedadTiroideaMaterna = EnfermedadTiroideaMaterna;
item.AntecedentesMaternos = AntecedentesMaternos;
item.CorticoidesMaterno = CorticoidesMaterno;
item.Observaciones = Observaciones;
item.ObservacionesResultados = ObservacionesResultados;
item.Estado = Estado;
item.IdUsuarioRegistro = IdUsuarioRegistro;
item.FechaRegistro = FechaRegistro;
item.IdUsuarioEnvio = IdUsuarioEnvio;
item.FechaEnvio = FechaEnvio;
item.IdUsuarioRecibe = IdUsuarioRecibe;
item.FechaRecibe = FechaRecibe;
item.IdUsuarioValida = IdUsuarioValida;
item.FechaValida = FechaValida;
item.IdLugarControl = IdLugarControl;
item.IdEfectorModifica = IdEfectorModifica;
item.Comentario = Comentario;
item.Motivo = Motivo;
item.Save(UserName);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Schema
{
using System;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Diagnostics;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Globalization;
/// <include file='doc\XmlSchemaFacet.uex' path='docs/doc[@for="XmlSchemaFacet"]/*' />
internal abstract class FacetsChecker
{
private struct FacetsCompiler
{
private DatatypeImplementation _datatype;
private RestrictionFacets _derivedRestriction;
private RestrictionFlags _baseFlags;
private RestrictionFlags _baseFixedFlags;
private RestrictionFlags _validRestrictionFlags;
//Helpers
private XmlSchemaDatatype _nonNegativeInt;
private XmlSchemaDatatype _builtInType;
private XmlTypeCode _builtInEnum;
private bool _firstPattern;
private StringBuilder _regStr;
private XmlSchemaPatternFacet _pattern_facet;
public FacetsCompiler(DatatypeImplementation baseDatatype, RestrictionFacets restriction)
{
_firstPattern = true;
_regStr = null;
_pattern_facet = null;
_datatype = baseDatatype;
_derivedRestriction = restriction;
_baseFlags = _datatype.Restriction != null ? _datatype.Restriction.Flags : 0;
_baseFixedFlags = _datatype.Restriction != null ? _datatype.Restriction.FixedFlags : 0;
_validRestrictionFlags = _datatype.ValidRestrictionFlags;
_nonNegativeInt = DatatypeImplementation.GetSimpleTypeFromTypeCode(XmlTypeCode.NonNegativeInteger).Datatype;
_builtInEnum = !(_datatype is Datatype_union || _datatype is Datatype_List) ? _datatype.TypeCode : 0;
_builtInType = (int)_builtInEnum > 0 ? DatatypeImplementation.GetSimpleTypeFromTypeCode(_builtInEnum).Datatype : _datatype;
}
internal void CompileLengthFacet(XmlSchemaFacet facet)
{
CheckProhibitedFlag(facet, RestrictionFlags.Length, SR.Sch_LengthFacetProhibited);
CheckDupFlag(facet, RestrictionFlags.Length, SR.Sch_DupLengthFacet);
_derivedRestriction.Length = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(_nonNegativeInt, facet, SR.Sch_LengthFacetInvalid, null, null));
if ((_baseFixedFlags & RestrictionFlags.Length) != 0)
{
if (!_datatype.IsEqual(_datatype.Restriction.Length, _derivedRestriction.Length))
{
throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet);
}
}
if ((_baseFlags & RestrictionFlags.Length) != 0)
{
if (_datatype.Restriction.Length < _derivedRestriction.Length)
{
throw new XmlSchemaException(SR.Sch_LengthGtBaseLength, facet);
}
}
// If the base has the MinLength facet, check that our derived length is not violating it
if ((_baseFlags & RestrictionFlags.MinLength) != 0)
{
if (_datatype.Restriction.MinLength > _derivedRestriction.Length)
{
throw new XmlSchemaException(SR.Sch_MaxMinLengthBaseLength, facet);
}
}
// If the base has the MaxLength facet, check that our derived length is not violating it
if ((_baseFlags & RestrictionFlags.MaxLength) != 0)
{
if (_datatype.Restriction.MaxLength < _derivedRestriction.Length)
{
throw new XmlSchemaException(SR.Sch_MaxMinLengthBaseLength, facet);
}
}
SetFlag(facet, RestrictionFlags.Length);
}
internal void CompileMinLengthFacet(XmlSchemaFacet facet)
{
CheckProhibitedFlag(facet, RestrictionFlags.MinLength, SR.Sch_MinLengthFacetProhibited);
CheckDupFlag(facet, RestrictionFlags.MinLength, SR.Sch_DupMinLengthFacet);
_derivedRestriction.MinLength = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(_nonNegativeInt, facet, SR.Sch_MinLengthFacetInvalid, null, null));
if ((_baseFixedFlags & RestrictionFlags.MinLength) != 0)
{
if (!_datatype.IsEqual(_datatype.Restriction.MinLength, _derivedRestriction.MinLength))
{
throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet);
}
}
if ((_baseFlags & RestrictionFlags.MinLength) != 0)
{
if (_datatype.Restriction.MinLength > _derivedRestriction.MinLength)
{
throw new XmlSchemaException(SR.Sch_MinLengthGtBaseMinLength, facet);
}
}
if ((_baseFlags & RestrictionFlags.Length) != 0)
{
if (_datatype.Restriction.Length < _derivedRestriction.MinLength)
{
throw new XmlSchemaException(SR.Sch_MaxMinLengthBaseLength, facet);
}
}
SetFlag(facet, RestrictionFlags.MinLength);
}
internal void CompileMaxLengthFacet(XmlSchemaFacet facet)
{
CheckProhibitedFlag(facet, RestrictionFlags.MaxLength, SR.Sch_MaxLengthFacetProhibited);
CheckDupFlag(facet, RestrictionFlags.MaxLength, SR.Sch_DupMaxLengthFacet);
_derivedRestriction.MaxLength = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(_nonNegativeInt, facet, SR.Sch_MaxLengthFacetInvalid, null, null));
if ((_baseFixedFlags & RestrictionFlags.MaxLength) != 0)
{
if (!_datatype.IsEqual(_datatype.Restriction.MaxLength, _derivedRestriction.MaxLength))
{
throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet);
}
}
if ((_baseFlags & RestrictionFlags.MaxLength) != 0)
{
if (_datatype.Restriction.MaxLength < _derivedRestriction.MaxLength)
{
throw new XmlSchemaException(SR.Sch_MaxLengthGtBaseMaxLength, facet);
}
}
if ((_baseFlags & RestrictionFlags.Length) != 0)
{
if (_datatype.Restriction.Length > _derivedRestriction.MaxLength)
{
throw new XmlSchemaException(SR.Sch_MaxMinLengthBaseLength, facet);
}
}
SetFlag(facet, RestrictionFlags.MaxLength);
}
internal void CompilePatternFacet(XmlSchemaPatternFacet facet)
{
CheckProhibitedFlag(facet, RestrictionFlags.Pattern, SR.Sch_PatternFacetProhibited);
if (_firstPattern == true)
{
_regStr = new StringBuilder();
_regStr.Append("(");
_regStr.Append(facet.Value);
_pattern_facet = facet;
_firstPattern = false;
}
else
{
_regStr.Append(")|(");
_regStr.Append(facet.Value);
}
SetFlag(facet, RestrictionFlags.Pattern);
}
internal void CompileEnumerationFacet(XmlSchemaFacet facet, IXmlNamespaceResolver nsmgr, XmlNameTable nameTable)
{
CheckProhibitedFlag(facet, RestrictionFlags.Enumeration, SR.Sch_EnumerationFacetProhibited);
if (_derivedRestriction.Enumeration == null)
{
_derivedRestriction.Enumeration = new ArrayList();
}
_derivedRestriction.Enumeration.Add(ParseFacetValue(_datatype, facet, SR.Sch_EnumerationFacetInvalid, nsmgr, nameTable));
SetFlag(facet, RestrictionFlags.Enumeration);
}
internal void CompileWhitespaceFacet(XmlSchemaFacet facet)
{
CheckProhibitedFlag(facet, RestrictionFlags.WhiteSpace, SR.Sch_WhiteSpaceFacetProhibited);
CheckDupFlag(facet, RestrictionFlags.WhiteSpace, SR.Sch_DupWhiteSpaceFacet);
if (facet.Value == "preserve")
{
_derivedRestriction.WhiteSpace = XmlSchemaWhiteSpace.Preserve;
}
else if (facet.Value == "replace")
{
_derivedRestriction.WhiteSpace = XmlSchemaWhiteSpace.Replace;
}
else if (facet.Value == "collapse")
{
_derivedRestriction.WhiteSpace = XmlSchemaWhiteSpace.Collapse;
}
else
{
throw new XmlSchemaException(SR.Sch_InvalidWhiteSpace, facet.Value, facet);
}
if ((_baseFixedFlags & RestrictionFlags.WhiteSpace) != 0)
{
if (!_datatype.IsEqual(_datatype.Restriction.WhiteSpace, _derivedRestriction.WhiteSpace))
{
throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet);
}
}
//Check base and derived whitespace facets
XmlSchemaWhiteSpace baseWhitespace;
if ((_baseFlags & RestrictionFlags.WhiteSpace) != 0)
{
baseWhitespace = _datatype.Restriction.WhiteSpace;
}
else
{
baseWhitespace = _datatype.BuiltInWhitespaceFacet;
}
if (baseWhitespace == XmlSchemaWhiteSpace.Collapse &&
(_derivedRestriction.WhiteSpace == XmlSchemaWhiteSpace.Replace || _derivedRestriction.WhiteSpace == XmlSchemaWhiteSpace.Preserve)
)
{
throw new XmlSchemaException(SR.Sch_WhiteSpaceRestriction1, facet);
}
if (baseWhitespace == XmlSchemaWhiteSpace.Replace &&
_derivedRestriction.WhiteSpace == XmlSchemaWhiteSpace.Preserve
)
{
throw new XmlSchemaException(SR.Sch_WhiteSpaceRestriction2, facet);
}
SetFlag(facet, RestrictionFlags.WhiteSpace);
}
internal void CompileMaxInclusiveFacet(XmlSchemaFacet facet)
{
CheckProhibitedFlag(facet, RestrictionFlags.MaxInclusive, SR.Sch_MaxInclusiveFacetProhibited);
CheckDupFlag(facet, RestrictionFlags.MaxInclusive, SR.Sch_DupMaxInclusiveFacet);
_derivedRestriction.MaxInclusive = ParseFacetValue(_builtInType, facet, SR.Sch_MaxInclusiveFacetInvalid, null, null);
if ((_baseFixedFlags & RestrictionFlags.MaxInclusive) != 0)
{
if (!_datatype.IsEqual(_datatype.Restriction.MaxInclusive, _derivedRestriction.MaxInclusive))
{
throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet);
}
}
CheckValue(_derivedRestriction.MaxInclusive, facet);
SetFlag(facet, RestrictionFlags.MaxInclusive);
}
internal void CompileMaxExclusiveFacet(XmlSchemaFacet facet)
{
CheckProhibitedFlag(facet, RestrictionFlags.MaxExclusive, SR.Sch_MaxExclusiveFacetProhibited);
CheckDupFlag(facet, RestrictionFlags.MaxExclusive, SR.Sch_DupMaxExclusiveFacet);
_derivedRestriction.MaxExclusive = ParseFacetValue(_builtInType, facet, SR.Sch_MaxExclusiveFacetInvalid, null, null);
if ((_baseFixedFlags & RestrictionFlags.MaxExclusive) != 0)
{
if (!_datatype.IsEqual(_datatype.Restriction.MaxExclusive, _derivedRestriction.MaxExclusive))
{
throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet);
}
}
CheckValue(_derivedRestriction.MaxExclusive, facet);
SetFlag(facet, RestrictionFlags.MaxExclusive);
}
internal void CompileMinInclusiveFacet(XmlSchemaFacet facet)
{
CheckProhibitedFlag(facet, RestrictionFlags.MinInclusive, SR.Sch_MinInclusiveFacetProhibited);
CheckDupFlag(facet, RestrictionFlags.MinInclusive, SR.Sch_DupMinInclusiveFacet);
_derivedRestriction.MinInclusive = ParseFacetValue(_builtInType, facet, SR.Sch_MinInclusiveFacetInvalid, null, null);
if ((_baseFixedFlags & RestrictionFlags.MinInclusive) != 0)
{
if (!_datatype.IsEqual(_datatype.Restriction.MinInclusive, _derivedRestriction.MinInclusive))
{
throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet);
}
}
CheckValue(_derivedRestriction.MinInclusive, facet);
SetFlag(facet, RestrictionFlags.MinInclusive);
}
internal void CompileMinExclusiveFacet(XmlSchemaFacet facet)
{
CheckProhibitedFlag(facet, RestrictionFlags.MinExclusive, SR.Sch_MinExclusiveFacetProhibited);
CheckDupFlag(facet, RestrictionFlags.MinExclusive, SR.Sch_DupMinExclusiveFacet);
_derivedRestriction.MinExclusive = ParseFacetValue(_builtInType, facet, SR.Sch_MinExclusiveFacetInvalid, null, null);
if ((_baseFixedFlags & RestrictionFlags.MinExclusive) != 0)
{
if (!_datatype.IsEqual(_datatype.Restriction.MinExclusive, _derivedRestriction.MinExclusive))
{
throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet);
}
}
CheckValue(_derivedRestriction.MinExclusive, facet);
SetFlag(facet, RestrictionFlags.MinExclusive);
}
internal void CompileTotalDigitsFacet(XmlSchemaFacet facet)
{
CheckProhibitedFlag(facet, RestrictionFlags.TotalDigits, SR.Sch_TotalDigitsFacetProhibited);
CheckDupFlag(facet, RestrictionFlags.TotalDigits, SR.Sch_DupTotalDigitsFacet);
XmlSchemaDatatype positiveInt = DatatypeImplementation.GetSimpleTypeFromTypeCode(XmlTypeCode.PositiveInteger).Datatype;
_derivedRestriction.TotalDigits = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(positiveInt, facet, SR.Sch_TotalDigitsFacetInvalid, null, null));
if ((_baseFixedFlags & RestrictionFlags.TotalDigits) != 0)
{
if (!_datatype.IsEqual(_datatype.Restriction.TotalDigits, _derivedRestriction.TotalDigits))
{
throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet);
}
}
if ((_baseFlags & RestrictionFlags.TotalDigits) != 0)
{
if (_derivedRestriction.TotalDigits > _datatype.Restriction.TotalDigits)
{
throw new XmlSchemaException(SR.Sch_TotalDigitsMismatch, string.Empty);
}
}
SetFlag(facet, RestrictionFlags.TotalDigits);
}
internal void CompileFractionDigitsFacet(XmlSchemaFacet facet)
{
CheckProhibitedFlag(facet, RestrictionFlags.FractionDigits, SR.Sch_FractionDigitsFacetProhibited);
CheckDupFlag(facet, RestrictionFlags.FractionDigits, SR.Sch_DupFractionDigitsFacet);
_derivedRestriction.FractionDigits = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(_nonNegativeInt, facet, SR.Sch_FractionDigitsFacetInvalid, null, null));
if ((_derivedRestriction.FractionDigits != 0) && (_datatype.TypeCode != XmlTypeCode.Decimal))
{
throw new XmlSchemaException(SR.Sch_FractionDigitsFacetInvalid, SR.Sch_FractionDigitsNotOnDecimal, facet);
}
if ((_baseFlags & RestrictionFlags.FractionDigits) != 0)
{
if (_derivedRestriction.FractionDigits > _datatype.Restriction.FractionDigits)
{
throw new XmlSchemaException(SR.Sch_TotalDigitsMismatch, string.Empty);
}
}
SetFlag(facet, RestrictionFlags.FractionDigits);
}
internal void FinishFacetCompile()
{
//Additional check for pattern facet
//If facet is XMLSchemaPattern, then the String built inside the loop
//needs to be converted to a RegEx
if (_firstPattern == false)
{
if (_derivedRestriction.Patterns == null)
{
_derivedRestriction.Patterns = new ArrayList();
}
try
{
_regStr.Append(")");
string tempStr = _regStr.ToString();
if (tempStr.Contains('|'))
{ // ordinal compare
_regStr.Insert(0, "(");
_regStr.Append(")");
}
_derivedRestriction.Patterns.Add(new Regex(Preprocess(_regStr.ToString()), RegexOptions.None));
}
catch (Exception e)
{
throw new XmlSchemaException(SR.Sch_PatternFacetInvalid, new string[] { e.Message }, e, _pattern_facet.SourceUri, _pattern_facet.LineNumber, _pattern_facet.LinePosition, _pattern_facet);
}
}
}
private void CheckValue(object value, XmlSchemaFacet facet)
{
RestrictionFacets restriction = _datatype.Restriction;
switch (facet.FacetType)
{
case FacetType.MaxInclusive:
if ((_baseFlags & RestrictionFlags.MaxInclusive) != 0)
{ //Base facet has maxInclusive
if (_datatype.Compare(value, restriction.MaxInclusive) > 0)
{
throw new XmlSchemaException(SR.Sch_MaxInclusiveMismatch, string.Empty);
}
}
if ((_baseFlags & RestrictionFlags.MaxExclusive) != 0)
{ //Base facet has maxExclusive
if (_datatype.Compare(value, restriction.MaxExclusive) >= 0)
{
throw new XmlSchemaException(SR.Sch_MaxIncExlMismatch, string.Empty);
}
}
break;
case FacetType.MaxExclusive:
if ((_baseFlags & RestrictionFlags.MaxExclusive) != 0)
{ //Base facet has maxExclusive
if (_datatype.Compare(value, restriction.MaxExclusive) > 0)
{
throw new XmlSchemaException(SR.Sch_MaxExclusiveMismatch, string.Empty);
}
}
if ((_baseFlags & RestrictionFlags.MaxInclusive) != 0)
{ //Base facet has maxInclusive
if (_datatype.Compare(value, restriction.MaxInclusive) > 0)
{
throw new XmlSchemaException(SR.Sch_MaxExlIncMismatch, string.Empty);
}
}
break;
case FacetType.MinInclusive:
if ((_baseFlags & RestrictionFlags.MinInclusive) != 0)
{ //Base facet has minInclusive
if (_datatype.Compare(value, restriction.MinInclusive) < 0)
{
throw new XmlSchemaException(SR.Sch_MinInclusiveMismatch, string.Empty);
}
}
if ((_baseFlags & RestrictionFlags.MinExclusive) != 0)
{ //Base facet has minExclusive
if (_datatype.Compare(value, restriction.MinExclusive) < 0)
{
throw new XmlSchemaException(SR.Sch_MinIncExlMismatch, string.Empty);
}
}
if ((_baseFlags & RestrictionFlags.MaxExclusive) != 0)
{ //Base facet has maxExclusive
if (_datatype.Compare(value, restriction.MaxExclusive) >= 0)
{
throw new XmlSchemaException(SR.Sch_MinIncMaxExlMismatch, string.Empty);
}
}
break;
case FacetType.MinExclusive:
if ((_baseFlags & RestrictionFlags.MinExclusive) != 0)
{ //Base facet has minExclusive
if (_datatype.Compare(value, restriction.MinExclusive) < 0)
{
throw new XmlSchemaException(SR.Sch_MinExclusiveMismatch, string.Empty);
}
}
if ((_baseFlags & RestrictionFlags.MinInclusive) != 0)
{ //Base facet has minInclusive
if (_datatype.Compare(value, restriction.MinInclusive) < 0)
{
throw new XmlSchemaException(SR.Sch_MinExlIncMismatch, string.Empty);
}
}
if ((_baseFlags & RestrictionFlags.MaxExclusive) != 0)
{ //Base facet has maxExclusive
if (_datatype.Compare(value, restriction.MaxExclusive) >= 0)
{
throw new XmlSchemaException(SR.Sch_MinExlMaxExlMismatch, string.Empty);
}
}
break;
default:
Debug.Assert(false);
break;
}
}
internal void CompileFacetCombinations()
{
RestrictionFacets baseRestriction = _datatype.Restriction;
//They are not allowed on the same type but allowed on derived types.
if (
(_derivedRestriction.Flags & RestrictionFlags.MaxInclusive) != 0 &&
(_derivedRestriction.Flags & RestrictionFlags.MaxExclusive) != 0
)
{
throw new XmlSchemaException(SR.Sch_MaxInclusiveExclusive, string.Empty);
}
if (
(_derivedRestriction.Flags & RestrictionFlags.MinInclusive) != 0 &&
(_derivedRestriction.Flags & RestrictionFlags.MinExclusive) != 0
)
{
throw new XmlSchemaException(SR.Sch_MinInclusiveExclusive, string.Empty);
}
if (
(_derivedRestriction.Flags & RestrictionFlags.Length) != 0 &&
(_derivedRestriction.Flags & (RestrictionFlags.MinLength | RestrictionFlags.MaxLength)) != 0
)
{
throw new XmlSchemaException(SR.Sch_LengthAndMinMax, string.Empty);
}
CopyFacetsFromBaseType();
// Check combinations
if (
(_derivedRestriction.Flags & RestrictionFlags.MinLength) != 0 &&
(_derivedRestriction.Flags & RestrictionFlags.MaxLength) != 0
)
{
if (_derivedRestriction.MinLength > _derivedRestriction.MaxLength)
{
throw new XmlSchemaException(SR.Sch_MinLengthGtMaxLength, string.Empty);
}
}
if (
(_derivedRestriction.Flags & RestrictionFlags.MinInclusive) != 0 &&
(_derivedRestriction.Flags & RestrictionFlags.MaxInclusive) != 0
)
{
if (_datatype.Compare(_derivedRestriction.MinInclusive, _derivedRestriction.MaxInclusive) > 0)
{
throw new XmlSchemaException(SR.Sch_MinInclusiveGtMaxInclusive, string.Empty);
}
}
if (
(_derivedRestriction.Flags & RestrictionFlags.MinInclusive) != 0 &&
(_derivedRestriction.Flags & RestrictionFlags.MaxExclusive) != 0
)
{
if (_datatype.Compare(_derivedRestriction.MinInclusive, _derivedRestriction.MaxExclusive) > 0)
{
throw new XmlSchemaException(SR.Sch_MinInclusiveGtMaxExclusive, string.Empty);
}
}
if (
(_derivedRestriction.Flags & RestrictionFlags.MinExclusive) != 0 &&
(_derivedRestriction.Flags & RestrictionFlags.MaxExclusive) != 0
)
{
if (_datatype.Compare(_derivedRestriction.MinExclusive, _derivedRestriction.MaxExclusive) > 0)
{
throw new XmlSchemaException(SR.Sch_MinExclusiveGtMaxExclusive, string.Empty);
}
}
if (
(_derivedRestriction.Flags & RestrictionFlags.MinExclusive) != 0 &&
(_derivedRestriction.Flags & RestrictionFlags.MaxInclusive) != 0
)
{
if (_datatype.Compare(_derivedRestriction.MinExclusive, _derivedRestriction.MaxInclusive) > 0)
{
throw new XmlSchemaException(SR.Sch_MinExclusiveGtMaxInclusive, string.Empty);
}
}
if ((_derivedRestriction.Flags & (RestrictionFlags.TotalDigits | RestrictionFlags.FractionDigits)) == (RestrictionFlags.TotalDigits | RestrictionFlags.FractionDigits))
{
if (_derivedRestriction.FractionDigits > _derivedRestriction.TotalDigits)
{
throw new XmlSchemaException(SR.Sch_FractionDigitsGtTotalDigits, string.Empty);
}
}
}
private void CopyFacetsFromBaseType()
{
RestrictionFacets baseRestriction = _datatype.Restriction;
// Copy additional facets from the base type
if (
(_derivedRestriction.Flags & RestrictionFlags.Length) == 0 &&
(_baseFlags & RestrictionFlags.Length) != 0
)
{
_derivedRestriction.Length = baseRestriction.Length;
SetFlag(RestrictionFlags.Length);
}
if (
(_derivedRestriction.Flags & RestrictionFlags.MinLength) == 0 &&
(_baseFlags & RestrictionFlags.MinLength) != 0
)
{
_derivedRestriction.MinLength = baseRestriction.MinLength;
SetFlag(RestrictionFlags.MinLength);
}
if (
(_derivedRestriction.Flags & RestrictionFlags.MaxLength) == 0 &&
(_baseFlags & RestrictionFlags.MaxLength) != 0
)
{
_derivedRestriction.MaxLength = baseRestriction.MaxLength;
SetFlag(RestrictionFlags.MaxLength);
}
if ((_baseFlags & RestrictionFlags.Pattern) != 0)
{
if (_derivedRestriction.Patterns == null)
{
_derivedRestriction.Patterns = baseRestriction.Patterns;
}
else
{
_derivedRestriction.Patterns.AddRange(baseRestriction.Patterns);
}
SetFlag(RestrictionFlags.Pattern);
}
if ((_baseFlags & RestrictionFlags.Enumeration) != 0)
{
if (_derivedRestriction.Enumeration == null)
{
_derivedRestriction.Enumeration = baseRestriction.Enumeration;
}
SetFlag(RestrictionFlags.Enumeration);
}
if (
(_derivedRestriction.Flags & RestrictionFlags.WhiteSpace) == 0 &&
(_baseFlags & RestrictionFlags.WhiteSpace) != 0
)
{
_derivedRestriction.WhiteSpace = baseRestriction.WhiteSpace;
SetFlag(RestrictionFlags.WhiteSpace);
}
if (
(_derivedRestriction.Flags & RestrictionFlags.MaxInclusive) == 0 &&
(_baseFlags & RestrictionFlags.MaxInclusive) != 0
)
{
_derivedRestriction.MaxInclusive = baseRestriction.MaxInclusive;
SetFlag(RestrictionFlags.MaxInclusive);
}
if (
(_derivedRestriction.Flags & RestrictionFlags.MaxExclusive) == 0 &&
(_baseFlags & RestrictionFlags.MaxExclusive) != 0
)
{
_derivedRestriction.MaxExclusive = baseRestriction.MaxExclusive;
SetFlag(RestrictionFlags.MaxExclusive);
}
if (
(_derivedRestriction.Flags & RestrictionFlags.MinInclusive) == 0 &&
(_baseFlags & RestrictionFlags.MinInclusive) != 0
)
{
_derivedRestriction.MinInclusive = baseRestriction.MinInclusive;
SetFlag(RestrictionFlags.MinInclusive);
}
if (
(_derivedRestriction.Flags & RestrictionFlags.MinExclusive) == 0 &&
(_baseFlags & RestrictionFlags.MinExclusive) != 0
)
{
_derivedRestriction.MinExclusive = baseRestriction.MinExclusive;
SetFlag(RestrictionFlags.MinExclusive);
}
if (
(_derivedRestriction.Flags & RestrictionFlags.TotalDigits) == 0 &&
(_baseFlags & RestrictionFlags.TotalDigits) != 0
)
{
_derivedRestriction.TotalDigits = baseRestriction.TotalDigits;
SetFlag(RestrictionFlags.TotalDigits);
}
if (
(_derivedRestriction.Flags & RestrictionFlags.FractionDigits) == 0 &&
(_baseFlags & RestrictionFlags.FractionDigits) != 0
)
{
_derivedRestriction.FractionDigits = baseRestriction.FractionDigits;
SetFlag(RestrictionFlags.FractionDigits);
}
}
private object ParseFacetValue(XmlSchemaDatatype datatype, XmlSchemaFacet facet, string code, IXmlNamespaceResolver nsmgr, XmlNameTable nameTable)
{
object typedValue;
Exception ex = datatype.TryParseValue(facet.Value, nameTable, nsmgr, out typedValue);
if (ex == null)
{
return typedValue;
}
else
{
throw new XmlSchemaException(code, new string[] { ex.Message }, ex, facet.SourceUri, facet.LineNumber, facet.LinePosition, facet);
}
}
private struct Map
{
internal Map(char m, string r)
{
match = m;
replacement = r;
}
internal char match;
internal string replacement;
};
private static readonly Map[] s_map = {
new Map('c', "\\p{_xmlC}"),
new Map('C', "\\P{_xmlC}"),
new Map('d', "\\p{_xmlD}"),
new Map('D', "\\P{_xmlD}"),
new Map('i', "\\p{_xmlI}"),
new Map('I', "\\P{_xmlI}"),
new Map('w', "\\p{_xmlW}"),
new Map('W', "\\P{_xmlW}"),
};
private static string Preprocess(string pattern)
{
StringBuilder bufBld = new StringBuilder();
bufBld.Append("^");
char[] source = pattern.ToCharArray();
int length = pattern.Length;
int copyPosition = 0;
for (int position = 0; position < length - 2; position++)
{
if (source[position] == '\\')
{
if (source[position + 1] == '\\')
{
position++; // skip it
}
else
{
char ch = source[position + 1];
for (int i = 0; i < s_map.Length; i++)
{
if (s_map[i].match == ch)
{
if (copyPosition < position)
{
bufBld.Append(source, copyPosition, position - copyPosition);
}
bufBld.Append(s_map[i].replacement);
position++;
copyPosition = position + 1;
break;
}
}
}
}
}
if (copyPosition < length)
{
bufBld.Append(source, copyPosition, length - copyPosition);
}
bufBld.Append("$");
return bufBld.ToString();
}
private void CheckProhibitedFlag(XmlSchemaFacet facet, RestrictionFlags flag, string errorCode)
{
if ((_validRestrictionFlags & flag) == 0)
{
throw new XmlSchemaException(errorCode, _datatype.TypeCodeString, facet);
}
}
private void CheckDupFlag(XmlSchemaFacet facet, RestrictionFlags flag, string errorCode)
{
if ((_derivedRestriction.Flags & flag) != 0)
{
throw new XmlSchemaException(errorCode, facet);
}
}
private void SetFlag(XmlSchemaFacet facet, RestrictionFlags flag)
{
_derivedRestriction.Flags |= flag;
if (facet.IsFixed)
{
_derivedRestriction.FixedFlags |= flag;
}
}
private void SetFlag(RestrictionFlags flag)
{
_derivedRestriction.Flags |= flag;
if ((_baseFixedFlags & flag) != 0)
{
_derivedRestriction.FixedFlags |= flag;
}
}
}
internal virtual Exception CheckLexicalFacets(ref string parseString, XmlSchemaDatatype datatype)
{
CheckWhitespaceFacets(ref parseString, datatype);
return CheckPatternFacets(datatype.Restriction, parseString);
}
internal virtual Exception CheckValueFacets(object value, XmlSchemaDatatype datatype)
{
return null;
}
internal virtual Exception CheckValueFacets(decimal value, XmlSchemaDatatype datatype)
{
return null;
}
internal virtual Exception CheckValueFacets(long value, XmlSchemaDatatype datatype)
{
return null;
}
internal virtual Exception CheckValueFacets(int value, XmlSchemaDatatype datatype)
{
return null;
}
internal virtual Exception CheckValueFacets(short value, XmlSchemaDatatype datatype)
{
return null;
}
internal virtual Exception CheckValueFacets(DateTime value, XmlSchemaDatatype datatype)
{
return null;
}
internal virtual Exception CheckValueFacets(double value, XmlSchemaDatatype datatype)
{
return null;
}
internal virtual Exception CheckValueFacets(float value, XmlSchemaDatatype datatype)
{
return null;
}
internal virtual Exception CheckValueFacets(string value, XmlSchemaDatatype datatype)
{
return null;
}
internal virtual Exception CheckValueFacets(byte[] value, XmlSchemaDatatype datatype)
{
return null;
}
internal virtual Exception CheckValueFacets(TimeSpan value, XmlSchemaDatatype datatype)
{
return null;
}
internal virtual Exception CheckValueFacets(XmlQualifiedName value, XmlSchemaDatatype datatype)
{
return null;
}
internal void CheckWhitespaceFacets(ref string s, XmlSchemaDatatype datatype)
{
// before parsing, check whitespace facet
RestrictionFacets restriction = datatype.Restriction;
switch (datatype.Variety)
{
case XmlSchemaDatatypeVariety.List:
s = s.Trim();
break;
case XmlSchemaDatatypeVariety.Atomic:
if (datatype.BuiltInWhitespaceFacet == XmlSchemaWhiteSpace.Collapse)
{
s = XmlComplianceUtil.NonCDataNormalize(s);
}
else if (datatype.BuiltInWhitespaceFacet == XmlSchemaWhiteSpace.Replace)
{
s = XmlComplianceUtil.CDataNormalize(s);
}
else if (restriction != null && (restriction.Flags & RestrictionFlags.WhiteSpace) != 0)
{ //Restriction has whitespace facet specified
if (restriction.WhiteSpace == XmlSchemaWhiteSpace.Replace)
{
s = XmlComplianceUtil.CDataNormalize(s);
}
else if (restriction.WhiteSpace == XmlSchemaWhiteSpace.Collapse)
{
s = XmlComplianceUtil.NonCDataNormalize(s);
}
}
break;
default:
break;
}
}
internal Exception CheckPatternFacets(RestrictionFacets restriction, string value)
{
if (restriction != null && (restriction.Flags & RestrictionFlags.Pattern) != 0)
{
for (int i = 0; i < restriction.Patterns.Count; ++i)
{
Regex regex = (Regex)restriction.Patterns[i];
if (!regex.IsMatch(value))
{
return new XmlSchemaException(SR.Sch_PatternConstraintFailed, string.Empty);
}
}
}
return null;
}
internal virtual bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype)
{
return false;
}
//Compile-time Facet Checking
internal virtual RestrictionFacets ConstructRestriction(DatatypeImplementation datatype, XmlSchemaObjectCollection facets, XmlNameTable nameTable)
{
//Datatype is the type on which this method is called
RestrictionFacets derivedRestriction = new RestrictionFacets();
FacetsCompiler facetCompiler = new FacetsCompiler(datatype, derivedRestriction);
for (int i = 0; i < facets.Count; ++i)
{
XmlSchemaFacet facet = (XmlSchemaFacet)facets[i];
if (facet.Value == null)
{
throw new XmlSchemaException(SR.Sch_InvalidFacet, facet);
}
IXmlNamespaceResolver nsmgr = new SchemaNamespaceManager(facet);
switch (facet.FacetType)
{
case FacetType.Length:
facetCompiler.CompileLengthFacet(facet);
break;
case FacetType.MinLength:
facetCompiler.CompileMinLengthFacet(facet);
break;
case FacetType.MaxLength:
facetCompiler.CompileMaxLengthFacet(facet);
break;
case FacetType.Pattern:
facetCompiler.CompilePatternFacet(facet as XmlSchemaPatternFacet);
break;
case FacetType.Enumeration:
facetCompiler.CompileEnumerationFacet(facet, nsmgr, nameTable);
break;
case FacetType.Whitespace:
facetCompiler.CompileWhitespaceFacet(facet);
break;
case FacetType.MinInclusive:
facetCompiler.CompileMinInclusiveFacet(facet);
break;
case FacetType.MinExclusive:
facetCompiler.CompileMinExclusiveFacet(facet);
break;
case FacetType.MaxInclusive:
facetCompiler.CompileMaxInclusiveFacet(facet);
break;
case FacetType.MaxExclusive:
facetCompiler.CompileMaxExclusiveFacet(facet);
break;
case FacetType.TotalDigits:
facetCompiler.CompileTotalDigitsFacet(facet);
break;
case FacetType.FractionDigits:
facetCompiler.CompileFractionDigitsFacet(facet);
break;
default:
throw new XmlSchemaException(SR.Sch_UnknownFacet, facet);
}
}
facetCompiler.FinishFacetCompile();
facetCompiler.CompileFacetCombinations();
return derivedRestriction;
}
internal static decimal Power(int x, int y)
{
//Returns X raised to the power Y
decimal returnValue = 1m;
decimal decimalValue = (decimal)x;
if (y > 28)
{ //CLR decimal cannot handle more than 29 digits (10 power 28.)
return decimal.MaxValue;
}
for (int i = 0; i < y; i++)
{
returnValue = returnValue * decimalValue;
}
return returnValue;
}
}
internal class Numeric10FacetsChecker : FacetsChecker
{
private static readonly char[] s_signs = new char[] { '+', '-' };
private decimal _maxValue;
private decimal _minValue;
internal Numeric10FacetsChecker(decimal minVal, decimal maxVal)
{
_minValue = minVal;
_maxValue = maxVal;
}
internal override Exception CheckValueFacets(object value, XmlSchemaDatatype datatype)
{
decimal decimalValue = datatype.ValueConverter.ToDecimal(value);
return CheckValueFacets(decimalValue, datatype);
}
internal override Exception CheckValueFacets(decimal value, XmlSchemaDatatype datatype)
{
RestrictionFacets restriction = datatype.Restriction;
RestrictionFlags flags = restriction != null ? restriction.Flags : 0;
XmlValueConverter valueConverter = datatype.ValueConverter;
//Check built-in facets
if (value > _maxValue || value < _minValue)
{
return new OverflowException(SR.Format(SR.XmlConvert_Overflow, value.ToString(CultureInfo.InvariantCulture), datatype.TypeCodeString));
}
//Check user-defined facets
if (flags != 0)
{
if ((flags & RestrictionFlags.MaxInclusive) != 0)
{
if (value > valueConverter.ToDecimal(restriction.MaxInclusive))
{
return new XmlSchemaException(SR.Sch_MaxInclusiveConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.MaxExclusive) != 0)
{
if (value >= valueConverter.ToDecimal(restriction.MaxExclusive))
{
return new XmlSchemaException(SR.Sch_MaxExclusiveConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.MinInclusive) != 0)
{
if (value < valueConverter.ToDecimal(restriction.MinInclusive))
{
return new XmlSchemaException(SR.Sch_MinInclusiveConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.MinExclusive) != 0)
{
if (value <= valueConverter.ToDecimal(restriction.MinExclusive))
{
return new XmlSchemaException(SR.Sch_MinExclusiveConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.Enumeration) != 0)
{
if (!MatchEnumeration(value, restriction.Enumeration, valueConverter))
{
return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty);
}
}
return CheckTotalAndFractionDigits(value, restriction.TotalDigits, restriction.FractionDigits, ((flags & RestrictionFlags.TotalDigits) != 0), ((flags & RestrictionFlags.FractionDigits) != 0));
}
return null;
}
internal override Exception CheckValueFacets(long value, XmlSchemaDatatype datatype)
{
decimal decimalValue = (decimal)value;
return CheckValueFacets(decimalValue, datatype);
}
internal override Exception CheckValueFacets(int value, XmlSchemaDatatype datatype)
{
decimal decimalValue = (decimal)value;
return CheckValueFacets(decimalValue, datatype);
}
internal override Exception CheckValueFacets(short value, XmlSchemaDatatype datatype)
{
decimal decimalValue = (decimal)value;
return CheckValueFacets(decimalValue, datatype);
}
internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype)
{
return MatchEnumeration(datatype.ValueConverter.ToDecimal(value), enumeration, datatype.ValueConverter);
}
internal bool MatchEnumeration(decimal value, ArrayList enumeration, XmlValueConverter valueConverter)
{
for (int i = 0; i < enumeration.Count; ++i)
{
if (value == valueConverter.ToDecimal(enumeration[i]))
{
return true;
}
}
return false;
}
internal Exception CheckTotalAndFractionDigits(decimal value, int totalDigits, int fractionDigits, bool checkTotal, bool checkFraction)
{
decimal maxValue = FacetsChecker.Power(10, totalDigits) - 1; //(decimal)Math.Pow(10, totalDigits) - 1 ;
int powerCnt = 0;
if (value < 0)
{
value = decimal.Negate(value); //Need to compare maxValue allowed against the absolute value
}
while (decimal.Truncate(value) != value)
{ //Till it has a fraction
value = value * 10;
powerCnt++;
}
if (checkTotal && (value > maxValue || powerCnt > totalDigits))
{
return new XmlSchemaException(SR.Sch_TotalDigitsConstraintFailed, string.Empty);
}
if (checkFraction && powerCnt > fractionDigits)
{
return new XmlSchemaException(SR.Sch_FractionDigitsConstraintFailed, string.Empty);
}
return null;
}
}
internal class Numeric2FacetsChecker : FacetsChecker
{
internal override Exception CheckValueFacets(object value, XmlSchemaDatatype datatype)
{
double doubleValue = datatype.ValueConverter.ToDouble(value);
return CheckValueFacets(doubleValue, datatype);
}
internal override Exception CheckValueFacets(double value, XmlSchemaDatatype datatype)
{
RestrictionFacets restriction = datatype.Restriction;
RestrictionFlags flags = restriction != null ? restriction.Flags : 0;
XmlValueConverter valueConverter = datatype.ValueConverter;
if ((flags & RestrictionFlags.MaxInclusive) != 0)
{
if (value > valueConverter.ToDouble(restriction.MaxInclusive))
{
return new XmlSchemaException(SR.Sch_MaxInclusiveConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.MaxExclusive) != 0)
{
if (value >= valueConverter.ToDouble(restriction.MaxExclusive))
{
return new XmlSchemaException(SR.Sch_MaxExclusiveConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.MinInclusive) != 0)
{
if (value < (valueConverter.ToDouble(restriction.MinInclusive)))
{
return new XmlSchemaException(SR.Sch_MinInclusiveConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.MinExclusive) != 0)
{
if (value <= valueConverter.ToDouble(restriction.MinExclusive))
{
return new XmlSchemaException(SR.Sch_MinExclusiveConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.Enumeration) != 0)
{
if (!MatchEnumeration(value, restriction.Enumeration, valueConverter))
{
return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty);
}
}
return null;
}
internal override Exception CheckValueFacets(float value, XmlSchemaDatatype datatype)
{
double doubleValue = (double)value;
return CheckValueFacets(doubleValue, datatype);
}
internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype)
{
return MatchEnumeration(datatype.ValueConverter.ToDouble(value), enumeration, datatype.ValueConverter);
}
private bool MatchEnumeration(double value, ArrayList enumeration, XmlValueConverter valueConverter)
{
for (int i = 0; i < enumeration.Count; ++i)
{
if (value == valueConverter.ToDouble(enumeration[i]))
{
return true;
}
}
return false;
}
}
internal class DurationFacetsChecker : FacetsChecker
{
internal override Exception CheckValueFacets(object value, XmlSchemaDatatype datatype)
{
TimeSpan timeSpanValue = (TimeSpan)datatype.ValueConverter.ChangeType(value, typeof(TimeSpan));
return CheckValueFacets(timeSpanValue, datatype);
}
internal override Exception CheckValueFacets(TimeSpan value, XmlSchemaDatatype datatype)
{
RestrictionFacets restriction = datatype.Restriction;
RestrictionFlags flags = restriction != null ? restriction.Flags : 0;
if ((flags & RestrictionFlags.MaxInclusive) != 0)
{
if (TimeSpan.Compare(value, (TimeSpan)restriction.MaxInclusive) > 0)
{
return new XmlSchemaException(SR.Sch_MaxInclusiveConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.MaxExclusive) != 0)
{
if (TimeSpan.Compare(value, (TimeSpan)restriction.MaxExclusive) >= 0)
{
return new XmlSchemaException(SR.Sch_MaxExclusiveConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.MinInclusive) != 0)
{
if (TimeSpan.Compare(value, (TimeSpan)restriction.MinInclusive) < 0)
{
return new XmlSchemaException(SR.Sch_MinInclusiveConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.MinExclusive) != 0)
{
if (TimeSpan.Compare(value, (TimeSpan)restriction.MinExclusive) <= 0)
{
return new XmlSchemaException(SR.Sch_MinExclusiveConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.Enumeration) != 0)
{
if (!MatchEnumeration(value, restriction.Enumeration))
{
return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty);
}
}
return null;
}
internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype)
{
return MatchEnumeration((TimeSpan)value, enumeration);
}
private bool MatchEnumeration(TimeSpan value, ArrayList enumeration)
{
for (int i = 0; i < enumeration.Count; ++i)
{
if (TimeSpan.Compare(value, (TimeSpan)enumeration[i]) == 0)
{
return true;
}
}
return false;
}
}
internal class DateTimeFacetsChecker : FacetsChecker
{
internal override Exception CheckValueFacets(object value, XmlSchemaDatatype datatype)
{
DateTime dateTimeValue = datatype.ValueConverter.ToDateTime(value);
return CheckValueFacets(dateTimeValue, datatype);
}
internal override Exception CheckValueFacets(DateTime value, XmlSchemaDatatype datatype)
{
RestrictionFacets restriction = datatype.Restriction;
RestrictionFlags flags = restriction != null ? restriction.Flags : 0;
if ((flags & RestrictionFlags.MaxInclusive) != 0)
{
if (datatype.Compare(value, (DateTime)restriction.MaxInclusive) > 0)
{
return new XmlSchemaException(SR.Sch_MaxInclusiveConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.MaxExclusive) != 0)
{
if (datatype.Compare(value, (DateTime)restriction.MaxExclusive) >= 0)
{
return new XmlSchemaException(SR.Sch_MaxExclusiveConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.MinInclusive) != 0)
{
if (datatype.Compare(value, (DateTime)restriction.MinInclusive) < 0)
{
return new XmlSchemaException(SR.Sch_MinInclusiveConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.MinExclusive) != 0)
{
if (datatype.Compare(value, (DateTime)restriction.MinExclusive) <= 0)
{
return new XmlSchemaException(SR.Sch_MinExclusiveConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.Enumeration) != 0)
{
if (!MatchEnumeration(value, restriction.Enumeration, datatype))
{
return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty);
}
}
return null;
}
internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype)
{
return MatchEnumeration(datatype.ValueConverter.ToDateTime(value), enumeration, datatype);
}
private bool MatchEnumeration(DateTime value, ArrayList enumeration, XmlSchemaDatatype datatype)
{
for (int i = 0; i < enumeration.Count; ++i)
{
if (datatype.Compare(value, (DateTime)enumeration[i]) == 0)
{
return true;
}
}
return false;
}
}
internal class StringFacetsChecker : FacetsChecker
{ //All types derived from string & anyURI
private static Regex s_languagePattern;
private static Regex LanguagePattern
{
get
{
if (s_languagePattern == null)
{
Regex langRegex = new Regex("^([a-zA-Z]{1,8})(-[a-zA-Z0-9]{1,8})*$", RegexOptions.None);
Interlocked.CompareExchange(ref s_languagePattern, langRegex, null);
}
return s_languagePattern;
}
}
internal override Exception CheckValueFacets(object value, XmlSchemaDatatype datatype)
{
string stringValue = datatype.ValueConverter.ToString(value);
return CheckValueFacets(stringValue, datatype, true);
}
internal override Exception CheckValueFacets(string value, XmlSchemaDatatype datatype)
{
return CheckValueFacets(value, datatype, true);
}
internal Exception CheckValueFacets(string value, XmlSchemaDatatype datatype, bool verifyUri)
{
//Length, MinLength, MaxLength
int length = value.Length;
RestrictionFacets restriction = datatype.Restriction;
RestrictionFlags flags = restriction != null ? restriction.Flags : 0;
Exception exception;
exception = CheckBuiltInFacets(value, datatype.TypeCode, verifyUri);
if (exception != null) return exception;
if (flags != 0)
{
if ((flags & RestrictionFlags.Length) != 0)
{
if (restriction.Length != length)
{
return new XmlSchemaException(SR.Sch_LengthConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.MinLength) != 0)
{
if (length < restriction.MinLength)
{
return new XmlSchemaException(SR.Sch_MinLengthConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.MaxLength) != 0)
{
if (restriction.MaxLength < length)
{
return new XmlSchemaException(SR.Sch_MaxLengthConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.Enumeration) != 0)
{
if (!MatchEnumeration(value, restriction.Enumeration, datatype))
{
return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty);
}
}
}
return null;
}
internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype)
{
return MatchEnumeration(datatype.ValueConverter.ToString(value), enumeration, datatype);
}
private bool MatchEnumeration(string value, ArrayList enumeration, XmlSchemaDatatype datatype)
{
if (datatype.TypeCode == XmlTypeCode.AnyUri)
{
for (int i = 0; i < enumeration.Count; ++i)
{
if (value.Equals(((Uri)enumeration[i]).OriginalString))
{
return true;
}
}
}
else
{
for (int i = 0; i < enumeration.Count; ++i)
{
if (value.Equals((string)enumeration[i]))
{
return true;
}
}
}
return false;
}
private Exception CheckBuiltInFacets(string s, XmlTypeCode typeCode, bool verifyUri)
{
Exception exception = null;
switch (typeCode)
{
case XmlTypeCode.AnyUri:
if (verifyUri)
{
Uri uri;
exception = XmlConvert.TryToUri(s, out uri);
}
break;
case XmlTypeCode.NormalizedString:
exception = XmlConvert.TryVerifyNormalizedString(s);
break;
case XmlTypeCode.Token:
exception = XmlConvert.TryVerifyTOKEN(s);
break;
case XmlTypeCode.Language:
if (s == null || s.Length == 0)
{
return new XmlSchemaException(SR.Sch_EmptyAttributeValue, string.Empty);
}
if (!LanguagePattern.IsMatch(s))
{
return new XmlSchemaException(SR.Sch_InvalidLanguageId, string.Empty);
}
break;
case XmlTypeCode.NmToken:
exception = XmlConvert.TryVerifyNMTOKEN(s);
break;
case XmlTypeCode.Name:
exception = XmlConvert.TryVerifyName(s);
break;
case XmlTypeCode.NCName:
case XmlTypeCode.Id:
case XmlTypeCode.Idref:
case XmlTypeCode.Entity:
exception = XmlConvert.TryVerifyNCName(s);
break;
default:
break;
}
return exception;
}
}
internal class QNameFacetsChecker : FacetsChecker
{
internal override Exception CheckValueFacets(object value, XmlSchemaDatatype datatype)
{
XmlQualifiedName qualifiedNameValue = (XmlQualifiedName)datatype.ValueConverter.ChangeType(value, typeof(XmlQualifiedName));
return CheckValueFacets(qualifiedNameValue, datatype);
}
internal override Exception CheckValueFacets(XmlQualifiedName value, XmlSchemaDatatype datatype)
{
RestrictionFacets restriction = datatype.Restriction;
RestrictionFlags flags = restriction != null ? restriction.Flags : 0;
if (flags != 0)
{ //If there are facets defined
string strValue = value.ToString();
int length = strValue.Length;
if ((flags & RestrictionFlags.Length) != 0)
{
if (restriction.Length != length)
{
return new XmlSchemaException(SR.Sch_LengthConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.MinLength) != 0)
{
if (length < restriction.MinLength)
{
return new XmlSchemaException(SR.Sch_MinLengthConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.MaxLength) != 0)
{
if (restriction.MaxLength < length)
{
return new XmlSchemaException(SR.Sch_MaxLengthConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.Enumeration) != 0)
{
if (!MatchEnumeration(value, restriction.Enumeration))
{
return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty);
}
}
}
return null;
}
internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype)
{
return MatchEnumeration((XmlQualifiedName)datatype.ValueConverter.ChangeType(value, typeof(XmlQualifiedName)), enumeration);
}
private bool MatchEnumeration(XmlQualifiedName value, ArrayList enumeration)
{
for (int i = 0; i < enumeration.Count; ++i)
{
if (value.Equals((XmlQualifiedName)enumeration[i]))
{
return true;
}
}
return false;
}
}
internal class MiscFacetsChecker : FacetsChecker
{ //For bool, anySimpleType
}
internal class BinaryFacetsChecker : FacetsChecker
{ //hexBinary & Base64Binary
internal override Exception CheckValueFacets(object value, XmlSchemaDatatype datatype)
{
byte[] byteArrayValue = (byte[])value;
return CheckValueFacets(byteArrayValue, datatype);
}
internal override Exception CheckValueFacets(byte[] value, XmlSchemaDatatype datatype)
{
//Length, MinLength, MaxLength
RestrictionFacets restriction = datatype.Restriction;
int length = value.Length;
RestrictionFlags flags = restriction != null ? restriction.Flags : 0;
if (flags != 0)
{ //if it has facets defined
if ((flags & RestrictionFlags.Length) != 0)
{
if (restriction.Length != length)
{
return new XmlSchemaException(SR.Sch_LengthConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.MinLength) != 0)
{
if (length < restriction.MinLength)
{
return new XmlSchemaException(SR.Sch_MinLengthConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.MaxLength) != 0)
{
if (restriction.MaxLength < length)
{
return new XmlSchemaException(SR.Sch_MaxLengthConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.Enumeration) != 0)
{
if (!MatchEnumeration(value, restriction.Enumeration, datatype))
{
return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty);
}
}
}
return null;
}
internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype)
{
return MatchEnumeration((byte[])value, enumeration, datatype);
}
private bool MatchEnumeration(byte[] value, ArrayList enumeration, XmlSchemaDatatype datatype)
{
for (int i = 0; i < enumeration.Count; ++i)
{
if (datatype.Compare(value, (byte[])enumeration[i]) == 0)
{
return true;
}
}
return false;
}
}
internal class ListFacetsChecker : FacetsChecker
{
internal override Exception CheckValueFacets(object value, XmlSchemaDatatype datatype)
{
//Check for facets allowed on lists - Length, MinLength, MaxLength
Array values = value as Array;
Debug.Assert(values != null);
RestrictionFacets restriction = datatype.Restriction;
RestrictionFlags flags = restriction != null ? restriction.Flags : 0;
if ((flags & (RestrictionFlags.Length | RestrictionFlags.MinLength | RestrictionFlags.MaxLength)) != 0)
{
int length = values.Length;
if ((flags & RestrictionFlags.Length) != 0)
{
if (restriction.Length != length)
{
return new XmlSchemaException(SR.Sch_LengthConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.MinLength) != 0)
{
if (length < restriction.MinLength)
{
return new XmlSchemaException(SR.Sch_MinLengthConstraintFailed, string.Empty);
}
}
if ((flags & RestrictionFlags.MaxLength) != 0)
{
if (restriction.MaxLength < length)
{
return new XmlSchemaException(SR.Sch_MaxLengthConstraintFailed, string.Empty);
}
}
}
if ((flags & RestrictionFlags.Enumeration) != 0)
{
if (!MatchEnumeration(value, restriction.Enumeration, datatype))
{
return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty);
}
}
return null;
}
internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype)
{
for (int i = 0; i < enumeration.Count; ++i)
{
if (datatype.Compare(value, enumeration[i]) == 0)
{
return true;
}
}
return false;
}
}
internal class UnionFacetsChecker : FacetsChecker
{
internal override Exception CheckValueFacets(object value, XmlSchemaDatatype datatype)
{
RestrictionFacets restriction = datatype.Restriction;
RestrictionFlags flags = restriction != null ? restriction.Flags : 0;
if ((flags & RestrictionFlags.Enumeration) != 0)
{
if (!MatchEnumeration(value, restriction.Enumeration, datatype))
{
return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty);
}
}
return null;
}
internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype)
{
for (int i = 0; i < enumeration.Count; ++i)
{
if (datatype.Compare(value, enumeration[i]) == 0)
{ //Compare on Datatype_union will compare two XsdSimpleValue
return true;
}
}
return false;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.11.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyFile
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// Files operations.
/// </summary>
public partial class Files : IServiceOperations<AutoRestSwaggerBATFileService>, IFiles
{
/// <summary>
/// Initializes a new instance of the Files class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public Files(AutoRestSwaggerBATFileService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestSwaggerBATFileService
/// </summary>
public AutoRestSwaggerBATFileService Client { get; private set; }
/// <summary>
/// Get file
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<System.IO.Stream>> GetFileWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// 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, "GetFile", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/files/stream/nonempty").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
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);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<System.IO.Stream>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
result.Body = await httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get empty file
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<System.IO.Stream>> GetEmptyFileWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// 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, "GetEmptyFile", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/files/stream/empty").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
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);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<System.IO.Stream>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
result.Body = await httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace liquicode.AppTools
{
[Serializable]
public abstract class CommandContext
{
}
public class Commands
{
//|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\\
//|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\\
[Serializable]
public class SettingsCommand : CommandContext
{
//---------------------------------------------------------------------
private Hashtable _out_Settings = new Hashtable();
public Hashtable out_Settings
{
get { return this._out_Settings; }
set { this._out_Settings = value; }
}
//---------------------------------------------------------------------
public SettingsCommand()
{ return; }
}
//|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\\
//|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\\
[Serializable]
public class ListEntriesCommand : CommandContext
{
//---------------------------------------------------------------------
private string _in_Pathname = "";
public string in_Pathname
{
get { return this._in_Pathname; }
set { this._in_Pathname = value; }
}
////---------------------------------------------------------------------
//private string _in_Pattern = "";
//public string in_Pattern
//{
// get { return this._in_Pattern; }
// set { this._in_Pattern = value; }
//}
//---------------------------------------------------------------------
private bool _in_IncludeFolders = false;
public bool in_IncludeFolders
{
get { return this._in_IncludeFolders; }
set { this._in_IncludeFolders = value; }
}
//---------------------------------------------------------------------
private bool _in_IncludeLinks = false;
public bool in_IncludeLinks
{
get { return this._in_IncludeLinks; }
set { this._in_IncludeLinks = value; }
}
//---------------------------------------------------------------------
private bool _in_IncludeFiles = false;
public bool in_IncludeFiles
{
get { return this._in_IncludeFiles; }
set { this._in_IncludeFiles = value; }
}
////---------------------------------------------------------------------
//private bool _in_IncludeSubfolders = false;
//public bool in_IncludeSubfolders
//{
// get { return this._in_IncludeSubfolders; }
// set { this._in_IncludeSubfolders = value; }
//}
//---------------------------------------------------------------------
private FileSystemItemList _out_ItemList = null;
public FileSystemItemList out_ItemList
{
get { return this._out_ItemList; }
set { this._out_ItemList = value; }
}
//---------------------------------------------------------------------
public ListEntriesCommand()
{ return; }
//---------------------------------------------------------------------
public ListEntriesCommand( string Pathname, bool IncludeFolders, bool IncludeLinks, bool IncludeFiles )
{
this._in_Pathname = Pathname;
this._in_IncludeFolders = IncludeFolders;
this._in_IncludeLinks = IncludeLinks;
this._in_IncludeFiles = IncludeFiles;
return;
}
}
//|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\\
//|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\\
[Serializable]
public class CreateItemCommand : CommandContext
{
//---------------------------------------------------------------------
private string _in_Pathname = "";
public string in_Pathname
{
get { return this._in_Pathname; }
set { this._in_Pathname = value; }
}
//---------------------------------------------------------------------
private bool _in_IsFolder = false;
public bool in_IsFolder
{
get { return this._in_IsFolder; }
set { this._in_IsFolder = value; }
}
//---------------------------------------------------------------------
private bool _in_CreatePath = false;
public bool in_CreatePath
{
get { return this._in_CreatePath; }
set { this._in_CreatePath = value; }
}
//---------------------------------------------------------------------
private FileSystemItem _out_Item = null;
public FileSystemItem out_Item
{
get { return this._out_Item; }
set { this._out_Item = value; }
}
//---------------------------------------------------------------------
public CreateItemCommand()
{ return; }
//---------------------------------------------------------------------
public CreateItemCommand( string Pathname, bool IsFolder, bool CreatePath )
{
this.in_Pathname = Pathname;
this._in_IsFolder = IsFolder;
this._in_CreatePath = CreatePath;
return;
}
}
//|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\\
//|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\\
[Serializable]
public class ReadItemCommand : CommandContext
{
//---------------------------------------------------------------------
private string _in_Pathname = "";
public string in_Pathname
{
get { return this._in_Pathname; }
set { this._in_Pathname = value; }
}
//---------------------------------------------------------------------
private FileSystemItem _out_Item = null;
public FileSystemItem out_Item
{
get { return this._out_Item; }
set { this._out_Item = value; }
}
//---------------------------------------------------------------------
public ReadItemCommand()
{ return; }
//---------------------------------------------------------------------
public ReadItemCommand( string Pathname )
{
this._in_Pathname = Pathname;
return;
}
}
//|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\\
//|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\\
[Serializable]
public class UpdateItemCommand : CommandContext
{
//---------------------------------------------------------------------
private string _in_Pathname = "";
public string in_Pathname
{
get { return this._in_Pathname; }
set { this._in_Pathname = value; }
}
//---------------------------------------------------------------------
private FileSystemItem _in_Item = null;
public FileSystemItem in_Item
{
get { return this._in_Item; }
set { this._in_Item = value; }
}
//---------------------------------------------------------------------
private bool _in_IsFolder = false;
public bool in_IsFolder
{
get { return this._in_IsFolder; }
set { this._in_IsFolder = value; }
}
//---------------------------------------------------------------------
private FileSystemItem _out_Item = null;
public FileSystemItem out_Item
{
get { return this._out_Item; }
set { this._out_Item = value; }
}
//---------------------------------------------------------------------
public UpdateItemCommand()
{ return; }
//---------------------------------------------------------------------
public UpdateItemCommand( string Pathname, bool IsFolder, FileSystemItem Item )
{
this._in_Pathname = Pathname;
this._in_IsFolder = IsFolder;
this._in_Item = Item;
return;
}
}
//|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\\
//|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\\
[Serializable]
public class DeleteItemCommand : CommandContext
{
//---------------------------------------------------------------------
private string _in_Pathname = "";
public string in_Pathname
{
get { return this._in_Pathname; }
set { this._in_Pathname = value; }
}
//---------------------------------------------------------------------
private bool _in_IsFolder = false;
public bool in_IsFolder
{
get { return this._in_IsFolder; }
set { this._in_IsFolder = value; }
}
//---------------------------------------------------------------------
public DeleteItemCommand()
{ return; }
//---------------------------------------------------------------------
public DeleteItemCommand( string Pathname, bool IsFolder )
{
this._in_Pathname = Pathname;
this._in_IsFolder = IsFolder;
return;
}
}
//|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\\
//|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\\
[Serializable]
public class ReadFileContentCommand : CommandContext
{
//---------------------------------------------------------------------
private string _in_Pathname = "";
public string in_Pathname
{
get { return this._in_Pathname; }
set { this._in_Pathname = value; }
}
//---------------------------------------------------------------------
private int _in_Offset = 0;
public int in_Offset
{
get { return this._in_Offset; }
set { this._in_Offset = value; }
}
//---------------------------------------------------------------------
private int _in_Length = -1;
public int in_Length
{
get { return this._in_Length; }
set { this._in_Length = value; }
}
//---------------------------------------------------------------------
private byte[] _out_Content = null;
public byte[] out_Content
{
get { return this._out_Content; }
set { this._out_Content = value; }
}
//---------------------------------------------------------------------
public ReadFileContentCommand()
{ return; }
//---------------------------------------------------------------------
public ReadFileContentCommand( string Pathname, int Offset, int Length )
{
this._in_Pathname = Pathname;
this._in_Offset = Offset;
this._in_Length = Length;
return;
}
//---------------------------------------------------------------------
public ReadFileContentCommand( string Pathname, int Offset )
: this( Pathname, Offset, -1 )
{ return; }
}
//|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\\
//|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\\
[Serializable]
public class WriteFileContentCommand : CommandContext
{
//---------------------------------------------------------------------
private string _in_Pathname = "";
public string in_Pathname
{
get { return this._in_Pathname; }
set { this._in_Pathname = value; }
}
//---------------------------------------------------------------------
private int _in_Offset = 0;
public int in_Offset
{
get { return this._in_Offset; }
set { this._in_Offset = value; }
}
//---------------------------------------------------------------------
private bool _in_Truncate = false;
public bool in_Truncate
{
get { return this._in_Truncate; }
set { this._in_Truncate = value; }
}
//---------------------------------------------------------------------
private byte[] _in_Content = null;
public byte[] in_Content
{
get { return this._in_Content; }
set { this._in_Content = value; }
}
//---------------------------------------------------------------------
private FileSystemItem _out_Item = null;
public FileSystemItem out_Item
{
get { return this._out_Item; }
set { this._out_Item = value; }
}
//---------------------------------------------------------------------
public WriteFileContentCommand()
{ return; }
//---------------------------------------------------------------------
public WriteFileContentCommand( string Pathname, int Offset, byte[] Content, bool Truncate )
{
this._in_Pathname = Pathname;
this._in_Offset = Offset;
this._in_Content = Content;
this._in_Truncate = Truncate;
return;
}
//---------------------------------------------------------------------
public WriteFileContentCommand( string Pathname, int Offset, byte[] Content )
: this( Pathname, Offset, Content, true )
{ return; }
}
//|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\\
//|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\\
}
}
| |
using System.Linq;
namespace System.Collections.Generic
{
public static class ListUtils
{
/// <summary>
/// Checks if 2 enumerables have the same elements in the same order
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns></returns>
public static bool HasTheSameElementsAs<T>(this IEnumerable<T> first,IEnumerable<T> second)
{
first.MustNotBeNull();
second.MustNotBeNull();
var cnt1 = first.Count();
if (cnt1 != second.Count()) return false;
T item1 = default(T);
T item2 = default(T);
for(int i=0;i<cnt1;i++)
{
item1 = first.Skip(i).Take(1).First();
item2 = second.Skip(i).Take(1).First();
if (!item1.Equals(item2)) return false;
}
return true;
}
/// <summary>
/// Compares two sequences and returns the added or removed items.
/// </summary>
/// <typeparam name="T">Implements IEquatable</typeparam>
/// <param name="fresh">Recent sequence</param>
/// <param name="old">Older sequence used as base of comparison</param>
/// <returns></returns>
public static IModifiedSet<T> Compare<T>(this IEnumerable<T> fresh, IEnumerable<T> old) where T:IEquatable<T>
{
if (fresh == null) throw new ArgumentNullException("fresh");
if (old == null) throw new ArgumentNullException("old");
var mods = new ModifiedSet<T>();
foreach (var item in old)
{
if (!fresh.Contains(item)) mods.RemovedItem(item);
}
foreach (var item in fresh)
{
if (!old.Contains(item)) mods.AddedItem(item);
}
return mods;
}
/// <summary>
/// Compares two sequences and returns the added or removed items.
/// Use this when T doesn't implement IEquatable
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="fresh">Recent sequence</param>
/// <param name="old">Older sequence used as base of comparison</param>
/// <param name="match">function to check equality</param>
/// <returns></returns>
public static IModifiedSet<T> Compare<T>(this IEnumerable<T> fresh, IEnumerable<T> old,Func<T,T,bool> match)
{
if (fresh == null) throw new ArgumentNullException("fresh");
if (old == null) throw new ArgumentNullException("old");
if (match == null) throw new ArgumentNullException("match");
var mods = new ModifiedSet<T>();
foreach (var item in old)
{
if (!fresh.Any(d=>match(d,item))) mods.RemovedItem(item);
}
foreach (var item in fresh)
{
if (!old.Any(d=>match(d,item))) mods.AddedItem(item);
}
return mods;
}
/// <summary>
/// Compares two sequences and returns the result.
/// This special case method is best used when you have identifiable objects that can change their content/value but not their id.
/// </summary>
/// <typeparam name="T">Implements IEquatable</typeparam>
/// <param name="fresh">Recent sequence</param>
/// <param name="old">Older sequence used as base of comparison</param>
/// <param name="detectChange">Delegate to determine if the items are identical.
/// First parameter is new item, second is the item used as base for comparison</param>
/// <returns></returns>
public static IModifiedSet<T> WhatChanged<T>(this IEnumerable<T> fresh, IEnumerable<T> old,Func<T,T,bool> detectChange) where T : IEquatable<T>
{
if (fresh == null) throw new ArgumentNullException("fresh");
if (old == null) throw new ArgumentNullException("old");
if (detectChange == null) throw new ArgumentNullException("detectChange");
var mods = new ModifiedSet<T>();
foreach (var item in old)
{
if (!fresh.Any(d=> d.Equals(item))) mods.RemovedItem(item);
}
foreach (var item in fresh)
{
if (!old.Any(d=>d.Equals(item))) mods.AddedItem(item);
else
{
var oldItem = old.First(d => d.Equals(item));
if (detectChange(item,oldItem))
{
mods.ModifiedItem(oldItem,item);
}
}
}
return mods;
}
/// <summary>
/// Updates the old collection with new items, while removing the inexistent.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="old"></param>
/// <param name="fresh"></param>
/// <returns></returns>
public static void Update<T>(this IList<T> old,IEnumerable<T> fresh) where T:IEquatable<T>
{
if (old == null) throw new ArgumentNullException("old");
if (fresh == null) throw new ArgumentNullException("fresh");
var diff = fresh.Compare(old);
foreach (var item in diff.Removed)
{
old.Remove(item);
}
foreach (var item in diff.Added)
{
old.Add(item);
}
}
/// <summary>
/// Updates the old collection with new items, while removing the inexistent.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="old"></param>
/// <param name="fresh"></param>
/// <returns></returns>
public static void Update<T>(this IList<T> old, IEnumerable<T> fresh,Func<T,T,bool> isEqual)
{
if (old == null) throw new ArgumentNullException("old");
if (fresh == null) throw new ArgumentNullException("fresh");
var diff = fresh.Compare(old,isEqual);
foreach (var item in diff.Removed)
{
var i = old.Where(d => isEqual(d, item)).Select((d,idx)=>idx).First();
old.RemoveAt(i);
}
foreach (var item in diff.Added)
{
old.Add(item);
}
}
/// <summary>
/// Checks if a collection is null or empty duh!
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="items">collection</param>
/// <returns></returns>
public static bool IsNullOrEmpty<T>(this IEnumerable<T> items)
{
return items == null || !items.Any();
}
/// <summary>
/// Gets typed value from dictionary or a default value if key is missing
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dic"></param>
/// <param name="key"></param>
/// <param name="defValue">Value to return if dictionary doesn't contain the key</param>
/// <returns></returns>
public static T GetValue<T>(this IDictionary<string,object> dic,string key,T defValue=default(T))
{
if (dic.ContainsKey(key)) return dic[key].Cast<T>();
return defValue;
}
public static bool AddIfNotPresent<T>(this IList<T> list, T item)
{
list.MustNotBeNull();
if (!list.Contains(item))
{
list.Add(item);
return true;
}
return false;
}
/// <summary>
/// Returns number of items removed
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <param name="predicate"></param>
/// <returns></returns>
public static int RemoveAll<T>(this IList<T> items, Func<T, bool> predicate)
{
items.MustNotBeEmpty();
predicate.MustNotBeNull();
var removed = 0;
for (int i = items.Count - 1; i >= 0; i--)
{
if (predicate(items[i]))
{
items.RemoveAt(i);
removed++;
}
}
return removed;
}
}
}
| |
using UnityEngine;
using System.Collections;
/// <summary>
/// Provides base functionality to handle textures with multiple image frames.
/// </summary>
[ExecuteInEditMode]
public class OTContainer : MonoBehaviour
{
/// <exclude />
public string _name = "";
bool registered = false;
/// <exclude />
protected bool dirtyContainer = true;
/// <exclude />
protected string _name_ = "";
/// <summary>
/// Stores texture data of a specific container frame.
/// </summary>
public struct Frame
{
/// <summary>
/// This frame's name
/// </summary>
public string name;
/// <summary>
/// This frame's image scale modifier
/// </summary>
public Vector2 size;
/// <summary>
/// This frame's original image size
/// </summary>
public Vector2 imageSize;
/// <summary>
/// This frame's world position offset modifier
/// </summary>
public Vector2 offset;
/// <summary>
/// This frame's world rotation modifier
/// </summary>
public float rotation;
/// <summary>
/// Texture UV coordinates (x/y).
/// </summary>
public Vector2[] uv;
/// <summary>
/// Mesh vertices used when OffsetSizing = false (Atlas)
/// </summary>
public Vector3[] vertices;
}
Frame[] frames = { };
/// <summary>
/// Name of the container
/// </summary>
new public string name
{
get
{
return _name;
}
set
{
string old = _name;
_name = value;
gameObject.name = _name;
if (OT.isValid)
{
_name_ = _name;
OT.RegisterContainerLookup(this, old);
}
}
}
/// <summary>
/// Container ready indicator.
/// </summary>
/// <remarks>
/// Container frame data or container texture can only be accessed when a container is ready.
/// Be sure to check this when retrieving data programmaticly.
/// </remarks>
public bool isReady
{
get
{
return frames.Length > 0;
}
}
/// <summary>
/// Number of frames in this container.
/// </summary>
public int frameCount
{
get
{
return frames.Length;
}
}
/// <summary>
/// Overridable virtal method to provide a container's texture
/// </summary>
/// <returns>Container's texture</returns>
public virtual Texture GetTexture()
{
return null;
}
/// <summary>
/// Overridable virtal method to provide the container's frames
/// </summary>
/// <returns>Container's array of frames</returns>
protected virtual Frame[] GetFrames()
{
return new Frame[] { };
}
/// <summary>
/// Return the frame number by its name or -1 if it doesn't exist.
/// </summary>
public virtual int GetFrameIndex(string inName)
{
for (int i = 0; i < frames.Length; ++i)
{
if (frames[i].name == inName)
{
return i;
}
}
return -1;
}
protected void Awake()
{
#if UNITY_EDITOR
if (!Application.isPlaying)
UnityEditor.PrefabUtility.RecordPrefabInstancePropertyModifications(this);
#endif
}
// Use this for initialization
/// <exclude />
protected void Start()
{
// initialize attributes
// initialize attributes
_name_ = name;
if (name == "")
{
name = "Container (id=" + this.gameObject.GetInstanceID() + ")";
#if UNITY_EDITOR
if (!Application.isPlaying)
UnityEditor.PrefabUtility.RecordPrefabInstancePropertyModifications(this);
#endif
}
RegisterContainer();
}
/// <summary>
/// Retrieve a specific container frame.
/// </summary>
/// <remarks>
/// The container frame contains data about each frame's texture offset and UV coordinates. The texture offset and scale
/// is used when this frame is mapped onto a single sprite. The UV coordinates are used when this images has to be mapped onto
/// a multi sprite mesh ( a SpriteBatch for example ).
/// <br></br><br></br>
/// When the index is out of bounce, an IndexOutOfRangeException will be raised.
/// </remarks>
/// <param name="index">Index of container frame to retrieve. (starting at 0)</param>
/// <returns>Retrieved container frame.</returns>
public Frame GetFrame(int index)
{
if (frames.Length > index)
return frames[index];
else
{
throw new System.IndexOutOfRangeException("Frame index out of bounds ["+index+"]");
}
}
void RegisterContainer()
{
if (OT.ContainerByName(name) == null)
{
OT.RegisterContainer(this);
gameObject.name = name;
registered = true;
}
if (_name_ != name)
{
OT.RegisterContainerLookup(this, _name_);
_name_ = name;
gameObject.name = name;
}
if (name != gameObject.name)
{
name = gameObject.name;
OT.RegisterContainerLookup(this, _name_);
_name_ = name;
#if UNITY_EDITOR
if (!Application.isPlaying)
UnityEditor.PrefabUtility.RecordPrefabInstancePropertyModifications(this);
#endif
}
}
// Update is called once per frame
/// <exclude />
protected void Update()
{
if (!OT.isValid) return;
if (!registered || !Application.isPlaying)
RegisterContainer();
if (frames.Length == 0 && !dirtyContainer)
dirtyContainer = true;
if (dirtyContainer || !isReady)
{
frames = GetFrames();
dirtyContainer = false;
}
}
void OnDestroy()
{
if (OT.isValid)
OT.RemoveContainer(this);
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2015-04-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Container for the parameters to the ModifyImageAttribute operation.
/// Modifies the specified attribute of the specified AMI. You can specify only one attribute
/// at a time.
///
/// <note>
/// <para>
/// AWS Marketplace product codes cannot be modified. Images with an AWS Marketplace product
/// code cannot be made public.
/// </para>
/// </note>
/// </summary>
public partial class ModifyImageAttributeRequest : AmazonEC2Request
{
private string _attribute;
private string _description;
private string _imageId;
private LaunchPermissionModifications _launchPermission;
private OperationType _operationType;
private List<string> _productCodes = new List<string>();
private List<string> _userGroups = new List<string>();
private List<string> _userIds = new List<string>();
private string _value;
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public ModifyImageAttributeRequest() { }
/// <summary>
/// Instantiates ModifyImageAttributeRequest with the parameterized properties
/// </summary>
/// <param name="imageId">The ID of the AMI.</param>
/// <param name="attribute">The name of the attribute to modify.</param>
public ModifyImageAttributeRequest(string imageId, string attribute)
{
_imageId = imageId;
_attribute = attribute;
}
/// <summary>
/// Gets and sets the property Attribute.
/// <para>
/// The name of the attribute to modify.
/// </para>
/// </summary>
public string Attribute
{
get { return this._attribute; }
set { this._attribute = value; }
}
// Check to see if Attribute property is set
internal bool IsSetAttribute()
{
return this._attribute != null;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// A description for the AMI.
/// </para>
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property ImageId.
/// <para>
/// The ID of the AMI.
/// </para>
/// </summary>
public string ImageId
{
get { return this._imageId; }
set { this._imageId = value; }
}
// Check to see if ImageId property is set
internal bool IsSetImageId()
{
return this._imageId != null;
}
/// <summary>
/// Gets and sets the property LaunchPermission.
/// <para>
/// A launch permission modification.
/// </para>
/// </summary>
public LaunchPermissionModifications LaunchPermission
{
get { return this._launchPermission; }
set { this._launchPermission = value; }
}
// Check to see if LaunchPermission property is set
internal bool IsSetLaunchPermission()
{
return this._launchPermission != null;
}
/// <summary>
/// Gets and sets the property OperationType.
/// <para>
/// The operation type.
/// </para>
/// </summary>
public OperationType OperationType
{
get { return this._operationType; }
set { this._operationType = value; }
}
// Check to see if OperationType property is set
internal bool IsSetOperationType()
{
return this._operationType != null;
}
/// <summary>
/// Gets and sets the property ProductCodes.
/// <para>
/// One or more product codes. After you add a product code to an AMI, it can't be removed.
/// This is only valid when modifying the <code>productCodes</code> attribute.
/// </para>
/// </summary>
public List<string> ProductCodes
{
get { return this._productCodes; }
set { this._productCodes = value; }
}
// Check to see if ProductCodes property is set
internal bool IsSetProductCodes()
{
return this._productCodes != null && this._productCodes.Count > 0;
}
/// <summary>
/// Gets and sets the property UserGroups.
/// <para>
/// One or more user groups. This is only valid when modifying the <code>launchPermission</code>
/// attribute.
/// </para>
/// </summary>
public List<string> UserGroups
{
get { return this._userGroups; }
set { this._userGroups = value; }
}
// Check to see if UserGroups property is set
internal bool IsSetUserGroups()
{
return this._userGroups != null && this._userGroups.Count > 0;
}
/// <summary>
/// Gets and sets the property UserIds.
/// <para>
/// One or more AWS account IDs. This is only valid when modifying the <code>launchPermission</code>
/// attribute.
/// </para>
/// </summary>
public List<string> UserIds
{
get { return this._userIds; }
set { this._userIds = value; }
}
// Check to see if UserIds property is set
internal bool IsSetUserIds()
{
return this._userIds != null && this._userIds.Count > 0;
}
/// <summary>
/// Gets and sets the property Value.
/// <para>
/// The value of the attribute being modified. This is only valid when modifying the <code>description</code>
/// attribute.
/// </para>
/// </summary>
public string Value
{
get { return this._value; }
set { this._value = value; }
}
// Check to see if Value property is set
internal bool IsSetValue()
{
return this._value != null;
}
}
}
| |
/*
* ClientAO.cs: GridProxy application that acts as a client side animation overrider.
* The application will start and stop animations corresponding to the movements
* of the avatar on screen.
*
* Copyright (c) 2007 Gilbert Roulot
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the Second Life Reverse Engineering Team nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.IO;
using System.Reflection;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenMetaverse.StructuredData;
using Nwc.XmlRpc;
using GridProxy;
public class ClientAO : ProxyPlugin
{
private ProxyFrame frame;
private Proxy proxy;
private UUID[] wetikonanims = {
Animations.WALK,
Animations.RUN,
Animations.CROUCHWALK,
Animations.FLY,
Animations.TURNLEFT,
Animations.TURNRIGHT,
Animations.JUMP,
Animations.HOVER_UP,
Animations.CROUCH,
Animations.HOVER_DOWN,
Animations.STAND,
Animations.STAND_1,
Animations.STAND_2,
Animations.STAND_3,
Animations.STAND_4,
Animations.HOVER,
Animations.SIT,
Animations.PRE_JUMP,
Animations.FALLDOWN,
Animations.LAND,
Animations.STANDUP,
Animations.FLYSLOW,
Animations.SIT_GROUND_staticRAINED,
UUID.Zero, //swimming doesnt exist
UUID.Zero,
UUID.Zero,
UUID.Zero
};
private string[] wetikonanimnames = {
"walk",
"run",
"crouch walk",
"fly",
"turn left",
"turn right",
"jump",
"hover up",
"crouch",
"hover down",
"stand",
"stand 2",
"stand 3",
"stand 4",
"stand 5",
"hover",
"sit",
"pre jump",
"fall down",
"land",
"stand up",
"fly slow",
"sit on ground",
"swim (ignored)", //swimming doesnt exist
"swim (ignored)",
"swim (ignored)",
"swim (ignored)"
};
private Dictionary<UUID, string> animuid2name;
//private Assembly libslAssembly;
#region Packet delegates members
private PacketDelegate _packetDelegate;
private PacketDelegate packetDelegate
{
get
{
if (_packetDelegate == null)
{
_packetDelegate = new PacketDelegate(AnimationPacketHandler);
}
return _packetDelegate;
}
}
private PacketDelegate _inventoryPacketDelegate;
private PacketDelegate inventoryPacketDelegate
{
get
{
if (_inventoryPacketDelegate == null)
{
_inventoryPacketDelegate = new PacketDelegate(InventoryDescendentsHandler);
}
return _inventoryPacketDelegate;
}
}
private PacketDelegate _transferPacketDelegate;
private PacketDelegate transferPacketDelegate
{
get
{
if (_transferPacketDelegate == null)
{
_transferPacketDelegate = new PacketDelegate(TransferPacketHandler);
}
return _transferPacketDelegate;
}
}
// private PacketDelegate _transferInfoDelegate;
// private PacketDelegate transferInfoDelegate
// {
// get
// {
// if (_transferInfoDelegate == null)
// {
// _transferInfoDelegate = new PacketDelegate(TransferInfoHandler);
// }
// return _transferInfoDelegate;
// }
// }
#endregion
//map of built in SL animations and their overrides
private Dictionary<UUID,UUID> overrides = new Dictionary<UUID,UUID>();
//list of animations currently running
private Dictionary<UUID, int> SignaledAnimations = new Dictionary<UUID, int>();
//playing status of animations'override animation
private Dictionary<UUID, bool> overrideanimationisplaying;
//Current inventory path search
string[] searchPath;
//Search level
int searchLevel;
//Current folder
UUID currentFolder;
// Number of directory descendents received
int nbdescendantsreceived;
//List of items in the current folder
Dictionary<string,InventoryItem> currentFolderItems;
//Asset download request ID
UUID assetdownloadID;
//Downloaded bytes so far
int downloadedbytes;
//size of download
int downloadsize;
//data buffer
byte[] buffer;
public ClientAO(ProxyFrame frame)
{
this.frame = frame;
this.proxy = frame.proxy;
}
//Initialise the plugin
public override void Init()
{
//libslAssembly = Assembly.Load("libsecondlife");
//if (libslAssembly == null) throw new Exception("Assembly load exception");
// build the table of /command delegates
InitializeCommandDelegates();
SayToUser("ClientAO loaded");
}
// InitializeCommandDelegates: configure ClientAO's commands
private void InitializeCommandDelegates()
{
//The ClientAO responds to command beginning with /ao
frame.AddCommand("/ao", new ProxyFrame.CommandDelegate(CmdAO));
}
//Process commands from the user
private void CmdAO(string[] words) {
if (words.Length < 2)
{
SayToUser("Usage: /ao on/off/notecard path");
}
else if (words[1] == "on")
{
//Turn AO on
AOOn();
SayToUser("AO started");
}
else if (words[1] == "off")
{
//Turn AO off
AOOff();
SayToUser("AO stopped");
}
else
{
//Load notecard from path
//exemple: /ao Objects/My AOs/wetikon/config.txt
string[] tmp = new string[words.Length - 1];
//join the arguments together with spaces, to
//take care of folder and item names with spaces in them
for (int i = 1; i < words.Length; i++)
{
tmp[i - 1] = words[i];
}
// add a delegate to monitor inventory infos
proxy.AddDelegate(PacketType.InventoryDescendents, Direction.Incoming, this.inventoryPacketDelegate);
RequestFindObjectByPath(frame.InventoryRoot, String.Join(" ", tmp));
}
}
private void AOOn()
{
// add a delegate to track agent movements
proxy.AddDelegate(PacketType.AvatarAnimation, Direction.Incoming, this.packetDelegate);
}
private void AOOff()
{
// remove the delegate to track agent movements
proxy.RemoveDelegate(PacketType.AvatarAnimation, Direction.Incoming, this.packetDelegate);
//Stop all override animations
foreach (UUID tmp in overrides.Values)
{
Animate(tmp, false);
}
}
// Inventory functions
//start requesting an item by its path
public void RequestFindObjectByPath(UUID baseFolder, string path)
{
if (path == null || path.Length == 0)
throw new ArgumentException("Empty path is not supported");
currentFolder = baseFolder;
//split path by '/'
searchPath = path.Split('/');
//search for first element in the path
searchLevel = 0;
// Start the search
RequestFolderContents(baseFolder,
true,
(searchPath.Length == 1) ? true : false,
InventorySortOrder.ByName);
}
//request a folder content
public void RequestFolderContents(UUID folder, bool folders, bool items,
InventorySortOrder order)
{
//empty the dictionnary containing current folder items by name
currentFolderItems = new Dictionary<string, InventoryItem>();
//reset the number of descendants received
nbdescendantsreceived = 0;
//build a packet to request the content
FetchInventoryDescendentsPacket fetch = new FetchInventoryDescendentsPacket();
fetch.AgentData.AgentID = frame.AgentID;
fetch.AgentData.SessionID = frame.SessionID;
fetch.InventoryData.FetchFolders = folders;
fetch.InventoryData.FetchItems = items;
fetch.InventoryData.FolderID = folder;
fetch.InventoryData.OwnerID = frame.AgentID; //is it correct?
fetch.InventoryData.SortOrder = (int)order;
//send packet to SL
proxy.InjectPacket(fetch, Direction.Outgoing);
}
//process the reply from SL
private Packet InventoryDescendentsHandler(Packet packet, IPEndPoint sim)
{
bool intercept = false;
InventoryDescendentsPacket reply = (InventoryDescendentsPacket)packet;
if (reply.AgentData.Descendents > 0
&& reply.AgentData.FolderID == currentFolder)
{
//SayToUser("nb descendents: " + reply.AgentData.Descendents);
//this packet concerns the folder we asked for
if (reply.FolderData[0].FolderID != UUID.Zero
&& searchLevel < searchPath.Length - 1)
{
nbdescendantsreceived += reply.FolderData.Length;
//SayToUser("nb received: " + nbdescendantsreceived);
//folders are present, and we are not at end of path.
//look at them
for (int i = 0; i < reply.FolderData.Length; i++)
{
//SayToUser("Folder: " + Utils.BytesToString(reply.FolderData[i].Name));
if (searchPath[searchLevel] == Utils.BytesToString(reply.FolderData[i].Name)) {
//We found the next folder in the path
currentFolder = reply.FolderData[i].FolderID;
if (searchLevel < searchPath.Length - 1)
{
// ask for next item in path
searchLevel++;
RequestFolderContents(currentFolder,
true,
(searchLevel < searchPath.Length - 1) ? false : true,
InventorySortOrder.ByName);
//Jump to end
goto End;
}
}
}
if (nbdescendantsreceived >= reply.AgentData.Descendents)
{
//We have not found the folder. The user probably mistyped it
SayToUser("Didn't find folder " + searchPath[searchLevel]);
//Stop looking at packets
proxy.RemoveDelegate(PacketType.InventoryDescendents, Direction.Incoming, this.inventoryPacketDelegate);
}
}
else if (searchLevel < searchPath.Length - 1)
{
//There are no folders in the packet ; but we are looking for one!
//We have not found the folder. The user probably mistyped it
SayToUser("Didn't find folder " + searchPath[searchLevel]);
//Stop looking at packets
proxy.RemoveDelegate(PacketType.InventoryDescendents, Direction.Incoming, this.inventoryPacketDelegate);
}
else
{
//There are folders in the packet. And we are at the end of
//the path, count their number in nbdescendantsreceived
nbdescendantsreceived += reply.FolderData.Length;
//SayToUser("nb received: " + nbdescendantsreceived);
}
if (reply.ItemData[0].ItemID != UUID.Zero
&& searchLevel == searchPath.Length - 1)
{
//there are items returned and we are looking for one
//(end of search path)
//count them
nbdescendantsreceived += reply.ItemData.Length;
//SayToUser("nb received: " + nbdescendantsreceived);
for (int i = 0; i < reply.ItemData.Length; i++)
{
//we are going to store info on all items. we'll need
//it to get the asset ID of animations refered to by the
//configuration notecard
if (reply.ItemData[i].ItemID != UUID.Zero)
{
InventoryItem item = CreateInventoryItem((InventoryType)reply.ItemData[i].InvType, reply.ItemData[i].ItemID);
item.ParentUUID = reply.ItemData[i].FolderID;
item.CreatorID = reply.ItemData[i].CreatorID;
item.AssetType = (AssetType)reply.ItemData[i].Type;
item.AssetUUID = reply.ItemData[i].AssetID;
item.CreationDate = Utils.UnixTimeToDateTime((uint)reply.ItemData[i].CreationDate);
item.Description = Utils.BytesToString(reply.ItemData[i].Description);
item.Flags = (uint)reply.ItemData[i].Flags;
item.Name = Utils.BytesToString(reply.ItemData[i].Name);
item.GroupID = reply.ItemData[i].GroupID;
item.GroupOwned = reply.ItemData[i].GroupOwned;
item.Permissions = new Permissions(
reply.ItemData[i].BaseMask,
reply.ItemData[i].EveryoneMask,
reply.ItemData[i].GroupMask,
reply.ItemData[i].NextOwnerMask,
reply.ItemData[i].OwnerMask);
item.SalePrice = reply.ItemData[i].SalePrice;
item.SaleType = (SaleType)reply.ItemData[i].SaleType;
item.OwnerID = reply.AgentData.OwnerID;
//SayToUser("item in folder: " + item.Name);
//Add the item to the name -> item hash
currentFolderItems.Add(item.Name, item);
}
}
if (nbdescendantsreceived >= reply.AgentData.Descendents)
{
//We have received all the items in the last folder
//Let's look for the item we are looking for
if (currentFolderItems.ContainsKey(searchPath[searchLevel]))
{
//We found what we where looking for
//Stop looking at packets
proxy.RemoveDelegate(PacketType.InventoryDescendents, Direction.Incoming, this.inventoryPacketDelegate);
//Download the notecard
assetdownloadID = RequestInventoryAsset(currentFolderItems[searchPath[searchLevel]]);
}
else
{
//We didnt find the item, the user probably mistyped its name
SayToUser("Didn't find notecard " + searchPath[searchLevel]);
//TODO: keep looking for a moment, or else reply packets may still
//come in case of a very large inventory folder
//Stop looking at packets
proxy.RemoveDelegate(PacketType.InventoryDescendents, Direction.Incoming, this.inventoryPacketDelegate);
}
}
}
else if (searchLevel == searchPath.Length - 1 && nbdescendantsreceived >= reply.AgentData.Descendents)
{
//There are no items in the packet, but we are looking for one!
//We didnt find the item, the user probably mistyped its name
SayToUser("Didn't find notecard " + searchPath[searchLevel]);
//TODO: keep looking for a moment, or else reply packets may still
//come in case of a very large inventory folder
//Stop looking at packets
proxy.RemoveDelegate(PacketType.InventoryDescendents, Direction.Incoming, this.inventoryPacketDelegate);
}
//Intercept the packet, it was a reply to our request. No need
//to confuse the actual SL client
intercept = true;
}
End:
if (intercept)
{
//stop packet
return null;
}
else
{
//let packet go to client
return packet;
}
}
public static InventoryItem CreateInventoryItem(InventoryType type, UUID id)
{
switch (type)
{
case InventoryType.Texture: return new InventoryTexture(id);
case InventoryType.Sound: return new InventorySound(id);
case InventoryType.CallingCard: return new InventoryCallingCard(id);
case InventoryType.Landmark: return new InventoryLandmark(id);
case InventoryType.Object: return new InventoryObject(id);
case InventoryType.Notecard: return new InventoryNotecard(id);
case InventoryType.Category: return new InventoryCategory(id);
case InventoryType.LSL: return new InventoryLSL(id);
case InventoryType.Snapshot: return new InventorySnapshot(id);
case InventoryType.Attachment: return new InventoryAttachment(id);
case InventoryType.Wearable: return new InventoryWearable(id);
case InventoryType.Animation: return new InventoryAnimation(id);
case InventoryType.Gesture: return new InventoryGesture(id);
default: return new InventoryItem(type, id);
}
}
//Ask for download of an item
public UUID RequestInventoryAsset(InventoryItem item)
{
// Build the request packet and send it
TransferRequestPacket request = new TransferRequestPacket();
request.TransferInfo.ChannelType = (int)ChannelType.Asset;
request.TransferInfo.Priority = 101.0f;
request.TransferInfo.SourceType = (int)SourceType.SimInventoryItem;
UUID transferID = UUID.Random();
request.TransferInfo.TransferID = transferID;
byte[] paramField = new byte[100];
Buffer.BlockCopy(frame.AgentID.GetBytes(), 0, paramField, 0, 16);
Buffer.BlockCopy(frame.SessionID.GetBytes(), 0, paramField, 16, 16);
Buffer.BlockCopy(item.OwnerID.GetBytes(), 0, paramField, 32, 16);
Buffer.BlockCopy(UUID.Zero.GetBytes(), 0, paramField, 48, 16);
Buffer.BlockCopy(item.UUID.GetBytes(), 0, paramField, 64, 16);
Buffer.BlockCopy(item.AssetUUID.GetBytes(), 0, paramField, 80, 16);
Buffer.BlockCopy(Utils.IntToBytes((int)item.AssetType), 0, paramField, 96, 4);
request.TransferInfo.Params = paramField;
// add a delegate to monitor configuration notecards download
proxy.AddDelegate(PacketType.TransferPacket, Direction.Incoming, this.transferPacketDelegate);
//send packet to SL
proxy.InjectPacket(request, Direction.Outgoing);
//so far we downloaded 0 bytes
downloadedbytes = 0;
//the total size of the download is yet unknown
downloadsize = 0;
//A 100K buffer should be enough for everyone
buffer = new byte[1024 * 100];
//Return the transfer ID
return transferID;
}
// SayToUser: send a message to the user as in-world chat
private void SayToUser(string message)
{
ChatFromSimulatorPacket packet = new ChatFromSimulatorPacket();
packet.ChatData.FromName = Utils.StringToBytes("ClientAO");
packet.ChatData.SourceID = UUID.Random();
packet.ChatData.OwnerID = frame.AgentID;
packet.ChatData.SourceType = (byte)2;
packet.ChatData.ChatType = (byte)1;
packet.ChatData.Audible = (byte)1;
packet.ChatData.Position = new Vector3(0, 0, 0);
packet.ChatData.Message = Utils.StringToBytes(message);
proxy.InjectPacket(packet, Direction.Incoming);
}
//start or stop an animation
public void Animate(UUID animationuuid, bool run)
{
AgentAnimationPacket animate = new AgentAnimationPacket();
animate.Header.Reliable = true;
animate.AgentData.AgentID = frame.AgentID;
animate.AgentData.SessionID = frame.SessionID;
//We send one animation
animate.AnimationList = new AgentAnimationPacket.AnimationListBlock[1];
animate.AnimationList[0] = new AgentAnimationPacket.AnimationListBlock();
animate.AnimationList[0].AnimID = animationuuid;
animate.AnimationList[0].StartAnim = run;
animate.PhysicalAvatarEventList = new AgentAnimationPacket.PhysicalAvatarEventListBlock[0];
//SayToUser("anim " + animname(animationuuid) + " " + run);
proxy.InjectPacket(animate, Direction.Outgoing);
}
//return the name of an animation by its UUID
// private string animname(UUID arg)
// {
// return animuid2name[arg];
// }
//handle animation packets from simulator
private Packet AnimationPacketHandler(Packet packet, IPEndPoint sim) {
AvatarAnimationPacket animation = (AvatarAnimationPacket)packet;
if (animation.Sender.ID == frame.AgentID)
{
//the received animation packet is about our Agent, handle it
lock (SignaledAnimations)
{
// Reset the signaled animation list
SignaledAnimations.Clear();
//fill it with the fresh list from simulator
for (int i = 0; i < animation.AnimationList.Length; i++)
{
UUID animID = animation.AnimationList[i].AnimID;
int sequenceID = animation.AnimationList[i].AnimSequenceID;
// Add this animation to the list of currently signaled animations
SignaledAnimations[animID] = sequenceID;
//SayToUser("Animation: " + animname(animID));
}
}
//we now have a list of currently running animations
//Start override animations if necessary
foreach (UUID key in overrides.Keys)
{
//For each overriden animation key, test if its override is running
if (SignaledAnimations.ContainsKey(key) && (!overrideanimationisplaying[key] ))
{
//An overriden animation is present and its override animation
//isnt currently playing
//Start the override animation
//SayToUser("animation " + animname(key) + " started, will override with " + animname(overrides[key]));
overrideanimationisplaying[key] = true;
Animate(overrides[key], true);
}
else if ((!SignaledAnimations.ContainsKey(key)) && overrideanimationisplaying[key])
{
//an override animation is currently playing, but it's overriden
//animation is not.
//stop the override animation
//SayToUser("animation " + animname(key) + " stopped, will override with " + animname(overrides[key]));
overrideanimationisplaying[key] = false;
Animate(overrides[key], false);
}
}
}
//Let the packet go to the client
return packet;
}
//handle packets that contain info about the notecard data transfer
// private Packet TransferInfoHandler(Packet packet, IPEndPoint simulator)
// {
// TransferInfoPacket info = (TransferInfoPacket)packet;
//
// if (info.TransferInfo.TransferID == assetdownloadID)
// {
// //this is our requested tranfer, handle it
// downloadsize = info.TransferInfo.Size;
//
// if ((StatusCode)info.TransferInfo.Status != StatusCode.OK)
// {
// SayToUser("Failed to read notecard");
// }
// if (downloadedbytes >= downloadsize)
// {
// //Download already completed!
// downloadCompleted();
// }
// //intercept packet
// return null;
// }
// return packet;
// }
//handle packets which contain the notecard data
private Packet TransferPacketHandler(Packet packet, IPEndPoint simulator)
{
TransferPacketPacket asset = (TransferPacketPacket)packet;
if (asset.TransferData.TransferID == assetdownloadID) {
Buffer.BlockCopy(asset.TransferData.Data, 0, buffer, 1000 * asset.TransferData.Packet,
asset.TransferData.Data.Length);
downloadedbytes += asset.TransferData.Data.Length;
// Check if we downloaded the full asset
if (downloadedbytes >= downloadsize)
{
downloadCompleted();
}
//Intercept packet
return null;
}
return packet;
}
private void downloadCompleted()
{
//We have the notecard.
//Stop looking at transfer packets
proxy.RemoveDelegate(PacketType.TransferPacket, Direction.Incoming, this.transferPacketDelegate);
//crop the buffer size
byte[] tmp = new byte[downloadedbytes];
Buffer.BlockCopy(buffer, 0, tmp, 0, downloadedbytes);
buffer = tmp;
String notecardtext = getNotecardText(Utils.BytesToString(buffer));
//Load config, wetikon format
loadWetIkon(notecardtext);
}
private void loadWetIkon(string config)
{
//Reinitialise override table
overrides = new Dictionary<UUID,UUID>();
overrideanimationisplaying = new Dictionary<UUID, bool>();
animuid2name = new Dictionary<UUID,string>();
foreach (UUID key in wetikonanims )
{
animuid2name[key] = wetikonanimnames[Array.IndexOf(wetikonanims, key)];
}
//list of animations in wetikon
//read every second line in the config
char[] sep = { '\n' };
string[] lines = config.Split(sep);
int length = lines.Length;
int i = 1;
while (i < length) {
//Read animation name and look it up
string animname = lines[i].Trim();
//SayToUser("anim: " + animname);
if (animname != "")
{
if (currentFolderItems.ContainsKey(animname))
{
UUID over = currentFolderItems[animname].AssetUUID;
UUID orig = wetikonanims[((i + 1) / 2) - 1];
//put it in overrides
animuid2name[over] = animname;
overrides[orig] = over;
overrideanimationisplaying[orig] = false;
//SayToUser(wetikonanimnames[((i + 1) / 2) - 1] + " overriden by " + animname + " ( " + over + ")");
}
else
{
//Not found
SayToUser(animname + " not found.");
}
}
i += 2;
}
SayToUser("Notecard read, " + overrides.Count + " animations found");
}
private string getNotecardText(string data)
{
// Version 1 format:
// Linden text version 1
// {
// <EmbeddedItemList chunk>
// Text length
// <ASCII text; 0x80 | index = embedded item>
// }
// Version 2 format: (NOTE: Imports identically to version 1)
// Linden text version 2
// {
// <EmbeddedItemList chunk>
// Text length
// <UTF8 text; FIRST_EMBEDDED_CHAR + index = embedded item>
// }
int i = 0;
char[] sep = { '\n' };
string[] lines = data.Split(sep);
int length = lines.Length;
string result = "";
//check format
if (!lines[i].StartsWith("Linden text version "))
{
SayToUser("error");
return "";
}
//{
i++;
if (lines[i] != "{")
{
SayToUser("error");
return "";
}
i++;
if (lines[i] != "LLEmbeddedItems version 1")
{
SayToUser("error");
return "";
}
//{
i++;
if (lines[i] != "{")
{
SayToUser("error");
return "";
}
//count ...
i++;
if (!lines[i].StartsWith("count "))
{
SayToUser("error");
return "";
}
//}
i++;
if (lines[i] != "}")
{
SayToUser("error");
return "";
}
//Text length ...
i++;
if (!lines[i].StartsWith("Text length "))
{
SayToUser("error");
return "";
}
i++;
while (i < length)
{
result += lines[i] + "\n";
i++;
}
result = result.Substring(0, result.Length - 3);
return result;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Linq.Expressions;
using Signum.Utilities;
using Signum.Entities;
using Signum.Entities.Reflection;
using Signum.Utilities.Reflection;
using Signum.Utilities.ExpressionTrees;
using Signum.Engine.Maps;
using Signum.Entities.Basics;
using Signum.Entities.Internal;
using Signum.Utilities.DataStructures;
namespace Signum.Engine.Linq
{
internal static class TranslatorBuilder
{
internal static ITranslateResult Build(ProjectionExpression proj)
{
Type type = proj.UniqueFunction == null ? proj.Type.ElementType()! : proj.Type;
return miBuildPrivate.GetInvoker(type)(proj);
}
static GenericInvoker<Func<ProjectionExpression, ITranslateResult>> miBuildPrivate = new GenericInvoker<Func<ProjectionExpression, ITranslateResult>>(pe => BuildPrivate<int>(pe));
static TranslateResult<T> BuildPrivate<T>(ProjectionExpression proj)
{
var eagerChildProjections = EagerChildProjectionGatherer.Gatherer(proj).Select(cp => BuildChild(cp)).ToList();
var lazyChildProjections = LazyChildProjectionGatherer.Gatherer(proj).Select(cp => BuildChild(cp)).ToList();
Scope scope = new Scope(
alias :proj.Select.Alias,
positions: proj.Select.Columns.Select((c, i) => new { c.Name, i }).ToDictionary(p => p.Name!, p => p.i) /*CSBUG*/
);
Expression<Func<IProjectionRow, T>> lambda = ProjectionBuilder.Build<T>(proj.Projector, scope);
var command = QueryFormatter.Format(proj.Select);
var result = new TranslateResult<T>(
eagerProjections: eagerChildProjections,
lazyChildProjections: lazyChildProjections,
mainCommand: command,
projectorExpression: lambda,
unique: proj.UniqueFunction
);
return result;
}
static IChildProjection BuildChild(ChildProjectionExpression childProj)
{
var proj = childProj.Projection;
Type type = proj.UniqueFunction == null ? proj.Type.ElementType()! : proj.Type;
if(!type.IsInstantiationOf(typeof(KeyValuePair<,>)))
throw new InvalidOperationException("All child projections should create KeyValuePairs");
Scope scope = new Scope(
alias: proj.Select.Alias,
positions: proj.Select.Columns.Select((c, i) => new { c.Name, i }).ToDictionary(p => p.Name!, p => p.i) /*CSBUG*/
);
var types = type.GetGenericArguments();
var command = QueryFormatter.Format(proj.Select);
if (childProj.IsLazyMList)
{
types[1] = types[1].GetGenericArguments()[0];
return giLazyChild.GetInvoker(types)(proj.Projector, scope, childProj.Token, command);
}
else
{
return giEagerChild.GetInvoker(types)(proj.Projector, scope, childProj.Token, command);
}
}
static readonly GenericInvoker<Func<Expression, Scope, LookupToken, SqlPreCommandSimple, IChildProjection>> giLazyChild =
new GenericInvoker<Func<Expression, Scope, LookupToken, SqlPreCommandSimple, IChildProjection>>((proj, scope, token, sql) => LazyChild<int, bool>(proj, scope, token, sql));
static IChildProjection LazyChild<K, V>(Expression projector, Scope scope, LookupToken token, SqlPreCommandSimple command)
where K : notnull
{
var proj = ProjectionBuilder.Build<KeyValuePair<K, MList<V>.RowIdElement>>(projector, scope);
return new LazyChildProjection<K, V>(token, command, proj);
}
static readonly GenericInvoker<Func<Expression, Scope, LookupToken, SqlPreCommandSimple, IChildProjection>> giEagerChild =
new GenericInvoker<Func<Expression, Scope, LookupToken, SqlPreCommandSimple, IChildProjection>>((proj, scope, token, sql) => EagerChild<int, bool>(proj, scope, token, sql));
static IChildProjection EagerChild<K, V>(Expression projector, Scope scope, LookupToken token, SqlPreCommandSimple command)
{
var proj = ProjectionBuilder.Build<KeyValuePair<K, V>>(projector, scope);
return new EagerChildProjection<K, V>(token, command, proj);
}
public static SqlPreCommandSimple BuildCommandResult(CommandExpression command)
{
return QueryFormatter.Format(command);
}
public class LazyChildProjectionGatherer : DbExpressionVisitor
{
List<ChildProjectionExpression> list = new List<ChildProjectionExpression>();
public static List<ChildProjectionExpression> Gatherer(ProjectionExpression proj)
{
LazyChildProjectionGatherer pg = new LazyChildProjectionGatherer();
pg.Visit(proj);
return pg.list;
}
protected internal override Expression VisitChildProjection(ChildProjectionExpression child)
{
if (child.IsLazyMList)
list.Add(child);
var result = base.VisitChildProjection(child);
return result;
}
}
public class EagerChildProjectionGatherer : DbExpressionVisitor
{
List<ChildProjectionExpression> list = new List<ChildProjectionExpression>();
public static List<ChildProjectionExpression> Gatherer(ProjectionExpression proj)
{
EagerChildProjectionGatherer pg = new EagerChildProjectionGatherer();
pg.Visit(proj);
return pg.list;
}
protected internal override Expression VisitChildProjection(ChildProjectionExpression child)
{
var result = base.VisitChildProjection(child);
if (!child.IsLazyMList)
list.Add(child);
return result;
}
}
/// <summary>
/// ProjectionBuilder is a visitor that converts an projector expression
/// that constructs result objects out of ColumnExpressions into an actual
/// LambdaExpression that constructs result objects out of accessing fields
/// of a ProjectionRow
/// </summary>
public class ProjectionBuilder : DbExpressionVisitor
{
static readonly ParameterExpression row = Expression.Parameter(typeof(IProjectionRow), "row");
static readonly PropertyInfo piRetriever = ReflectionTools.GetPropertyInfo((IProjectionRow r) => r.Retriever);
static readonly MemberExpression retriever = Expression.Property(row, piRetriever);
static readonly FieldInfo fiId = ReflectionTools.GetFieldInfo((Entity i) => i.id);
static readonly MethodInfo miCached = ReflectionTools.GetMethodInfo((IRetriever r) => r.Complete<TypeEntity>(null, null!)).GetGenericMethodDefinition();
static readonly MethodInfo miRequest = ReflectionTools.GetMethodInfo((IRetriever r) => r.Request<TypeEntity>(null)).GetGenericMethodDefinition();
static readonly MethodInfo miRequestIBA = ReflectionTools.GetMethodInfo((IRetriever r) => r.RequestIBA<TypeEntity>(null, null)).GetGenericMethodDefinition();
static readonly MethodInfo miRequestLite = ReflectionTools.GetMethodInfo((IRetriever r) => r.RequestLite<TypeEntity>(null)).GetGenericMethodDefinition();
static readonly MethodInfo miModifiablePostRetrieving = ReflectionTools.GetMethodInfo((IRetriever r) => r.ModifiablePostRetrieving<EmbeddedEntity>(null)).GetGenericMethodDefinition();
Scope scope;
public ProjectionBuilder(Scope scope)
{
this.scope = scope;
}
static internal Expression<Func<IProjectionRow, T>> Build<T>(Expression expression, Scope scope)
{
ProjectionBuilder pb = new ProjectionBuilder(scope);
Expression body = pb.Visit(expression);
return Expression.Lambda<Func<IProjectionRow, T>>(body, row);
}
Expression NullifyColumn(Expression exp)
{
if (!(exp is ColumnExpression ce))
return exp;
if (ce.Type.IsNullable() || ce.Type.IsClass)
return ce;
return new ColumnExpression(ce.Type.Nullify(), ce.Alias, ce.Name);
}
protected override Expression VisitUnary(UnaryExpression u)
{
if (u.NodeType == ExpressionType.Convert && u.Operand is ColumnExpression && DiffersInNullability(u.Type, u.Operand.Type))
{
ColumnExpression column = (ColumnExpression)u.Operand;
return scope.GetColumnExpression(row, column.Alias, column.Name!, u.Type);
}
return base.VisitUnary(u);
}
bool DiffersInNullability(Type a, Type b)
{
return
a.IsValueType && a.Nullify() == b ||
b.IsValueType && b.Nullify() == a;
}
protected internal override Expression VisitColumn(ColumnExpression column)
{
return scope.GetColumnExpression(row, column.Alias, column.Name!, column.Type);
}
protected internal override Expression VisitChildProjection(ChildProjectionExpression child)
{
Expression outer = Visit(child.OuterKey);
if (outer != child.OuterKey)
child = new ChildProjectionExpression(child.Projection, outer, child.IsLazyMList, child.Type, child.Token);
return scope.LookupEager(row, child);
}
protected Expression VisitMListChildProjection(ChildProjectionExpression child, MemberExpression field)
{
Expression outer = Visit(child.OuterKey);
if (outer != child.OuterKey)
child = new ChildProjectionExpression(child.Projection, outer, child.IsLazyMList, child.Type, child.Token);
return scope.LookupMList(row, child, field);
}
protected internal override Expression VisitProjection(ProjectionExpression proj)
{
throw new InvalidOperationException("No ProjectionExpressions expected at this stage");
}
protected internal override MixinEntityExpression VisitMixinEntity(MixinEntityExpression me)
{
throw new InvalidOperationException("Impossible to retrieve MixinEntity {0} without their main entity".FormatWith(me.Type.Name));
}
protected internal override Expression VisitEntity(EntityExpression fieldInit)
{
Expression id = Visit(NullifyColumn(fieldInit.ExternalId));
if (fieldInit.TableAlias == null)
return Expression.Call(retriever, miRequest.MakeGenericMethod(fieldInit.Type), id);
ParameterExpression e = Expression.Parameter(fieldInit.Type, fieldInit.Type.Name.ToLower().Substring(0, 1));
var bindings =
fieldInit.Bindings
.Where(a => !ReflectionTools.FieldEquals(EntityExpression.IdField, a.FieldInfo))
.Select(b =>
{
var field = Expression.Field(e, b.FieldInfo);
var value = b.Binding is ChildProjectionExpression ?
VisitMListChildProjection((ChildProjectionExpression)b.Binding, field) :
Convert(Visit(b.Binding), b.FieldInfo.FieldType);
return (Expression)Expression.Assign(field, value);
}).ToList();
if (fieldInit.Mixins != null)
{
var blocks = fieldInit.Mixins.Select(m => AssignMixin(e, m)).ToList();
bindings.AddRange(blocks);
}
LambdaExpression lambda = Expression.Lambda(typeof(Action<>).MakeGenericType(fieldInit.Type), Expression.Block(bindings), e);
return Expression.Call(retriever, miCached.MakeGenericMethod(fieldInit.Type), id.Nullify(), lambda);
}
BlockExpression AssignMixin(ParameterExpression e, MixinEntityExpression m)
{
var mixParam = Expression.Parameter(m.Type);
var mixAssign = Expression.Assign(mixParam, Expression.Call(e, MixinDeclarations.miMixin.MakeGenericMethod(m.Type)));
var mixBindings = m.Bindings.Select(b =>
{
var field = Expression.Field(mixParam, b.FieldInfo);
var value = b.Binding is ChildProjectionExpression ?
VisitMListChildProjection((ChildProjectionExpression)b.Binding, field) :
Convert(Visit(b.Binding), b.FieldInfo.FieldType);
return (Expression)Expression.Assign(field, value);
}).ToList();
mixBindings.Insert(0, mixAssign);
mixBindings.Add(Expression.Call(retriever, miModifiablePostRetrieving.MakeGenericMethod(m.Type), mixParam));
return Expression.Block(new[] { mixParam }, mixBindings);
}
private Expression Convert(Expression expression, Type type)
{
if (expression.Type == type)
return expression;
return Expression.Convert(expression, type);
}
protected internal override Expression VisitEmbeddedEntity(EmbeddedEntityExpression eee)
{
var embeddedParam = Expression.Parameter(eee.Type);
var embeddedAssign = Expression.Assign(embeddedParam, Expression.New(eee.Type));
var embeddedBindings =
eee.Bindings.Select(b =>
{
var field = Expression.Field(embeddedParam, b.FieldInfo);
var value = b.Binding is ChildProjectionExpression ?
VisitMListChildProjection((ChildProjectionExpression)b.Binding, field) :
Convert(Visit(b.Binding), b.FieldInfo.FieldType);
return Expression.Assign(field, value);
}).ToList<Expression>();
embeddedBindings.Insert(0, embeddedAssign);
if (typeof(EmbeddedEntity).IsAssignableFrom(eee.Type))
{
embeddedBindings.Add(Expression.Call(retriever, miModifiablePostRetrieving.MakeGenericMethod(eee.Type), embeddedParam));
}
else
{
embeddedBindings.Add(embeddedParam);
}
var block = Expression.Block(eee.Type, new[] { embeddedParam }, embeddedBindings);
return Expression.Condition(Expression.Equal(Visit(eee.HasValue.Nullify()), Expression.Constant(true, typeof(bool?))),
block,
Expression.Constant(null, block.Type));
}
protected internal override Expression VisitImplementedBy(ImplementedByExpression rb)
{
return rb.Implementations.Select(ee => new When(Visit(ee.Value.ExternalId).NotEqualsNulll(), Visit(ee.Value))).ToCondition(rb.Type);
}
protected internal override Expression VisitImplementedByAll(ImplementedByAllExpression rba)
{
return Expression.Call(retriever, miRequestIBA.MakeGenericMethod(rba.Type),
Visit(NullifyColumn(rba.TypeId.TypeColumn)),
Visit(NullifyColumn(rba.Id)));
}
static readonly ConstantExpression NullType = Expression.Constant(null, typeof(Type));
static readonly ConstantExpression NullId = Expression.Constant(null, typeof(int?));
protected internal override Expression VisitTypeEntity(TypeEntityExpression typeFie)
{
return Expression.Condition(
Expression.NotEqual(Visit(NullifyColumn(typeFie.ExternalId)), NullId),
Expression.Constant(typeFie.TypeValue, typeof(Type)),
NullType);
}
protected internal override Expression VisitTypeImplementedBy(TypeImplementedByExpression typeIb)
{
return typeIb.TypeImplementations.Reverse().Aggregate((Expression)NullType, (acum, imp) => Expression.Condition(
Expression.NotEqual(Visit(NullifyColumn(imp.Value)), NullId),
Expression.Constant(imp.Key, typeof(Type)),
acum));
}
static MethodInfo miGetType = ReflectionTools.GetMethodInfo((Schema s) => s.GetType(1));
protected internal override Expression VisitTypeImplementedByAll(TypeImplementedByAllExpression typeIba)
{
return Expression.Condition(
Expression.NotEqual(Visit(NullifyColumn(typeIba.TypeColumn)), NullId),
SchemaGetType(typeIba),
NullType);
}
private MethodCallExpression SchemaGetType(TypeImplementedByAllExpression typeIba)
{
return Expression.Call(Expression.Constant(Schema.Current), miGetType, Visit(typeIba.TypeColumn).UnNullify());
}
protected internal override Expression VisitLiteReference(LiteReferenceExpression lite)
{
var reference = Visit(lite.Reference);
var toStr = Visit(lite.CustomToStr);
return Lite.ToLiteFatInternalExpression(reference, toStr ?? Expression.Constant(null, typeof(string)));
}
protected internal override Expression VisitLiteValue(LiteValueExpression lite)
{
var id = Visit(NullifyColumn(lite.Id));
if (id == null)
return Expression.Constant(null, lite.Type);
var toStr = Visit(lite.ToStr);
var typeId = lite.TypeId;
var toStringOrNull = toStr ?? Expression.Constant(null, typeof(string));
Expression nothing = Expression.Constant(null, lite.Type);
Expression liteConstructor;
if (typeId is TypeEntityExpression)
{
Type type = ((TypeEntityExpression)typeId).TypeValue;
liteConstructor = Expression.Condition(Expression.NotEqual(id, NullId),
Expression.Convert(Lite.NewExpression(type, id, toStringOrNull), lite.Type),
nothing);
}
else if (typeId is TypeImplementedByExpression tib)
{
liteConstructor = tib.TypeImplementations.Aggregate(nothing,
(acum, ti) =>
{
var visitId = Visit(NullifyColumn(ti.Value));
return Expression.Condition(Expression.NotEqual(visitId, NullId),
Expression.Convert(Lite.NewExpression(ti.Key, visitId, toStringOrNull), lite.Type), acum);
});
}
else if (typeId is TypeImplementedByAllExpression tiba)
{
var tid = Visit(NullifyColumn(tiba.TypeColumn));
liteConstructor = Expression.Convert(Expression.Call(miLiteCreateParse, Expression.Constant(Schema.Current), tid, id.UnNullify(), toStringOrNull), lite.Type);
}
else
{
liteConstructor = Expression.Condition(Expression.NotEqual(id.Nullify(), NullId),
Expression.Convert(Expression.Call(miLiteCreate, Visit(typeId), id.UnNullify(), toStringOrNull), lite.Type),
nothing);
}
if (toStr != null)
return Expression.Call(retriever, miModifiablePostRetrieving.MakeGenericMethod(typeof(LiteImp)), liteConstructor.TryConvert(typeof(LiteImp))).TryConvert(liteConstructor.Type);
else
return Expression.Call(retriever, miRequestLite.MakeGenericMethod(Lite.Extract(lite.Type)!), liteConstructor);
}
static readonly MethodInfo miLiteCreateParse = ReflectionTools.GetMethodInfo(() => LiteCreateParse(null!, null, null!, null!));
static Lite<Entity>? LiteCreateParse(Schema schema, PrimaryKey? typeId, string id, string toString)
{
if (typeId == null)
return null;
Type type = schema.GetType(typeId.Value);
return Lite.Create(type, PrimaryKey.Parse(id, type), toString);
}
static MethodInfo miLiteCreate = ReflectionTools.GetMethodInfo(() => Lite.Create(null!, 0, null));
protected internal override Expression VisitMListElement(MListElementExpression mle)
{
Type type = mle.Type;
var bindings = new List<MemberAssignment>
{
Expression.Bind(type.GetProperty("RowId"), Visit(mle.RowId.UnNullify())),
Expression.Bind(type.GetProperty("Parent"), Visit(mle.Parent)),
};
if (mle.Order != null)
bindings.Add(Expression.Bind(type.GetProperty("Order"), Visit(mle.Order)));
bindings.Add(Expression.Bind(type.GetProperty("Element"), Visit(mle.Element)));
var init = Expression.MemberInit(Expression.New(type), bindings);
return Expression.Condition(SmartEqualizer.NotEqualNullable(Visit(mle.RowId.Nullify()), NullId),
init,
Expression.Constant(null, init.Type));
}
private Type? ConstantType(Expression typeId)
{
if (typeId.NodeType == ExpressionType.Convert)
typeId = ((UnaryExpression)typeId).Operand;
if (typeId.NodeType == ExpressionType.Constant)
return (Type)((ConstantExpression)typeId).Value;
return null;
}
protected internal override Expression VisitSqlConstant(SqlConstantExpression sce)
{
return Expression.Constant(sce.Value, sce.Type);
}
protected internal override Expression VisitPrimaryKey(PrimaryKeyExpression pk)
{
var val = Visit(pk.Value);
return Expression.Call(miWrap, Expression.Convert(val, typeof(IComparable)));
}
static readonly MethodInfo miWrap = ReflectionTools.GetMethodInfo(() => PrimaryKey.Wrap(1));
protected internal override Expression VisitPrimaryKeyString(PrimaryKeyStringExpression pk)
{
var id = this.Visit(pk.Id);
var type = this.Visit(pk.TypeId);
return Expression.Call(miTryParse, type, id);
}
static readonly MethodInfo miTryParse = ReflectionTools.GetMethodInfo(() => TryParse(null!, null!));
static PrimaryKey? TryParse(Type type, string id)
{
if (type == null)
return null;
return PrimaryKey.Parse(id, type);
}
protected internal override Expression VisitToDayOfWeek(ToDayOfWeekExpression toDayOfWeek)
{
var result = this.Visit(toDayOfWeek.Expression);
if (Schema.Current.Settings.IsPostgres)
{
return Expression.Call(ToDayOfWeekExpression.miToDayOfWeekPostgres, result);
}
else
{
var dateFirst = ((SqlServerConnector)Connector.Current).DateFirst;
return Expression.Call(ToDayOfWeekExpression.miToDayOfWeekSql, result, Expression.Constant(dateFirst, typeof(byte)));
}
}
static MethodInfo miToInterval = ReflectionTools.GetMethodInfo(() => ToInterval<int>(new NpgsqlTypes.NpgsqlRange<int>())).GetGenericMethodDefinition();
static Interval<T> ToInterval<T>(NpgsqlTypes.NpgsqlRange<T> range) where T : struct, IComparable<T>, IEquatable<T>
=> new Interval<T>(range.LowerBound, range.UpperBound);
protected internal override Expression VisitInterval(IntervalExpression interval)
{
var intervalType = interval.Type.GetGenericArguments()[0];
if (Schema.Current.Settings.IsPostgres)
{
return Expression.Call(miToInterval.MakeGenericMethod(intervalType), Visit(interval.PostgresRange));
}
else
{
return Expression.New(typeof(Interval<>).MakeGenericType(intervalType).GetConstructor(new[] { intervalType, intervalType })!, Visit(interval.Min), Visit(interval.Max));
}
}
protected override Expression VisitNew(NewExpression node)
{
var expressions = this.Visit(node.Arguments);
if (node.Members != null)
{
for (int i = 0; i < node.Members.Count; i++)
{
var m = node.Members[i];
var e = expressions[i];
if (m is PropertyInfo pi && !pi.PropertyType.IsAssignableFrom(e.Type))
{
throw new InvalidOperationException(
$"Impossible to assign a '{e.Type.TypeName()}' to the member '{m.Name}' of type '{pi.PropertyType.TypeName()}'." +
(e.Type.IsInstantiationOf(typeof(IEnumerable<>)) ? "\nConsider adding '.ToList()' at the end of your sub-query" : null)
);
}
}
}
return (Expression)node.Update(expressions);
}
}
}
internal class Scope
{
public Alias Alias;
public Dictionary<string, int> Positions;
public Scope(Alias alias, Dictionary<string, int> positions)
{
Alias = alias;
Positions = positions;
}
static readonly PropertyInfo miReader = ReflectionTools.GetPropertyInfo((IProjectionRow row) => row.Reader);
public Expression GetColumnExpression(Expression row, Alias alias, string name, Type type)
{
if (alias != Alias)
throw new InvalidOperationException("alias '{0}' not found".FormatWith(alias));
int position = Positions.GetOrThrow(name, "column name '{0}' not found in alias '" + alias + "'");
return FieldReader.GetExpression(Expression.Property(row, miReader), position, type);
}
static readonly MethodInfo miLookupRequest = ReflectionTools.GetMethodInfo((IProjectionRow row) => row.LookupRequest<int, double>(null!, 0, null!)).GetGenericMethodDefinition();
static readonly MethodInfo miLookup = ReflectionTools.GetMethodInfo((IProjectionRow row) => row.Lookup<int, double>(null!, 0)).GetGenericMethodDefinition();
public Expression LookupEager(Expression row, ChildProjectionExpression cProj)
{
if (cProj.IsLazyMList)
throw new InvalidOperationException("IsLazyMList not expected at this stage");
Type type = cProj.Projection.UniqueFunction == null ? cProj.Type.ElementType()! : cProj.Type;
MethodInfo mi = miLookup.MakeGenericMethod(cProj.OuterKey.Type, type);
Expression call = Expression.Call(row, mi, Expression.Constant(cProj.Token), cProj.OuterKey);
if (cProj.Projection.UniqueFunction != null)
throw new InvalidOperationException("Eager ChildProyection with UniqueFunction '{0}' not expected at this stage".FormatWith(cProj.Projection.UniqueFunction));
return call;
}
public Expression LookupMList(Expression row, ChildProjectionExpression cProj, MemberExpression field)
{
if (!cProj.IsLazyMList)
throw new InvalidOperationException("Not IsLazyMList not expected at this stage");
if (!cProj.Type.IsMList())
throw new InvalidOperationException("Lazy ChildProyection of type '{0}' instead of MList".FormatWith(cProj.Type.TypeName()));
if (cProj.Projection.UniqueFunction != null)
throw new InvalidOperationException("Lazy ChildProyection with UniqueFunction '{0}'".FormatWith(cProj.Projection.UniqueFunction));
MethodInfo mi = miLookupRequest.MakeGenericMethod(cProj.OuterKey.Type, cProj.Type.ElementType()!);
return Expression.Call(row, mi, Expression.Constant(cProj.Token), cProj.OuterKey, field);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.CoreModules.World.Wind;
namespace OpenSim.Region.CoreModules
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "WindModule")]
public class WindModule : IWindModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private uint m_frame = 0;
private uint m_frameLastUpdateClientArray = 0;
private int m_frameUpdateRate = 150;
//private Random m_rndnums = new Random(Environment.TickCount);
private Scene m_scene = null;
private bool m_ready = false;
private bool m_enabled = false;
private IConfig m_windConfig;
private IWindModelPlugin m_activeWindPlugin = null;
private string m_dWindPluginName = "SimpleRandomWind";
private Dictionary<string, IWindModelPlugin> m_availableWindPlugins = new Dictionary<string, IWindModelPlugin>();
// Simplified windSpeeds based on the fact that the client protocal tracks at a resolution of 16m
private Vector2[] windSpeeds = new Vector2[16 * 16];
#region INonSharedRegionModule Methods
public void Initialise(IConfigSource config)
{
m_windConfig = config.Configs["Wind"];
// string desiredWindPlugin = m_dWindPluginName;
if (m_windConfig != null)
{
m_enabled = m_windConfig.GetBoolean("enabled", true);
m_frameUpdateRate = m_windConfig.GetInt("wind_update_rate", 150);
// Determine which wind model plugin is desired
if (m_windConfig.Contains("wind_plugin"))
{
m_dWindPluginName = m_windConfig.GetString("wind_plugin", m_dWindPluginName);
}
}
if (m_enabled)
{
m_log.InfoFormat("[WIND] Enabled with an update rate of {0} frames.", m_frameUpdateRate);
}
}
public void AddRegion(Scene scene)
{
if (!m_enabled)
return;
m_scene = scene;
m_frame = 0;
// Register all the Wind Model Plug-ins
foreach (IWindModelPlugin windPlugin in AddinManager.GetExtensionObjects("/OpenSim/WindModule", false))
{
m_log.InfoFormat("[WIND] Found Plugin: {0}", windPlugin.Name);
m_availableWindPlugins.Add(windPlugin.Name, windPlugin);
}
// Check for desired plugin
if (m_availableWindPlugins.ContainsKey(m_dWindPluginName))
{
m_activeWindPlugin = m_availableWindPlugins[m_dWindPluginName];
m_log.InfoFormat("[WIND] {0} plugin found, initializing.", m_dWindPluginName);
if (m_windConfig != null)
{
m_activeWindPlugin.Initialise();
m_activeWindPlugin.WindConfig(m_scene, m_windConfig);
}
}
// if the plug-in wasn't found, default to no wind.
if (m_activeWindPlugin == null)
{
m_log.ErrorFormat("[WIND] Could not find specified wind plug-in: {0}", m_dWindPluginName);
m_log.ErrorFormat("[WIND] Defaulting to no wind.");
}
// This one puts an entry in the main help screen
// m_scene.AddCommand("Regions", this, "wind", "wind", "Usage: wind <plugin> <param> [value] - Get or Update Wind paramaters", null);
// This one enables the ability to type just the base command without any parameters
// m_scene.AddCommand("Regions", this, "wind", "", "", HandleConsoleCommand);
// Get a list of the parameters for each plugin
foreach (IWindModelPlugin windPlugin in m_availableWindPlugins.Values)
{
// m_scene.AddCommand("Regions", this, String.Format("wind base wind_plugin {0}", windPlugin.Name), String.Format("{0} - {1}", windPlugin.Name, windPlugin.Description), "", HandleConsoleBaseCommand);
m_scene.AddCommand(
"Regions",
this,
"wind base wind_update_rate",
"wind base wind_update_rate [<value>]",
"Get or set the wind update rate.",
"",
HandleConsoleBaseCommand);
foreach (KeyValuePair<string, string> kvp in windPlugin.WindParams())
{
string windCommand = String.Format("wind {0} {1}", windPlugin.Name, kvp.Key);
m_scene.AddCommand("Regions", this, windCommand, string.Format("{0} [<value>]", windCommand), kvp.Value, "", HandleConsoleParamCommand);
}
}
// Register event handlers for when Avatars enter the region, and frame ticks
m_scene.EventManager.OnFrame += WindUpdate;
m_scene.EventManager.OnMakeRootAgent += OnAgentEnteredRegion;
// Register the wind module
m_scene.RegisterModuleInterface<IWindModule>(this);
// Generate initial wind values
GenWindPos();
// Mark Module Ready for duty
m_ready = true;
}
public void RemoveRegion(Scene scene)
{
if (!m_enabled)
return;
m_ready = false;
// REVIEW: If a region module is closed, is there a possibility that it'll re-open/initialize ??
m_activeWindPlugin = null;
foreach (IWindModelPlugin windPlugin in m_availableWindPlugins.Values)
{
windPlugin.Dispose();
}
m_availableWindPlugins.Clear();
// Remove our hooks
m_scene.EventManager.OnFrame -= WindUpdate;
m_scene.EventManager.OnMakeRootAgent -= OnAgentEnteredRegion;
}
public void Close()
{
}
public string Name
{
get { return "WindModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void RegionLoaded(Scene scene)
{
}
#endregion
#region Console Commands
private void ValidateConsole()
{
if (m_scene.ConsoleScene() == null)
{
// FIXME: If console region is root then this will be printed by every module. Currently, there is no
// way to prevent this, short of making the entire module shared (which is complete overkill).
// One possibility is to return a bool to signal whether the module has completely handled the command
m_log.InfoFormat("[WIND]: Please change to a specific region in order to set Sun parameters.");
return;
}
if (m_scene.ConsoleScene() != m_scene)
{
m_log.InfoFormat("[WIND]: Console Scene is not my scene.");
return;
}
}
/// <summary>
/// Base console command handler, only used if a person specifies the base command with now options
/// </summary>
private void HandleConsoleCommand(string module, string[] cmdparams)
{
ValidateConsole();
m_log.Info("[WIND] The wind command can be used to change the currently active wind model plugin and update the parameters for wind plugins.");
}
/// <summary>
/// Called to change the active wind model plugin
/// </summary>
private void HandleConsoleBaseCommand(string module, string[] cmdparams)
{
ValidateConsole();
if ((cmdparams.Length != 4)
|| !cmdparams[1].Equals("base"))
{
m_log.Info("[WIND] Invalid parameters to change parameters for Wind module base, usage: wind base <parameter> <value>");
return;
}
switch (cmdparams[2])
{
case "wind_update_rate":
int newRate = 1;
if (int.TryParse(cmdparams[3], out newRate))
{
m_frameUpdateRate = newRate;
}
else
{
m_log.InfoFormat("[WIND] Invalid value {0} specified for {1}", cmdparams[3], cmdparams[2]);
return;
}
break;
case "wind_plugin":
string desiredPlugin = cmdparams[3];
if (desiredPlugin.Equals(m_activeWindPlugin.Name))
{
m_log.InfoFormat("[WIND] Wind model plugin {0} is already active", cmdparams[3]);
return;
}
if (m_availableWindPlugins.ContainsKey(desiredPlugin))
{
m_activeWindPlugin = m_availableWindPlugins[cmdparams[3]];
m_log.InfoFormat("[WIND] {0} wind model plugin now active", m_activeWindPlugin.Name);
}
else
{
m_log.InfoFormat("[WIND] Could not find wind model plugin {0}", desiredPlugin);
}
break;
}
}
/// <summary>
/// Called to change plugin parameters.
/// </summary>
private void HandleConsoleParamCommand(string module, string[] cmdparams)
{
ValidateConsole();
// wind <plugin> <param> [value]
if ((cmdparams.Length != 4)
&& (cmdparams.Length != 3))
{
m_log.Info("[WIND] Usage: wind <plugin> <param> [value]");
return;
}
string plugin = cmdparams[1];
string param = cmdparams[2];
float value = 0f;
if (cmdparams.Length == 4)
{
if (!float.TryParse(cmdparams[3], out value))
{
m_log.InfoFormat("[WIND] Invalid value {0}", cmdparams[3]);
}
try
{
WindParamSet(plugin, param, value);
}
catch (Exception e)
{
m_log.InfoFormat("[WIND] {0}", e.Message);
}
}
else
{
try
{
value = WindParamGet(plugin, param);
m_log.InfoFormat("[WIND] {0} : {1}", param, value);
}
catch (Exception e)
{
m_log.InfoFormat("[WIND] {0}", e.Message);
}
}
}
#endregion
#region IWindModule Methods
/// <summary>
/// Retrieve the wind speed at the given region coordinate. This
/// implimentation ignores Z.
/// </summary>
/// <param name="x">0...255</param>
/// <param name="y">0...255</param>
public Vector3 WindSpeed(int x, int y, int z)
{
if (m_activeWindPlugin != null)
{
return m_activeWindPlugin.WindSpeed(x, y, z);
}
else
{
return new Vector3(0.0f, 0.0f, 0.0f);
}
}
public void WindParamSet(string plugin, string param, float value)
{
if (m_availableWindPlugins.ContainsKey(plugin))
{
IWindModelPlugin windPlugin = m_availableWindPlugins[plugin];
windPlugin.WindParamSet(param, value);
m_log.InfoFormat("[WIND] {0} set to {1}", param, value);
}
else
{
throw new Exception(String.Format("Could not find plugin {0}", plugin));
}
}
public float WindParamGet(string plugin, string param)
{
if (m_availableWindPlugins.ContainsKey(plugin))
{
IWindModelPlugin windPlugin = m_availableWindPlugins[plugin];
return windPlugin.WindParamGet(param);
}
else
{
throw new Exception(String.Format("Could not find plugin {0}", plugin));
}
}
public string WindActiveModelPluginName
{
get
{
if (m_activeWindPlugin != null)
{
return m_activeWindPlugin.Name;
}
else
{
return String.Empty;
}
}
}
#endregion
/// <summary>
/// Called on each frame update. Updates the wind model and clients as necessary.
/// </summary>
public void WindUpdate()
{
if (((m_frame++ % m_frameUpdateRate) != 0) || !m_ready)
{
return;
}
GenWindPos();
SendWindAllClients();
}
public void OnAgentEnteredRegion(ScenePresence avatar)
{
if (m_ready)
{
if (m_activeWindPlugin != null)
{
// Ask wind plugin to generate a LL wind array to be cached locally
// Try not to update this too often, as it may involve array copies
if (m_frame >= (m_frameLastUpdateClientArray + m_frameUpdateRate))
{
windSpeeds = m_activeWindPlugin.WindLLClientArray();
m_frameLastUpdateClientArray = m_frame;
}
}
avatar.ControllingClient.SendWindData(windSpeeds);
}
}
private void SendWindAllClients()
{
if (m_ready)
{
if (m_scene.GetRootAgentCount() > 0)
{
// Ask wind plugin to generate a LL wind array to be cached locally
// Try not to update this too often, as it may involve array copies
if (m_frame >= (m_frameLastUpdateClientArray + m_frameUpdateRate))
{
windSpeeds = m_activeWindPlugin.WindLLClientArray();
m_frameLastUpdateClientArray = m_frame;
}
m_scene.ForEachRootClient(delegate(IClientAPI client)
{
client.SendWindData(windSpeeds);
});
}
}
}
/// <summary>
/// Calculate the sun's orbital position and its velocity.
/// </summary>
private void GenWindPos()
{
if (m_activeWindPlugin != null)
{
// Tell Wind Plugin to update it's wind data
m_activeWindPlugin.WindUpdate(m_frame);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#define CONTRACTS_FULL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;
using Microsoft.Research.ClousotRegression;
namespace ArraysNonNull
{
public class ArraysBasic
{
[ClousotRegressionTest("NonNull")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 26, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 19, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 32, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 39, MethodILOffset = 0)]
public void Test0()
{
object[] refs = new object[100];
for (int i = 0; i < refs.Length; i++)
{
refs[i] = new object();
}
Contract.Assert(refs[2] != null);
}
[ClousotRegressionTest("NonNull")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 28, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 56, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 49, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 62, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 69, MethodILOffset = 0)]
public void Test1(int k)
{
string[] strArray;
int num = 0;
if (k < 0xff)
{
strArray = new string[4];
strArray[num++] = "";
}
else
{
strArray = new string[3];
}
// Here we need the disjunction represented by the arrays
for (int i = num; i < strArray.Length; i++)
{
strArray[i] = "";
}
Contract.Assert(strArray[0] != null);
}
[ClousotRegressionTest("NonNull")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 23, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 6, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as receiver)", PrimaryILOffset = 7, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 62, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 43, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 73, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 7, MethodILOffset = 47)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 19, MethodILOffset = 47)]
public static void Main(string[] args)
{
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine(args[i].Length);
}
var str = "";
foreach (var arg in args)
{ // To prove the preconditions we need a loop invariant which depends on the quantified invariant
str = Concat(str, arg);
}
Contract.Assert(str != null);
}
[ClousotRegressionTest("NonNull")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 35, MethodILOffset = 61)]
private static string Concat(string s1, string s2)
{
Contract.Requires(s1 != null);
Contract.Requires(s2 != null);
Contract.Ensures(Contract.Result<string>() != null);
var tmp = s1 + s2;
Contract.Assume(tmp != null);
return tmp;
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 38, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 18, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"assert unproven", PrimaryILOffset = 27, MethodILOffset = 0)]
#if NETFRAMEWORK_4_0
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=17,MethodILOffset=72)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=39,MethodILOffset=72)]
#else
#if CLOUSOT2
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=3,MethodILOffset=72)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=25,MethodILOffset=72)]
#else
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 22, MethodILOffset = 72)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 44, MethodILOffset = 72)]
#endif
#endif
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 77, MethodILOffset = 0)]
public string CheckAllTheElements(string[] s)
{
Contract.Requires(s != null);
for (var i = 0; i < s.Length; i++)
{
var x = s[i];
Contract.Assert(x != null);
}
Contract.Assert(Contract.ForAll(s, el => el != null));
return null;
}
}
public class AssumeForAll
{
[ClousotRegressionTest("NonNull")]
#if !CLOUSOT2
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 60, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 14, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 44, MethodILOffset = 0)]
#endif
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 8, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 49, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 65, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 8, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 90, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 96, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 103, MethodILOffset = 0)]
public static void Test0_OK(string[] s, int i)
{
Contract.Requires(s != null);
Contract.Requires(i >= 0);
Contract.Requires(i < s.Length);
Contract.Requires(Contract.ForAll(0, s.Length, j => s[j] != null));
Contract.Assert(s[i] != null); // True
}
[ClousotRegressionTest("NonNull")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 8, MethodILOffset = 0)]
#if !CLOUSOT2
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 14, MethodILOffset = 0)]
#endif
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 8, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 57, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 64, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 77, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 83, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 96, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 103, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 71, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"assert unproven", PrimaryILOffset = 90, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.False, Message = @"assert is false", PrimaryILOffset = 107, MethodILOffset = 0)]
public void Test1_Ok(object[] os)
{
Contract.Requires(os != null);
Contract.Requires(Contract.ForAll(10, 20, j => os[j] != null));
Contract.Assert(os[15] != null); // True
Contract.Assert(os[0] != null); // Top
Contract.Assert(os[19] == null); // False
}
[ClousotRegressionTest("NonNull")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 26, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 69, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 93, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"assert unproven", PrimaryILOffset = 76, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 49, MethodILOffset = 94)]
public object Test2_NotOk(object[] data, int count)
{
Contract.Requires(data != null);
Contract.Requires(count >= 0);
Contract.Requires(count <= data.Length);
Contract.Ensures(Contract.Result<object>() != null);
if (count == 0) throw new InvalidOperationException();
for (int i = 0; i < count; i++)
{
Contract.Assert(data[i] != null);
}
return data[count - 1];
}
[ClousotRegressionTest("NonNull")]
#if !CLOUSOT2
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 8, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 14, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 44, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 8, MethodILOffset = 151)]
#endif
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 49, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 8, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 115, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 121, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 142, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 150, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 128, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 96, MethodILOffset = 151)]
public object Test2_Ok(object[] data, int count)
{
Contract.Requires(data != null);
Contract.Requires(count >= 0);
Contract.Requires(count <= data.Length);
Contract.Requires(Contract.ForAll(0, count, i => data[i] != null));
Contract.Ensures(Contract.Result<object>() != null);
if (count == 0) throw new InvalidOperationException();
for (int i = 0; i < count; i++)
{
Contract.Assert(data[i] != null);
}
return data[count - 1];
}
}
public class AssertForAll
{
[ClousotRegressionTest("NonNull")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 8, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 36, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"Possible use of a null array 'strings'", PrimaryILOffset = 41, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 18, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 29, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 47, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 52, MethodILOffset = 0)]
#if NETFRAMEWORK_4_0
[RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=13,MethodILOffset=66)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=35,MethodILOffset=66)]
#else
#if CLOUSOT2
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=3,MethodILOffset=66)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=25,MethodILOffset=66)]
#else
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 22, MethodILOffset = 66)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 44, MethodILOffset = 66)]
#endif
#endif
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 71, MethodILOffset = 0)]
public void NotNull0(string[] strings)
{
for (int i = 0; i < strings.Length; i++)
{
strings[i] = "ciao";
}
Contract.Assert(Contract.ForAll(0, strings.Length, i => strings[i] != null));
}
[ClousotRegressionTest("NonNull")]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"Possible use of a null array 'strings'", PrimaryILOffset = 54, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 8, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 8, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 27, MethodILOffset = 0)]
//[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"Possible use of a null array 'strings'", PrimaryILOffset = 38, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"Possible use of a null array 'strings' (Fixing this warning may solve one additional issue in the code)", PrimaryILOffset = 38, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 49, MethodILOffset = 0)]
#if NETFRAMEWORK_4_0
[RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=13,MethodILOffset=68)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=35,MethodILOffset=68)]
#else
#if CLOUSOT2
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=3,MethodILOffset=68)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=25,MethodILOffset=68)]
#else
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 22, MethodILOffset = 68)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 44, MethodILOffset = 68)]
#endif
#endif
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"assert unproven", PrimaryILOffset = 73, MethodILOffset = 0)]
public void NotNull1_NotOk(string[] strings, int k)
{
Contract.Requires(k > 5);
for (int i = 0; i < k; i++)
{
strings[i] = "ciao";
}
Contract.Assert(Contract.ForAll(0, strings.Length, i => strings[i] != null));
}
[ClousotRegressionTest("NonNull")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 8, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 8, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 27, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"Possible use of a null array 'strings'. The static checker determined that the condition 'strings != null' should hold on entry. Nevertheless, the condition may be too strong for the callers. If you think it is ok, add a precondition to document it: Contract.Requires(strings != null);", PrimaryILOffset = 38, MethodILOffset = 0)]
#if NETFRAMEWORK_4_0
[RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=13,MethodILOffset=61)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=35,MethodILOffset=61)]
#else
#if CLOUSOT2
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=3,MethodILOffset=61)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=25,MethodILOffset=61)]
#else
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 22, MethodILOffset = 61)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 44, MethodILOffset = 61)]
#endif
#endif
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 66, MethodILOffset = 0)]
public void NotNull1_Ok(string[] strings, int k)
{
Contract.Requires(k > 5);
for (int i = 0; i < k; i++)
{
strings[i] = "ciao";
}
Contract.Assert(Contract.ForAll(0, k, i => strings[i] != null));
}
[ClousotRegressionTest("NonNull")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 8, MethodILOffset = 0)]
#if !CLOUSOT2
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 14, MethodILOffset = 0)]
#endif
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 8, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 49, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 54, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 35, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 42, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 60, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 65, MethodILOffset = 0)]
#if NETFRAMEWORK_4_0
[RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=13,MethodILOffset=79)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=35,MethodILOffset=79)]
#else
#if CLOUSOT2
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=3,MethodILOffset=79)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=25,MethodILOffset=79)]
#else
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 22, MethodILOffset = 79)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 44, MethodILOffset = 79)]
#endif
#endif
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 84, MethodILOffset = 0)]
public void AllNull(object[] os)
{
Contract.Requires(os != null);
for (int i = 0; i < os.Length; i++)
{
os[i] = null;
}
Contract.Assert(Contract.ForAll(0, os.Length, i => os[i] == null));
}
}
public class NonNullStack
{
private object[] arr;
private int counter;
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(arr != null);
Contract.Invariant(counter >= 0);
Contract.Invariant(counter <= arr.Length);
Contract.Invariant(Contract.ForAll(0, counter, i => arr[i] != null));
}
[ClousotRegressionTest("NonNull")]
public bool IsEmpty
{
get
{
return counter == 0;
}
}
[ClousotRegressionTest("NonNull")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as receiver)", PrimaryILOffset = 1, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 25, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 32, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 12, MethodILOffset = 37)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 29, MethodILOffset = 37)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 53, MethodILOffset = 37)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 82, MethodILOffset = 37)]
public NonNullStack(int len)
{
Contract.Requires(len >= 0);
arr = new object[len];
counter = 0;
}
[ClousotRegressionTest("NonNull")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 13, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 19, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 24, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 29, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 34, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 67, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 53, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 59, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 60, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 76, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 82, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 88, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 94, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 97, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 104, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 12, MethodILOffset = 109)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 29, MethodILOffset = 109)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 53, MethodILOffset = 109)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 82, MethodILOffset = 109)]
public void Push(object x)
{
Contract.Requires(x != null);
if (counter == arr.Length)
{
var newArr = new object[arr.Length * 2 + 1];
for (int i = 0; i < counter; i++)
{
newArr[i] = arr[i];
}
arr = newArr;
}
arr[counter] = x;
counter++;
}
[ClousotRegressionTest("NonNull")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 13, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 18, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 21, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 29, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 34, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 67, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 72, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 53, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 59, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 60, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 78, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 84, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 91, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 100, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 107, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 12, MethodILOffset = 108)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 29, MethodILOffset = 108)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 53, MethodILOffset = 108)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 82, MethodILOffset = 108)]
public void PushWithDifferentTestCondition(object obj)
{
Contract.Requires(obj != null);
if (arr.Length == counter)
{
var newElements = new object[arr.Length * 2 + 1];
for (var i = 0; i < arr.Length; i++) // F: There was a precision bug here, which was losing some equalities
{
newElements[i] = arr[i];
}
arr = newElements;
}
arr[counter++] = obj;
}
[ClousotRegressionTest("NonNull")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 1, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 7, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 12, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 17, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 22, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 55, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 41, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 47, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 48, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 64, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 70, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 77, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 86, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 93, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 12, MethodILOffset = 94)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 29, MethodILOffset = 94)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 53, MethodILOffset = 94)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"invariant unproven: Contract.ForAll(0, counter, i => arr[i] != null)", PrimaryILOffset = 82, MethodILOffset = 94)]
public void PushWrong(object x)
{
if (counter == arr.Length)
{
var newArr = new object[arr.Length * 2 + 1];
for (int i = 0; i < counter; i++)
{
newArr[i] = arr[i];
}
arr = newArr;
}
arr[counter++] = x;
}
[ClousotRegressionTest("NonNull")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as receiver)", PrimaryILOffset = 1, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 32, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 39, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 45, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 51, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 56, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 12, MethodILOffset = 59)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 29, MethodILOffset = 59)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 53, MethodILOffset = 59)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 82, MethodILOffset = 59)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 25, MethodILOffset = 59)]
public object Pop()
{
Contract.Requires(!this.IsEmpty);
Contract.Ensures(Contract.Result<object>() != null);
counter--;
var res = arr[counter];
return res;
}
[ClousotRegressionTest("NonNull")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as receiver)", PrimaryILOffset = 1, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 32, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 60, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 66, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 71, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 96, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 102, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 109, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 112, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 118, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 126, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 129, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 136, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 143, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 171, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 177, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 182, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 165, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 201, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 12, MethodILOffset = 207)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 29, MethodILOffset = 207)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 53, MethodILOffset = 207)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 82, MethodILOffset = 207)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 25, MethodILOffset = 207)]
#if NETFRAMEWORK_4_0
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=13,MethodILOffset=49)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=35,MethodILOffset=49)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=13,MethodILOffset=85)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=35,MethodILOffset=85)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=13,MethodILOffset=160)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=35,MethodILOffset=160)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=13,MethodILOffset=196)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=35,MethodILOffset=196)]
#else
#if CLOUSOT2
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=3,MethodILOffset=49)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=25,MethodILOffset=49)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=3,MethodILOffset=85)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=25,MethodILOffset=85)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=3,MethodILOffset=160)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=25,MethodILOffset=160)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=3,MethodILOffset=196)] // we can prove it with clousot2, even without wp
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=25,MethodILOffset=196)]
#else
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 22, MethodILOffset = 49)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 44, MethodILOffset = 49)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 22, MethodILOffset = 85)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 44, MethodILOffset = 85)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 22, MethodILOffset = 160)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 44, MethodILOffset = 160)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"requires unproven", PrimaryILOffset = 22, MethodILOffset = 196)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 44, MethodILOffset = 196)]
#endif
#endif
public object PopGCFriendly()
{
Contract.Requires(!this.IsEmpty);
Contract.Ensures(Contract.Result<object>() != null);
Contract.Assume(Contract.ForAll(0, counter, i => arr[i] != null));
Contract.Assume(Contract.ForAll(counter, arr.Length, i => arr[i] == null));
var r = arr[counter - 1];
arr[counter - 1] = null;
counter = counter - 1;
Contract.Assert(Contract.ForAll(0, counter, i => arr[i] != null));
Contract.Assert(Contract.ForAll(counter, arr.Length, i => arr[i] == null));
return r;
}
}
}
namespace DaveSexton
{
internal class ArrayCrash
{
private string biz = "", bar = "", baz = "";
private bool can = true;
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 10, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 15, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 23, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 27, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 32, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 40, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 44, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 59, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 74, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 13, MethodILOffset = 76)]
private void Test()
{
var value = biz + "." + bar + "." + ((can) ? baz + ", " : "");
}
}
}
namespace ExamplesWithUIntIndexes
{
public class Z3repros
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 6, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 53, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 21, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 27, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 35, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 36, MethodILOffset = 0)]
internal static IntPtr[] ArrayToNative(Z3Object[] a)
{
if (a == null) return null;
IntPtr[] an = new IntPtr[a.Length];
for (uint i = 0; i < a.Length; i++)
// We were not understanding the cast in a[i]
if (a[i] != null) an[i] = a[i].NativeObject;
return an;
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 13, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 24, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 46, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 59, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 78, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 66, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 85, MethodILOffset = 0)]
private void EnumSort(string[] enumNames)
{
Contract.Requires(enumNames != null);
Contract.Requires(enumNames.Length > 0);
int n = enumNames.Length;
var _constdecls = new string[n];
for (uint i = 0; i < n; i++)
{
// We were not understanding the cast in a[i]
_constdecls[i] = "hello";
}
Contract.Assert(_constdecls[0] != null);
for (uint i = 0; i < n; i++)
{
Contract.Assert(_constdecls[i] != null);
}
}
}
public class Z3Object
{
extern public IntPtr NativeObject { get; }
}
}
| |
//
// Copyright (C) 2012-2014 DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using NUnit.Framework;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Moq;
namespace Cassandra.Tests
{
[TestFixture]
public class RowSetUnitTests
{
[Test]
public void RowIteratesThroughValues()
{
var rs = CreateStringsRowset(4, 1);
var row = rs.First();
//Use Linq's IEnumerable ToList: it iterates and maps to a list
var cellValues = row.ToList();
Assert.AreEqual("row_0_col_0", cellValues[0]);
Assert.AreEqual("row_0_col_1", cellValues[1]);
Assert.AreEqual("row_0_col_2", cellValues[2]);
Assert.AreEqual("row_0_col_3", cellValues[3]);
}
/// <summary>
/// Test that all possible ways to get the value from the row gets the same value
/// </summary>
[Test]
public void RowGetTheSameValues()
{
var row = CreateStringsRowset(3, 1).First();
var value00 = row[0];
var value01 = row.GetValue<object>(0);
var value02 = row.GetValue(typeof(object), 0);
Assert.True(value00.Equals(value01) && value01.Equals(value02), "Row values do not match");
var value10 = (string)row[1];
var value11 = row.GetValue<string>(1);
var value12 = (string)row.GetValue(typeof(string), 1);
Assert.True(value10.Equals(value11) && value11.Equals(value12), "Row values do not match");
var value20 = (string)row["col_2"];
var value21 = row.GetValue<string>("col_2");
var value22 = (string)row.GetValue(typeof(string), "col_2");
Assert.True(value20.Equals(value21) && value21.Equals(value22), "Row values do not match");
}
[Test]
public void RowSetIteratesTest()
{
var rs = CreateStringsRowset(2, 3);
//Use Linq's IEnumerable ToList to iterate and map it to a list
var rowList = rs.ToList();
Assert.AreEqual(3, rowList.Count);
Assert.AreEqual("row_0_col_0", rowList[0].GetValue<string>("col_0"));
Assert.AreEqual("row_1_col_1", rowList[1].GetValue<string>("col_1"));
Assert.AreEqual("row_2_col_0", rowList[2].GetValue<string>("col_0"));
}
[Test]
public void RowSetCallsFetchNextTest()
{
//Create a rowset with 1 row
var rs = CreateStringsRowset(1, 1, "a_");
Assert.True(rs.AutoPage);
//It has paging state, stating that there are more pages
rs.PagingState = new byte[] { 0 };
//Add a handler to fetch next
rs.FetchNextPage = (pagingState) =>
{
return CreateStringsRowset(1, 1, "b_");
};
//use linq to iterate and map it to a list
var rowList = rs.ToList();
Assert.AreEqual(2, rowList.Count);
Assert.AreEqual("a_row_0_col_0", rowList[0].GetValue<string>("col_0"));
Assert.AreEqual("b_row_0_col_0", rowList[1].GetValue<string>("col_0"));
}
[Test]
public void RowSetDoesNotCallFetchNextWhenAutoPageFalseTest()
{
//Create a rowset with 1 row
var rs = CreateStringsRowset(1, 1, "a_");
//Set to not to automatically page
rs.AutoPage = false;
//It has paging state, stating that there are more pages
rs.PagingState = new byte[] { 0 };
//Add a handler to fetch next
var called = false;
rs.FetchNextPage = (pagingState) =>
{
called = true;
return CreateStringsRowset(1, 1, "b_");
};
//use linq to iterate and map it to a list
var rowList = rs.ToList();
Assert.False(called);
Assert.AreEqual(1, rowList.Count);
}
/// <summary>
/// Ensures that in case there is an exception while retrieving the next page, it propagates.
/// </summary>
[Test]
public void RowSetFetchNextPropagatesExceptionTest()
{
var rs = CreateStringsRowset(1, 1);
//It has paging state, stating that there are more pages.
rs.PagingState = new byte[] { 0 };
//Throw a test exception when fetching the next page.
rs.FetchNextPage = (pagingState) =>
{
throw new TestException();
};
//use linq to iterate and map it to a list
//The row set should throw an exception when getting the next page.
Assert.Throws<TestException>(() => { rs.ToList(); });
}
/// <summary>
/// Tests that once iterated, it can not be iterated any more.
/// </summary>
[Test]
public void RowSetMustDequeue()
{
var rowLength = 10;
var rs = CreateStringsRowset(2, rowLength);
rs.FetchNextPage = (pagingState) =>
{
Assert.Fail("Event to get next page must not be called as there is no paging state.");
return null;
};
//Use Linq to iterate
var rowsFirstIteration = rs.ToList();
Assert.AreEqual(rowLength, rowsFirstIteration.Count);
//Following iterations must yield 0 rows
var rowsSecondIteration = rs.ToList();
var rowsThridIteration = rs.ToList();
Assert.AreEqual(0, rowsSecondIteration.Count);
Assert.AreEqual(0, rowsThridIteration.Count);
Assert.IsTrue(rs.IsExhausted());
Assert.IsTrue(rs.IsFullyFetched);
}
/// <summary>
/// Tests that when multi threading, all enumerators of the same rowset wait for the fetching.
/// </summary>
[Test]
public void RowSetFetchNextAllEnumeratorsWait()
{
var pageSize = 10;
var rs = CreateStringsRowset(10, pageSize);
rs.PagingState = new byte[0];
var fetchCounter = 0;
rs.FetchNextPage = (pagingState) =>
{
fetchCounter++;
//fake a fetch
Thread.Sleep(1000);
return CreateStringsRowset(10, pageSize);
};
var counterList = new ConcurrentBag<int>();
Action iteration = () =>
{
var counter = 0;
foreach (var row in rs)
{
counter++;
//Try to synchronize, all the threads will try to fetch at the almost same time.
Thread.Sleep(300);
}
counterList.Add(counter);
};
//Invoke it in parallel more than 10 times
Parallel.Invoke(iteration, iteration, iteration, iteration, iteration, iteration, iteration, iteration, iteration, iteration, iteration, iteration, iteration, iteration, iteration);
//Assert that the fetch was called just 1 time
Assert.AreEqual(1, fetchCounter);
//Sum all rows dequeued from the different threads
var totalRows = counterList.Sum();
//Check that the total amount of rows dequeued are the same as pageSize * number of pages.
Assert.AreEqual(pageSize * 2, totalRows);
}
[Test]
public void RowSetFetchNext3Pages()
{
var rowLength = 10;
var rs = CreateStringsRowset(10, rowLength, "page_0_");
rs.PagingState = new byte[0];
var fetchCounter = 0;
rs.FetchNextPage = (pagingState) =>
{
fetchCounter++;
var pageRowSet = CreateStringsRowset(10, rowLength, "page_" + fetchCounter + "_");
if (fetchCounter < 3)
{
//when retrieving the pages, state that there are more results
pageRowSet.PagingState = new byte[0];
}
else
{
//On the 3rd page, state that there aren't any more pages.
pageRowSet.PagingState = null;
}
return pageRowSet;
};
//Use Linq to iterate
var rows = rs.ToList();
Assert.AreEqual(3, fetchCounter, "Fetch must have been called 3 times");
Assert.AreEqual(rows.Count, rowLength * 4, "RowSet must contain 4 pages in total");
//Check the values are in the correct order
Assert.AreEqual(rows[0].GetValue<string>(0), "page_0_row_0_col_0");
Assert.AreEqual(rows[rowLength].GetValue<string>(0), "page_1_row_0_col_0");
Assert.AreEqual(rows[rowLength * 2].GetValue<string>(0), "page_2_row_0_col_0");
Assert.AreEqual(rows[rowLength * 3].GetValue<string>(0), "page_3_row_0_col_0");
}
[Test]
public void RowSetFetchNext3PagesExplicitFetch()
{
var rowLength = 10;
var rs = CreateStringsRowset(10, rowLength, "page_0_");
rs.PagingState = new byte[0];
var fetchCounter = 0;
rs.FetchNextPage = (pagingState) =>
{
fetchCounter++;
var pageRowSet = CreateStringsRowset(10, rowLength, "page_" + fetchCounter + "_");
if (fetchCounter < 3)
{
//when retrieving the pages, state that there are more results
pageRowSet.PagingState = new byte[0];
}
else if (fetchCounter == 3)
{
//On the 3rd page, state that there aren't any more pages.
pageRowSet.PagingState = null;
}
else
{
throw new Exception("It should not be called more than 3 times.");
}
return pageRowSet;
};
Assert.AreEqual(rowLength * 1, rs.InnerQueueCount);
rs.FetchMoreResults();
Assert.AreEqual(rowLength * 2, rs.InnerQueueCount);
rs.FetchMoreResults();
Assert.AreEqual(rowLength * 3, rs.InnerQueueCount);
rs.FetchMoreResults();
Assert.AreEqual(rowLength * 4, rs.InnerQueueCount);
//Use Linq to iterate:
var rows = rs.ToList();
Assert.AreEqual(rows.Count, rowLength * 4, "RowSet must contain 4 pages in total");
//Check the values are in the correct order
Assert.AreEqual(rows[0].GetValue<string>(0), "page_0_row_0_col_0");
Assert.AreEqual(rows[rowLength].GetValue<string>(0), "page_1_row_0_col_0");
Assert.AreEqual(rows[rowLength * 2].GetValue<string>(0), "page_2_row_0_col_0");
Assert.AreEqual(rows[rowLength * 3].GetValue<string>(0), "page_3_row_0_col_0");
}
[Test]
public void NotExistentColumnThrows()
{
var row = CreateSampleRowSet().First();
var ex = Assert.Throws<ArgumentException>(() => row.GetValue<string>("not_existent_col"));
StringAssert.Contains("Column", ex.Message);
StringAssert.Contains("not found", ex.Message);
}
[Test]
public void NullValuesWithStructTypeColumnThrows()
{
//Row with all null values
var row = CreateSampleRowSet().Last();
Assert.IsNull(row.GetValue<string>("text_sample"));
Assert.Throws<NullReferenceException>(() => row.GetValue<int>("int_sample"));
Assert.DoesNotThrow(() => row.GetValue<int?>("int_sample"));
}
[Test]
public void RowsetIsMockable()
{
var rowMock = new Mock<Row>();
rowMock.Setup(r => r.GetValue<int>(It.Is<string>(n => n == "int_value"))).Returns(100);
var rows = new Row[]
{
rowMock.Object
};
var mock = new Mock<RowSet>();
mock
.Setup(r => r.GetEnumerator()).Returns(() => ((IEnumerable<Row>)rows).GetEnumerator());
var rs = mock.Object;
var rowArray = rs.ToArray();
Assert.AreEqual(rowArray.Length, 1);
Assert.AreEqual(rowArray[0].GetValue<int>("int_value"), 100);
}
/// <summary>
/// Creates a rowset.
/// The columns are named: col_0, ..., col_n
/// The rows values are: row_0_col_0, ..., row_m_col_n
/// </summary>
private static RowSet CreateStringsRowset(int columnLength, int rowLength, string valueModifier = null)
{
var columns = new List<CqlColumn>();
var columnIndexes = new Dictionary<string, int>();
for (var i = 0; i < columnLength; i++)
{
var c = new CqlColumn()
{
Index = i,
Name = "col_" + i,
TypeCode = ColumnTypeCode.Text,
Type = typeof(string)
};
columns.Add(c);
columnIndexes.Add(c.Name, c.Index);
}
var rs = new RowSet();
for (var j = 0; j < rowLength; j++)
{
var rowValues = new List<byte[]>();
foreach (var c in columns)
{
var value = valueModifier + "row_" + j + "_col_" + c.Index;
rowValues.Add(Encoding.UTF8.GetBytes(value));
}
rs.AddRow(new Row(1, rowValues.ToArray(), columns.ToArray(), columnIndexes));
}
return rs;
}
/// <summary>
/// Creates a RowSet with few rows with int, text columns (null values in the last row)
/// </summary>
private static RowSet CreateSampleRowSet()
{
var columns = new List<CqlColumn>
{
new CqlColumn()
{
Index = 0,
Name = "text_sample",
TypeCode = ColumnTypeCode.Text,
Type = typeof (string)
},
new CqlColumn()
{
Index = 1,
Name = "int_sample",
TypeCode = ColumnTypeCode.Int,
Type = typeof(int)
}
};
var columnIndexes = columns.ToDictionary(c => c.Name, c => c.Index);
var rs = new RowSet();
var rowValues = new[]
{
Encoding.UTF8.GetBytes("text value"),
TypeCodec.EncodeInt(2, null, 100)
};
rs.AddRow(new Row(2, rowValues, columns.ToArray(), columnIndexes));
rowValues = new byte[][]
{
null,
null
};
rs.AddRow(new Row(2, rowValues, columns.ToArray(), columnIndexes));
return rs;
}
private class TestException : Exception { }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public class GroupJoinTests
{
private const int KeyFactor = 8;
private const int ElementFactor = 4;
public static IEnumerable<object[]> GroupJoinData(int[] leftCounts, int[] rightCounts)
{
foreach (object[] parms in UnorderedSources.BinaryRanges(leftCounts, rightCounts))
{
yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] };
}
}
//
// GroupJoin
//
[Theory]
[MemberData(nameof(UnorderedSources.BinaryRanges), new[] { 0, 1, 2, 16 }, new[] { 0, 1, 16 }, MemberType = typeof(UnorderedSources))]
public static void GroupJoin_Unordered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, leftCount);
foreach (var p in leftQuery.GroupJoin(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)))
{
seen.Add(p.Key);
if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor)
{
Assert.Equal(p.Key * KeyFactor, Assert.Single(p.Value));
}
else
{
Assert.Empty(p.Value);
}
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnorderedSources.BinaryRanges), new[] { 1024 * 4, 1024 * 8 }, new[] { 0, 1, 1024 * 4, 1024 * 8 }, MemberType = typeof(UnorderedSources))]
public static void GroupJoin_Unordered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
GroupJoin_Unordered(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(GroupJoinData), new[] { 0, 1, 2, 16 }, new[] { 0, 1, 16 })]
public static void GroupJoin(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
foreach (var p in leftQuery.GroupJoin(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)))
{
Assert.Equal(seen++, p.Key);
if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor)
{
Assert.Equal(p.Key * KeyFactor, Assert.Single(p.Value));
}
else
{
Assert.Empty(p.Value);
}
}
Assert.Equal(leftCount, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(GroupJoinData), new[] { 1024 * 4, 1024 * 8 }, new[] { 0, 1, 1024 * 4, 1024 * 8 })]
public static void GroupJoin_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
GroupJoin(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(UnorderedSources.BinaryRanges), new[] { 0, 1, 2, 16 }, new[] { 0, 1, 16 }, MemberType = typeof(UnorderedSources))]
public static void GroupJoin_Unordered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, leftCount);
Assert.All(leftQuery.GroupJoin(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)).ToList(),
p =>
{
seen.Add(p.Key);
if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor)
{
Assert.Equal(p.Key * KeyFactor, Assert.Single(p.Value));
}
else
{
Assert.Empty(p.Value);
}
});
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnorderedSources.BinaryRanges), new[] { 1024 * 4, 1024 * 8 }, new[] { 0, 1, 1024 * 4, 1024 * 8 }, MemberType = typeof(UnorderedSources))]
public static void GroupJoin_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
GroupJoin_Unordered_NotPipelined(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(GroupJoinData), new[] { 0, 1, 2, 16 }, new[] { 0, 1, 16 })]
public static void GroupJoin_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
Assert.All(leftQuery.GroupJoin(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)).ToList(),
p =>
{
Assert.Equal(seen++, p.Key);
if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor)
{
Assert.Equal(p.Key * KeyFactor, Assert.Single(p.Value));
}
else
{
Assert.Empty(p.Value);
}
});
Assert.Equal(leftCount, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(GroupJoinData), new[] { 1024 * 4, 1024 * 8 }, new[] { 0, 1, 1024 * 4, 1024 * 8 })]
public static void GroupJoin_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
GroupJoin_NotPipelined(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(UnorderedSources.BinaryRanges), new[] { 0, 1, 2, 15, 16 }, new[] { 0, 1, 16 }, MemberType = typeof(UnorderedSources))]
public static void GroupJoin_Unordered_Multiple(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seenOuter = new IntegerRangeSet(0, leftCount);
Assert.All(leftQuery.GroupJoin(rightQuery, x => x, y => y / KeyFactor, (x, y) => KeyValuePair.Create(x, y)),
p =>
{
seenOuter.Add(p.Key);
if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor)
{
IntegerRangeSet seenInner = new IntegerRangeSet(p.Key * KeyFactor, Math.Min(rightCount - p.Key * KeyFactor, KeyFactor));
Assert.All(p.Value, y => { Assert.Equal(p.Key, y / KeyFactor); seenInner.Add(y); });
seenInner.AssertComplete();
}
else
{
Assert.Empty(p.Value);
}
});
seenOuter.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnorderedSources.BinaryRanges), new[] { 1024 * 4, 1024 * 8 }, new[] { 0, 1, 1024 * 4, 1024 * 8 }, MemberType = typeof(UnorderedSources))]
public static void GroupJoin_Unordered_Multiple_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
GroupJoin_Unordered_Multiple(left, leftCount, right, rightCount);
}
[Theory]
[ActiveIssue(1155)]
[MemberData(nameof(GroupJoinData), new[] { 0, 1, 2, 15, 16 }, new[] { 0, 1, 16 })]
// GroupJoin doesn't always return elements from the right in order. See Issue #1155
public static void GroupJoin_Multiple(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seenOuter = 0;
Assert.All(leftQuery.GroupJoin(rightQuery, x => x, y => y / KeyFactor, (x, y) => KeyValuePair.Create(x, y)),
p =>
{
Assert.Equal(seenOuter++, p.Key);
if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor)
{
int seenInner = p.Key * KeyFactor;
Assert.All(p.Value, y =>
{
Assert.Equal(p.Key, y / KeyFactor);
Assert.Equal(seenInner++, y);
});
Assert.Equal(Math.Min((p.Key + 1) * KeyFactor, rightCount), seenInner);
}
else
{
Assert.Empty(p.Value);
}
});
Assert.Equal(leftCount, seenOuter);
}
[Theory]
[ActiveIssue(1155)]
[OuterLoop]
[MemberData(nameof(GroupJoinData), new[] { 1024 * 4, 1024 * 8 }, new[] { 0, 1, 1024 * 4, 1024 * 8 })]
public static void GroupJoin_Multiple_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
GroupJoin_Multiple(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(UnorderedSources.BinaryRanges), new[] { 0, 1, 2, 16 }, new[] { 0, 1, 16 }, MemberType = typeof(UnorderedSources))]
public static void GroupJoin_Unordered_CustomComparator(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seenOuter = new IntegerRangeSet(0, leftCount);
Assert.All(leftQuery.GroupJoin(rightQuery, x => x, y => y % ElementFactor, (x, y) => KeyValuePair.Create(x, y), new ModularCongruenceComparer(KeyFactor)),
p =>
{
seenOuter.Add(p.Key);
if (p.Key % KeyFactor < Math.Min(ElementFactor, rightCount))
{
IntegerRangeSet seenInner = new IntegerRangeSet(0, (rightCount + (ElementFactor - 1) - p.Key % ElementFactor) / ElementFactor);
Assert.All(p.Value, y => { Assert.Equal(p.Key % KeyFactor, y % ElementFactor); seenInner.Add(y / ElementFactor); });
seenInner.AssertComplete();
}
else
{
Assert.Empty(p.Value);
}
});
seenOuter.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnorderedSources.BinaryRanges), new[] { 512, 1024 }, new[] { 0, 1, 1024, 1024 * 4 }, MemberType = typeof(UnorderedSources))]
public static void GroupJoin_Unordered_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
GroupJoin_Unordered_CustomComparator(left, leftCount, right, rightCount);
}
[Theory]
[ActiveIssue(1155)]
[MemberData(nameof(GroupJoinData), new[] { 0, 1, 2, 16 }, new[] { 0, 1, 16 })]
public static void GroupJoin_CustomComparator(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seenOuter = 0;
Assert.All(leftQuery.GroupJoin(rightQuery, x => x, y => y % ElementFactor, (x, y) => KeyValuePair.Create(x, y), new ModularCongruenceComparer(KeyFactor)),
p =>
{
Assert.Equal(seenOuter++, p.Key);
if (p.Key % KeyFactor < Math.Min(ElementFactor, rightCount))
{
int seenInner = p.Key % (KeyFactor / 2) - (KeyFactor / 2);
Assert.All(p.Value, y =>
{
Assert.Equal(p.Key % KeyFactor, y % (KeyFactor / 2));
Assert.Equal(seenInner += (KeyFactor / 2), y);
});
Assert.Equal(Math.Max(p.Key % (KeyFactor / 2), rightCount + (p.Key % (KeyFactor / 2) - (KeyFactor / 2))), seenInner);
}
else
{
Assert.Empty(p.Value);
}
});
Assert.Equal(leftCount, seenOuter);
}
[Theory]
[ActiveIssue(1155)]
[OuterLoop]
[MemberData(nameof(GroupJoinData), new[] { 512, 1024 }, new[] { 0, 1, 1024, 1024 * 4 })]
public static void GroupJoin_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
GroupJoin_CustomComparator(left, leftCount, right, rightCount);
}
[Fact]
public static void GroupJoin_NotSupportedException()
{
#pragma warning disable 618
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(Enumerable.Range(0, 1), i => i, i => i, (i, j) => i));
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(Enumerable.Range(0, 1), i => i, i => i, (i, j) => i, null));
#pragma warning restore 618
}
[Fact]
// Should not get the same setting from both operands.
public static void GroupJoin_NoDuplicateSettings()
{
CancellationToken t = new CancellationTokenSource().Token;
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).GroupJoin(ParallelEnumerable.Range(0, 1).WithCancellation(t), x => x, y => y, (x, e) => e));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).GroupJoin(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1), x => x, y => y, (x, e) => e));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).GroupJoin(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default), x => x, y => y, (x, e) => e));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).GroupJoin(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default), x => x, y => y, (x, e) => e));
}
[Fact]
public static void GroupJoin_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, i => i, (i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin((ParallelQuery<int>)null, i => i, i => i, (i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), (Func<int, int>)null, i => i, (i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, (Func<int, int>)null, (i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, i => i, (Func<int, IEnumerable<int>, int>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, i => i, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin((ParallelQuery<int>)null, i => i, i => i, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), (Func<int, int>)null, i => i, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, (Func<int, int>)null, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, i => i, (Func<int, IEnumerable<int>, int>)null, EqualityComparer<int>.Default));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
namespace IxMilia.Dxf
{
internal class DxfWriter
{
private StreamWriter textWriter = null;
private BinaryWriter binWriter = null;
private Stream fileStream = null;
private bool asText = true;
private DxfAcadVersion version;
public DxfWriter(Stream stream, bool asText, DxfAcadVersion version)
{
fileStream = stream;
this.asText = asText;
this.version = version;
}
/// <summary>
/// Test-only shortcut.
/// </summary>
internal void CreateInternalWriters()
{
if (asText)
{
// always create writer as UTF8; the actual file version will determine if just ASCII is written
textWriter = new StreamWriter(fileStream, new UTF8Encoding(false));
}
else
{
binWriter = new BinaryWriter(fileStream);
}
}
public void Initialize()
{
CreateInternalWriters();
if (binWriter != null)
{
binWriter.Write(GetAsciiBytes(DxfFile.BinarySentinel));
binWriter.Write((byte)'\r');
binWriter.Write((byte)'\n');
binWriter.Write((byte)26);
binWriter.Write((byte)0);
}
}
public void Close()
{
WriteCodeValuePair(new DxfCodePair(0, DxfFile.EofText));
Flush();
}
/// <summary>
/// Test-only helper.
/// </summary>
internal void Flush()
{
if (textWriter != null)
{
textWriter.Flush();
}
if (binWriter != null)
{
binWriter.Flush();
}
}
public void WriteCodeValuePair(DxfCodePair pair)
{
WriteCode(pair.Code);
WriteValue(pair.Code, pair.Value);
}
public void WriteCodeValuePairs(IEnumerable<DxfCodePair> pairs)
{
foreach (var pair in pairs)
WriteCodeValuePair(pair);
}
private void WriteCode(int code)
{
if (textWriter != null)
{
WriteLine(CodeAsString(code));
}
else if (binWriter != null)
{
if (version >= DxfAcadVersion.R13)
{
// 2 byte codes
binWriter.Write((short)code);
}
else if (code >= 255)
{
binWriter.Write((byte)255);
binWriter.Write((short)code);
}
else
{
binWriter.Write((byte)code);
}
}
else
{
throw new InvalidOperationException("No writer available");
}
}
internal static string CodeAsString(int code)
{
return code.ToString(CultureInfo.InvariantCulture).PadLeft(3);
}
private void WriteValue(int code, object value)
{
var type = DxfCodePair.ExpectedType(code);
if (type == typeof(string))
WriteString((string)value);
else if (type == typeof(double))
WriteDouble((double)value);
else if (type == typeof(short))
WriteShort((short)value);
else if (type == typeof(int))
WriteInt((int)value);
else if (type == typeof(long))
WriteLong((long)value);
else if (type == typeof(bool))
{
if (DxfCodePair.IsPotentialShortAsBool(code) && value.GetType() == typeof(short))
WriteShort((short)value);
else
WriteBool((bool)value);
}
else if (type == typeof(byte[]))
WriteBinary((byte[])value);
else
throw new InvalidOperationException("No writer available");
}
private void WriteString(string value)
{
if (textWriter != null)
WriteStringWithEncoding(TransformControlCharacters(value ?? string.Empty));
else if (binWriter != null)
{
binWriter.Write(GetAsciiBytes(value));
binWriter.Write((byte)0);
}
}
/// <summary>
/// Internal to make testing easier.
/// </summary>
/// <param name="value"></param>
internal void WriteStringWithEncoding(string value)
{
if (version <= DxfAcadVersion.R2004)
{
value = EscapeUnicode(value);
}
WriteLine(value);
}
private static bool IsUnicodeCharacter(char c)
{
return c > 127;
}
private static bool HasUnicodeCharacter(string value)
{
foreach (var c in value)
{
if (IsUnicodeCharacter(c))
{
return true;
}
}
return false;
}
private static string EscapeUnicode(string value)
{
if (HasUnicodeCharacter(value))
{
var sb = new StringBuilder();
foreach (var c in value)
{
if (IsUnicodeCharacter(c))
{
sb.Append($"\\U+{(uint)c:X4}");
}
else
{
sb.Append(c);
}
}
return sb.ToString();
}
else
{
return value;
}
}
internal static string DoubleAsString(double value)
{
return value.ToString("0.0##############", CultureInfo.InvariantCulture);
}
private void WriteDouble(double value)
{
if (textWriter != null)
WriteLine(DoubleAsString(value));
else if (binWriter != null)
binWriter.Write(value);
}
internal static string ShortAsString(short value)
{
return value.ToString(CultureInfo.InvariantCulture).PadLeft(6);
}
private void WriteShort(short value)
{
if (textWriter != null)
WriteLine(ShortAsString(value));
else if (binWriter != null)
binWriter.Write(value);
}
internal static string IntAsString(int value)
{
return value.ToString(CultureInfo.InvariantCulture).PadLeft(9);
}
private void WriteInt(int value)
{
if (textWriter != null)
WriteLine(IntAsString(value));
else if (binWriter != null)
binWriter.Write(value);
}
internal static string LongAsString(long value)
{
return value.ToString(CultureInfo.InvariantCulture);
}
private void WriteLong(long value)
{
if (textWriter != null)
WriteLine(LongAsString(value));
else if (binWriter != null)
binWriter.Write(value);
}
private void WriteBool(bool value)
{
if (version >= DxfAcadVersion.R13 && binWriter != null)
{
// post R13 binary files write bools as a single byte
binWriter.Write((byte)(value ? 0x01 : 0x00));
}
else
{
WriteShort(value ? (short)1 : (short)0);
}
}
private void WriteBinary(byte[] value)
{
if (textWriter != null)
WriteLine(DxfCommonConverters.HexBytes(value));
else if (binWriter != null)
{
binWriter.Write((byte)value.Length);
binWriter.Write(value);
}
}
private void WriteLine(string value)
{
textWriter.Write(value);
textWriter.Write("\r\n");
}
private static byte[] GetAsciiBytes(string value)
{
var result = new byte[value.Length];
for (int i = 0; i < value.Length; i++)
{
result[i] = (byte)value[i];
}
return result;
}
internal static string TransformControlCharacters(string str)
{
var sb = new StringBuilder();
foreach (var c in str)
{
if ((c >= 0x00 && c <= 0x1F) || c == '^')
{
sb.Append('^');
sb.Append(TransformControlCharacter(c));
}
else
{
sb.Append(c);
}
}
return sb.ToString();
}
private static char TransformControlCharacter(char c)
{
switch ((int)c)
{
case 0x00: return '@';
case 0x01: return 'A';
case 0x02: return 'B';
case 0x03: return 'C';
case 0x04: return 'D';
case 0x05: return 'E';
case 0x06: return 'F';
case 0x07: return 'G';
case 0x08: return 'H';
case 0x09: return 'I';
case 0x0A: return 'J';
case 0x0B: return 'K';
case 0x0C: return 'L';
case 0x0D: return 'M';
case 0x0E: return 'N';
case 0x0F: return 'O';
case 0x10: return 'P';
case 0x11: return 'Q';
case 0x12: return 'R';
case 0x13: return 'S';
case 0x14: return 'T';
case 0x15: return 'U';
case 0x16: return 'V';
case 0x17: return 'W';
case 0x18: return 'X';
case 0x19: return 'Y';
case 0x1A: return 'Z';
case 0x1B: return '[';
case 0x1C: return '\\';
case 0x1D: return ']';
case 0x1E: return '^';
case 0x1F: return '_';
case '^': return ' ';
default:
return c;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Firebase;
using Firebase.Extensions;
using Firebase.Firestore;
using UnityEngine.TestTools;
using Firebase.Sample.Firestore;
using NUnit.Framework;
using UnityEngine;
using static Tests.TestAsserts;
namespace Tests {
public class QueryAndListenerTests : FirestoreIntegrationTests {
[UnityTest]
public IEnumerator TestListenForSnapshotsInSync() {
var events = new List<string>();
var doc = TestDocument();
var docAccumulator = new EventAccumulator<DocumentSnapshot>(mainThreadId);
var docListener = doc.Listen(snapshot => {
events.Add("doc");
docAccumulator.Listener(snapshot);
});
yield return AwaitSuccess(doc.SetAsync(TestData(1)));
yield return AwaitSuccess(docAccumulator.LastEventAsync());
events.Clear();
var syncAccumulator = new EventAccumulator<string>();
var syncListener = doc.Firestore.ListenForSnapshotsInSync(() => {
events.Add("sync");
syncAccumulator.Listener("sync");
});
// Ensure that the Task from the ListenerRegistration is in the correct state.
AssertTaskIsPending(syncListener.ListenerTask);
yield return AwaitSuccess(doc.SetAsync(TestData(2)));
yield return AwaitSuccess(docAccumulator.LastEventAsync());
yield return AwaitSuccess(syncAccumulator.LastEventsAsync(2));
var expectedEvents = new List<string> {
"sync", // Initial in-sync event
"doc", // From the Set()
"sync" // Another in-sync event
};
docListener.Stop();
syncListener.Stop();
yield return AwaitSuccess(syncListener.ListenerTask);
Assert.That(events, Is.EquivalentTo(expectedEvents));
}
[UnityTest]
public IEnumerator TestMultiInstanceDocumentReferenceListeners() {
var db1Doc = TestDocument();
var db1 = db1Doc.Firestore;
var app1 = db1.App;
var app2 = FirebaseApp.Create(app1.Options, "MultiInstanceDocumentReferenceListenersTest");
var db2 = FirebaseFirestore.GetInstance(app2);
var db2Doc = db2.Collection(db1Doc.Parent.Id).Document(db1Doc.Id);
var db1DocAccumulator = new EventAccumulator<DocumentSnapshot>();
db1Doc.Listen(db1DocAccumulator.Listener);
yield return AwaitSuccess(db1DocAccumulator.LastEventAsync());
var db2DocAccumulator = new EventAccumulator<DocumentSnapshot>();
db2Doc.Listen(db2DocAccumulator.Listener);
yield return AwaitSuccess(db2DocAccumulator.LastEventAsync());
// At this point we have two firestore instances and separate listeners attached to each one
// and all are in an idle state. Once the second instance is disposed the listeners on the
// first instance should continue to operate normally and the listeners on the second instance
// should not receive any more events.
db2DocAccumulator.ThrowOnAnyEvent();
app2.Dispose();
yield return AwaitFaults(db2Doc.SetAsync(TestData(3)));
yield return AwaitSuccess(db1Doc.SetAsync(TestData(3)));
yield return AwaitSuccess(db1DocAccumulator.LastEventAsync());
}
[UnityTest]
public IEnumerator TestMultiInstanceQueryListeners() {
var db1Collection = TestCollection();
var db1 = db1Collection.Firestore;
var app1 = db1.App;
var app2 = FirebaseApp.Create(app1.Options, "MultiInstanceQueryListenersTest");
var db2 = FirebaseFirestore.GetInstance(app2);
var db2Collection = db2.Collection(db1Collection.Id);
var db1CollectionAccumulator = new EventAccumulator<QuerySnapshot>();
db1Collection.Listen(db1CollectionAccumulator.Listener);
yield return AwaitSuccess(db1CollectionAccumulator.LastEventAsync());
var db2CollectionAccumulator = new EventAccumulator<QuerySnapshot>();
db2Collection.Listen(db2CollectionAccumulator.Listener);
yield return AwaitSuccess(db2CollectionAccumulator.LastEventAsync());
// At this point we have two firestore instances and separate listeners
// attached to each one and all are in an idle state. Once the second
// instance is disposed the listeners on the first instance should
// continue to operate normally and the listeners on the second
// instance should not receive any more events.
db2CollectionAccumulator.ThrowOnAnyEvent();
app2.Dispose();
yield return AwaitFaults(db2Collection.Document().SetAsync(TestData(1)));
yield return AwaitSuccess(db1Collection.Document().SetAsync(TestData(1)));
yield return AwaitSuccess(db1CollectionAccumulator.LastEventAsync());
}
[UnityTest]
public IEnumerator TestMultiInstanceSnapshotsInSyncListeners() {
var db1Doc = TestDocument();
var db1 = db1Doc.Firestore;
var app1 = db1.App;
var app2 = FirebaseApp.Create(app1.Options, "MultiInstanceSnapshotsInSyncTest");
var db2 = FirebaseFirestore.GetInstance(app2);
var db2Doc = db2.Collection(db1Doc.Parent.Id).Document(db1Doc.Id);
var db1SyncAccumulator = new EventAccumulator<string>();
var db1SyncListener =
db1.ListenForSnapshotsInSync(() => { db1SyncAccumulator.Listener("db1 in sync"); });
yield return AwaitSuccess(db1SyncAccumulator.LastEventAsync());
var db2SyncAccumulator = new EventAccumulator<string>();
db2.ListenForSnapshotsInSync(() => { db2SyncAccumulator.Listener("db2 in sync"); });
yield return AwaitSuccess(db2SyncAccumulator.LastEventAsync());
db1Doc.Listen((snap) => {});
yield return AwaitSuccess(db1SyncAccumulator.LastEventAsync());
db2Doc.Listen((snap) => {});
yield return AwaitSuccess(db2SyncAccumulator.LastEventAsync());
// At this point we have two firestore instances and separate listeners
// attached to each one and all are in an idle state. Once the second
// instance is disposed the listeners on the first instance should
// continue to operate normally and the listeners on the second
// instance should not receive any more events.
db2SyncAccumulator.ThrowOnAnyEvent();
app2.Dispose();
yield return AwaitFaults(db2Doc.SetAsync(TestData(2)));
yield return AwaitSuccess(db1Doc.SetAsync(TestData(2)));
yield return AwaitSuccess(db1SyncAccumulator.LastEventAsync());
}
[UnityTest]
public IEnumerator TestDocumentSnapshot() {
DocumentReference doc = db.Collection("col2").Document();
var data = TestData();
yield return AwaitSuccess(doc.SetAsync(data));
var task = doc.GetSnapshotAsync();
yield return AwaitSuccess(task);
var snap = task.Result;
VerifyDocumentSnapshotGetValueWorks(snap, data);
VerifyDocumentSnapshotTryGetValueWorks(snap, data);
VerifyDocumentSnapshotContainsFieldWorks(snap, data);
}
private void VerifyDocumentSnapshotGetValueWorks(DocumentSnapshot snap,
Dictionary<string, object> data) {
Assert.That(snap.GetValue<string>("name"), Is.EqualTo(data["name"]));
Assert.That(snap.GetValue<Dictionary<string, object>>("metadata"),
Is.EquivalentTo(data["metadata"] as IEnumerable),
"Resulting data.metadata does not match.");
Assert.That(snap.GetValue<string>("metadata.deep.field"), Is.EqualTo("deep-field-1"));
Assert.That(snap.GetValue<string>(new FieldPath("metadata", "deep", "field")),
Is.EqualTo("deep-field-1"));
// Nonexistent field.
Assert.Throws(typeof(InvalidOperationException), () => snap.GetValue<object>("nonexistent"));
// Existent field deserialized to wrong type.
Assert.Throws(typeof(ArgumentException), () => snap.GetValue<long>("name"));
}
private void VerifyDocumentSnapshotTryGetValueWorks(DocumentSnapshot snap,
Dictionary<string, object> data) {
// Existent field.
String name;
Assert.That(snap.TryGetValue<string>("name", out name), Is.True);
Assert.That(name, Is.EqualTo(data["name"]));
// Nonexistent field.
Assert.That(snap.TryGetValue<string>("namex", out name), Is.False);
Assert.That(name, Is.Null);
// Existent field deserialized to wrong type.
Assert.Throws(typeof(ArgumentException), () => {
long l;
snap.TryGetValue<long>("name", out l);
});
}
private void VerifyDocumentSnapshotContainsFieldWorks(DocumentSnapshot snap,
Dictionary<string, object> data) {
// Existent fields.
Assert.That(snap.ContainsField("name"), Is.True);
Assert.That(snap.ContainsField("metadata.deep.field"), Is.True);
Assert.That(snap.ContainsField(new FieldPath("metadata", "deep", "field")), Is.True);
// Nonexistent field.
Assert.That(snap.ContainsField("namex"), Is.False);
}
[UnityTest]
public IEnumerator TestDocumentSnapshotServerTimestampBehavior() {
DocumentReference doc = db.Collection("col2").Document();
// Disable network so we can test unresolved server timestamp behavior.
yield return AwaitSuccess(doc.Firestore.DisableNetworkAsync());
doc.SetAsync(new Dictionary<string, object> { { "timestamp", "prev" } });
doc.SetAsync(new Dictionary<string, object> { { "timestamp", FieldValue.ServerTimestamp } });
Task<DocumentSnapshot> task = doc.GetSnapshotAsync();
yield return AwaitSuccess(task);
var snap = task.Result;
// Default / None should return null.
Assert.That(snap.ToDictionary()["timestamp"], Is.Null);
Assert.That(snap.GetValue<object>("timestamp"), Is.Null);
Assert.That(snap.ToDictionary(ServerTimestampBehavior.None)["timestamp"], Is.Null);
Assert.That(snap.GetValue<object>("timestamp", ServerTimestampBehavior.None), Is.Null);
// Previous should be "prev"
Assert.That(snap.ToDictionary(ServerTimestampBehavior.Previous)["timestamp"],
Is.EqualTo("prev"));
Assert.That(snap.GetValue<object>("timestamp", ServerTimestampBehavior.Previous),
Is.EqualTo("prev"));
// Estimate should be a timestamp.
Assert.That(snap.ToDictionary(ServerTimestampBehavior.Estimate)["timestamp"],
Is.TypeOf(typeof(Timestamp)), "Estimate should be a Timestamp");
Assert.That(snap.GetValue<object>("timestamp", ServerTimestampBehavior.Estimate),
Is.TypeOf(typeof(Timestamp)), "Estimate should be a Timestamp");
yield return AwaitSuccess(doc.Firestore.EnableNetworkAsync());
}
[UnityTest]
public IEnumerator TestDocumentSnapshotIntegerIncrementBehavior() {
DocumentReference doc = TestDocument();
var data = TestData();
yield return AwaitSuccess(doc.SetAsync(data));
var incrementValue = FieldValue.Increment(1L);
var updateData = new Dictionary<string, object> { { "metadata.createdAt", incrementValue } };
yield return AwaitSuccess(doc.UpdateAsync(updateData));
var t = doc.GetSnapshotAsync();
yield return AwaitSuccess(t);
DocumentSnapshot snap = t.Result;
var expected = TestData();
((Dictionary<string, object>)expected["metadata"])["createdAt"] = 2L;
Assert.That(snap.ToDictionary(), Is.EquivalentTo(expected));
}
[UnityTest]
public IEnumerator TestDocumentSnapshotDoubleIncrementBehavior() {
DocumentReference doc = TestDocument();
var data = TestData();
yield return AwaitSuccess(doc.SetAsync(data));
var incrementValue = FieldValue.Increment(1.5);
var updateData = new Dictionary<string, object> { { "metadata.createdAt", incrementValue } };
yield return AwaitSuccess(doc.UpdateAsync(updateData));
var t = doc.GetSnapshotAsync();
yield return AwaitSuccess(t);
DocumentSnapshot snap = t.Result;
var expected = TestData();
((Dictionary<string, object>)expected["metadata"])["createdAt"] = 2.5;
Assert.That(snap.ToDictionary(), Is.EquivalentTo(expected));
}
[UnityTest]
public IEnumerator TestDocumentListen() {
var doc = TestDocument();
var initialData = TestData(1);
var newData = TestData(2);
yield return AwaitSuccess(doc.SetAsync(initialData));
var accumulator = new EventAccumulator<DocumentSnapshot>(mainThreadId);
var registration = doc.Listen(accumulator.Listener);
// Ensure that the Task from the ListenerRegistration is in the correct state.
AssertTaskIsPending(registration.ListenerTask);
// Wait for the first snapshot.
{
var lastEventTask = accumulator.LastEventAsync();
yield return AwaitSuccess(lastEventTask);
DocumentSnapshot snapshot = lastEventTask.Result;
Assert.That(snapshot.ToDictionary(), Is.EquivalentTo(initialData));
Assert.That(snapshot.Metadata.IsFromCache, Is.True);
Assert.That(snapshot.Metadata.HasPendingWrites, Is.False);
}
// Write new data and wait for the resulting snapshot.
{
doc.SetAsync(newData);
var lastEventTask = accumulator.LastEventAsync();
yield return AwaitSuccess(lastEventTask);
DocumentSnapshot snapshot = lastEventTask.Result;
Assert.That(snapshot.ToDictionary(), Is.EquivalentTo(newData));
Assert.That(snapshot.Metadata.HasPendingWrites, Is.True);
}
{
// Remove the listener and make sure we don't get events anymore.
accumulator.ThrowOnAnyEvent();
registration.Stop();
AssertTaskSucceeded(registration.ListenerTask);
yield return AwaitSuccess(doc.SetAsync(TestData(3)));
// Ensure that the Task from the ListenerRegistration correctly fails with an error.
var docWithInvalidName = TestCollection().Document("__badpath__");
var callbackInvoked = false;
var registration2 = docWithInvalidName.Listen(snap => { callbackInvoked = true; });
yield return AwaitCompletion(registration2.ListenerTask);
AssertTaskFaulted(registration2.ListenerTask, FirestoreError.InvalidArgument,
"__badpath__");
registration2.Stop();
Thread.Sleep(50);
Assert.That(callbackInvoked, Is.False);
}
}
[UnityTest]
public IEnumerator DocumentSnapshot_ShouldReturnCorrectMetadataChanges() {
var doc = TestDocument();
var initialData = TestData(1);
var newData = TestData(2);
yield return AwaitSuccess(doc.SetAsync(initialData));
var accumulator = new EventAccumulator<DocumentSnapshot>();
var registration = doc.Listen(MetadataChanges.Include, accumulator.Listener);
// Ensure that the Task from the ListenerRegistration is in the correct state.
AssertTaskIsPending(registration.ListenerTask);
// Wait for the first snapshot.
{
var lastEventTask = accumulator.LastEventAsync();
yield return AwaitSuccess(lastEventTask);
DocumentSnapshot snapshot = lastEventTask.Result;
Assert.That(snapshot.ToDictionary(), Is.EquivalentTo(initialData));
Assert.That(snapshot.Metadata.IsFromCache, Is.True);
Assert.That(snapshot.Metadata.HasPendingWrites, Is.False);
}
// Wait for new snapshot once we're synced with the backend.
{
var lastEventTask = accumulator.LastEventAsync();
yield return AwaitSuccess(lastEventTask);
DocumentSnapshot snapshot = lastEventTask.Result;
Assert.That(snapshot.ToDictionary(), Is.EquivalentTo(initialData));
Assert.That(snapshot.Metadata.IsFromCache, Is.False);
Assert.That(snapshot.Metadata.HasPendingWrites, Is.False);
}
// Write new data and wait for the resulting snapshot.
{
doc.SetAsync(newData);
var lastEventTask = accumulator.LastEventAsync();
yield return AwaitSuccess(lastEventTask);
DocumentSnapshot snapshot = lastEventTask.Result;
Assert.That(snapshot.ToDictionary(), Is.EquivalentTo(newData));
Assert.That(snapshot.Metadata.IsFromCache, Is.False);
Assert.That(snapshot.Metadata.HasPendingWrites, Is.True);
}
// Wait for new snapshot once write completes.
{
var lastEventTask = accumulator.LastEventAsync();
yield return AwaitSuccess(lastEventTask);
DocumentSnapshot snapshot = lastEventTask.Result;
Assert.That(snapshot.Metadata.HasPendingWrites, Is.False);
}
{
// Remove the listener and make sure we don't get events anymore.
accumulator.ThrowOnAnyEvent();
registration.Stop();
AssertTaskSucceeded(registration.ListenerTask);
yield return AwaitSuccess(doc.SetAsync(TestData(3)));
// Ensure that the Task from the ListenerRegistration correctly fails with an error.
var docWithInvalidName = TestCollection().Document("__badpath__");
var callbackInvoked = false;
var registration2 =
docWithInvalidName.Listen(MetadataChanges.Include, snap => { callbackInvoked = true; });
yield return AwaitCompletion(registration2.ListenerTask);
AssertTaskFaulted(registration2.ListenerTask, FirestoreError.InvalidArgument,
"__badpath__");
registration2.Stop();
Thread.Sleep(50);
Assert.That(callbackInvoked, Is.False);
}
}
[UnityTest]
public IEnumerator QuerySnapshot_ShouldReturnCorrectData() {
var collection = TestCollection();
var data1 = TestData(1);
var data2 = TestData(2);
yield return AwaitSuccess(collection.Document("a").SetAsync(data1));
var accumulator = new EventAccumulator<QuerySnapshot>(mainThreadId);
var registration = collection.Listen(accumulator.Listener);
// Ensure that the Task from the ListenerRegistration is in the correct state.
AssertTaskIsPending(registration.ListenerTask);
// Wait for the first snapshot.
{
var lastEventTask = accumulator.LastEventAsync();
yield return AwaitSuccess(lastEventTask);
QuerySnapshot snapshot = lastEventTask.Result;
Assert.That(snapshot.Count, Is.EqualTo(1));
Assert.That(snapshot[0].ToDictionary(), Is.EquivalentTo(data1));
Assert.That(snapshot.Metadata.IsFromCache, Is.True);
Assert.That(snapshot.Metadata.HasPendingWrites, Is.False);
}
// Write a new document and wait for the resulting snapshot.
{
collection.Document("b").SetAsync(data2);
var lastEventTask = accumulator.LastEventAsync();
yield return AwaitSuccess(lastEventTask);
QuerySnapshot snapshot = lastEventTask.Result;
Assert.That(snapshot.Count, Is.EqualTo(2));
Assert.That(snapshot[0].ToDictionary(), Is.EquivalentTo(data1));
Assert.That(snapshot[1].ToDictionary(), Is.EquivalentTo(data2));
Assert.That(snapshot.Metadata.HasPendingWrites, Is.True);
}
{
// Remove the listener and make sure we don't get events anymore
accumulator.ThrowOnAnyEvent();
registration.Stop();
AssertTaskSucceeded(registration.ListenerTask);
yield return AwaitSuccess(collection.Document("c").SetAsync(TestData(3)));
// Ensure that the Task from the ListenerRegistration correctly fails with an error.
var collectionWithInvalidName = TestCollection().Document("__badpath__").Collection("sub");
var callbackInvoked = false;
var registration2 = collectionWithInvalidName.Listen(snap => { callbackInvoked = true; });
yield return AwaitCompletion(registration2.ListenerTask);
AssertTaskFaulted(registration2.ListenerTask, FirestoreError.InvalidArgument,
"__badpath__");
registration2.Stop();
Thread.Sleep(50);
Assert.That(callbackInvoked, Is.False);
}
}
[UnityTest]
public IEnumerator QuerySnapshot_ShouldReturnCorrectMetadata() {
var collection = TestCollection();
var data1 = TestData(1);
var data2 = TestData(2);
yield return AwaitSuccess(collection.Document("a").SetAsync(data1));
var accumulator = new EventAccumulator<QuerySnapshot>();
var registration = collection.Listen(MetadataChanges.Include, accumulator.Listener);
// Ensure that the Task from the ListenerRegistration is in the correct state.
AssertTaskIsPending(registration.ListenerTask);
// Wait for the first snapshot.
{
var lastEventTask = accumulator.LastEventAsync();
yield return AwaitSuccess(lastEventTask);
QuerySnapshot snapshot = lastEventTask.Result;
Assert.That(snapshot.Count, Is.EqualTo(1));
Assert.That(snapshot[0].ToDictionary(), Is.EquivalentTo(data1));
Assert.That(snapshot.Metadata.IsFromCache, Is.True);
Assert.That(snapshot.Metadata.HasPendingWrites, Is.False);
}
// Wait for new snapshot once we're synced with the backend.
{
var lastEventTask = accumulator.LastEventAsync();
yield return AwaitSuccess(lastEventTask);
QuerySnapshot snapshot = lastEventTask.Result;
Assert.That(snapshot.Metadata.IsFromCache, Is.False);
}
// Write a new document and wait for the resulting snapshot.
{
collection.Document("b").SetAsync(data2);
var lastEventTask = accumulator.LastEventAsync();
yield return AwaitSuccess(lastEventTask);
QuerySnapshot snapshot = lastEventTask.Result;
Assert.That(snapshot.Count, Is.EqualTo(2));
Assert.That(snapshot[0].ToDictionary(), Is.EquivalentTo(data1));
Assert.That(snapshot[1].ToDictionary(), Is.EquivalentTo(data2));
Assert.That(snapshot.Metadata.HasPendingWrites, Is.True);
}
// Wait for new snapshot once write completes.
{
var lastEventTask = accumulator.LastEventAsync();
yield return AwaitSuccess(lastEventTask);
QuerySnapshot snapshot = lastEventTask.Result;
Assert.That(snapshot.Metadata.HasPendingWrites, Is.False);
}
{
// Remove the listener and make sure we don't get events anymore.
accumulator.ThrowOnAnyEvent();
registration.Stop();
AssertTaskSucceeded(registration.ListenerTask);
yield return AwaitSuccess(collection.Document("c").SetAsync(TestData(3)));
// Ensure that the Task from the ListenerRegistration correctly fails with an error.
var collectionWithInvalidName = TestCollection().Document("__badpath__").Collection("sub");
var callbackInvoked = false;
var registration2 = collectionWithInvalidName.Listen(MetadataChanges.Include,
snap => { callbackInvoked = true; });
yield return AwaitCompletion(registration2.ListenerTask);
AssertTaskFaulted(registration2.ListenerTask, FirestoreError.InvalidArgument,
"__badpath__");
registration2.Stop();
Thread.Sleep(50);
Assert.That(callbackInvoked, Is.False);
}
}
[UnityTest]
public IEnumerator QuerySnapshot_ShouldChangeCorrectly() {
var collection = TestCollection();
var initialData = TestData(1);
var updatedData = TestData(2);
yield return AwaitSuccess(collection.Document("a").SetAsync(initialData));
var accumulator = new EventAccumulator<QuerySnapshot>();
var registration = collection.Listen(MetadataChanges.Include, accumulator.Listener);
// Wait for the first snapshot.
yield return AwaitSuccess(accumulator.LastEventAsync());
// Wait for new snapshot once we're synced with the backend.
yield return AwaitSuccess(accumulator.LastEventAsync());
// Update the document and wait for the latency compensated snapshot.
{
collection.Document("a").SetAsync(updatedData);
var lastEventTask = accumulator.LastEventAsync();
yield return AwaitSuccess(lastEventTask);
QuerySnapshot snapshot = lastEventTask.Result;
Assert.That(snapshot[0].ToDictionary(), Is.EquivalentTo(updatedData));
Assert.That(snapshot.Metadata.HasPendingWrites, Is.True);
}
// Wait for backend acknowledged snapshot.
{
var lastEventTask = accumulator.LastEventAsync();
yield return AwaitSuccess(lastEventTask);
QuerySnapshot snapshot = lastEventTask.Result;
Assert.That(snapshot.Metadata.HasPendingWrites, Is.False);
var changes = snapshot.GetChanges();
Assert.That(changes, Is.Empty);
var changesIncludingMetadata = snapshot.GetChanges(MetadataChanges.Include);
var changeList = changesIncludingMetadata.ToList();
Assert.That(changeList.Count(), Is.EqualTo(1));
var changedDocument = changeList.First().Document;
Assert.That(changedDocument.Metadata.HasPendingWrites, Is.False);
}
{
// Remove the listener and make sure we don't get events anymore.
accumulator.ThrowOnAnyEvent();
registration.Stop();
yield return AwaitSuccess(collection.Document("c").SetAsync(TestData(3)));
}
}
[UnityTest]
public IEnumerator CommonQueries_ShouldWork() {
// Initialize collection with a few test documents to query against.
var collection = TestCollection();
collection.Document("a").SetAsync(new Dictionary<string, object> {
{ "num", 1 },
{ "state", "created" },
{ "active", true },
{ "nullable", "value" },
});
collection.Document("b").SetAsync(new Dictionary<string, object> {
{ "num", 2 },
{ "state", "done" },
{ "active", false },
{ "nullable", null },
});
collection.Document("c").SetAsync(new Dictionary<string, object> {
{ "num", 3 },
{ "state", "done" },
{ "active", true },
{ "nullable", null },
});
// Put in a nested collection (with same ID) for testing collection group queries.
collection.Document("d")
.Collection(collection.Id)
.Document("d-nested")
.SetAsync(new Dictionary<string, object> {
{ "num", 4 },
{ "state", "created" },
{ "active", false },
{ "nullable", null },
});
yield return AwaitSuccess(db.WaitForPendingWritesAsync());
yield return AssertQueryResults(desc: "EqualTo", query: collection.WhereEqualTo("num", 1),
docIds: AsList("a"));
yield return AssertQueryResults(desc: "EqualTo (FieldPath)",
query: collection.WhereEqualTo(new FieldPath("num"), 1),
docIds: AsList("a"));
yield return AssertQueryResults(desc: "NotEqualTo",
query: collection.WhereNotEqualTo("num", 1),
docIds: AsList("b", "c"));
yield return AssertQueryResults(desc: "NotEqualTo (FieldPath)",
query: collection.WhereNotEqualTo(new FieldPath("num"), 1),
docIds: AsList("b", "c"));
yield return AssertQueryResults(
desc: "NotEqualTo (FieldPath) on nullable",
query: collection.WhereNotEqualTo(new FieldPath("nullable"), null), docIds: AsList("a"));
yield return AssertQueryResults(desc: "LessThanOrEqualTo",
query: collection.WhereLessThanOrEqualTo("num", 2),
docIds: AsList("a", "b"));
yield return AssertQueryResults(
desc: "LessThanOrEqualTo (FieldPath)",
query: collection.WhereLessThanOrEqualTo(new FieldPath("num"), 2),
docIds: AsList("a", "b"));
yield return AssertQueryResults(desc: "LessThan", query: collection.WhereLessThan("num", 2),
docIds: AsList("a"));
yield return AssertQueryResults(desc: "LessThan (FieldPath)",
query: collection.WhereLessThan(new FieldPath("num"), 2),
docIds: AsList("a"));
yield return AssertQueryResults(desc: "GreaterThanOrEqualTo",
query: collection.WhereGreaterThanOrEqualTo("num", 2),
docIds: AsList("b", "c"));
yield return AssertQueryResults(
desc: "GreaterThanOrEqualTo (FieldPath)",
query: collection.WhereGreaterThanOrEqualTo(new FieldPath("num"), 2),
docIds: AsList("b", "c"));
yield return AssertQueryResults(
desc: "GreaterThan", query: collection.WhereGreaterThan("num", 2), docIds: AsList("c"));
yield return AssertQueryResults(desc: "GreaterThan (FieldPath)",
query: collection.WhereGreaterThan(new FieldPath("num"), 2),
docIds: AsList("c"));
yield return AssertQueryResults(
desc: "two EqualTos",
query: collection.WhereEqualTo("state", "done").WhereEqualTo("active", false),
docIds: AsList("b"));
yield return AssertQueryResults(desc: "OrderBy, Limit",
query: collection.OrderBy("num").Limit(2),
docIds: AsList("a", "b"));
yield return AssertQueryResults(desc: "OrderBy, Limit (FieldPath)",
query: collection.OrderBy(new FieldPath("num")).Limit(2),
docIds: AsList("a", "b"));
yield return AssertQueryResults(desc: "OrderByDescending, Limit",
query: collection.OrderByDescending("num").Limit(2),
docIds: AsList("c", "b"));
yield return AssertQueryResults(
desc: "OrderByDescending, Limit (FieldPath)",
query: collection.OrderByDescending(new FieldPath("num")).Limit(2),
docIds: AsList("c", "b"));
yield return AssertQueryResults(
desc: "StartAfter", query: collection.OrderBy("num").StartAfter(2), docIds: AsList("c"));
yield return AssertQueryResults(
desc: "EndBefore", query: collection.OrderBy("num").EndBefore(2), docIds: AsList("a"));
yield return AssertQueryResults(desc: "StartAt, EndAt",
query: collection.OrderBy("num").StartAt(2).EndAt(2),
docIds: AsList("b"));
// Collection Group Query
yield return AssertQueryResults(desc: "CollectionGroup",
query: db.CollectionGroup(collection.Id),
docIds: AsList("a", "b", "c", "d-nested"));
}
private static List<T> AsList<T>(params T[] elements) {
return elements.ToList();
}
private IEnumerator AssertQueryResults(string desc, Query query, List<string> docIds) {
var getTask = query.GetSnapshotAsync();
yield return AwaitSuccess(getTask);
var snapshot = getTask.Result;
Assert.That(snapshot.AsEnumerable().Select(d => d.Id), Is.EquivalentTo(docIds),
desc + ": Query results");
}
[UnityTest]
public IEnumerator LimitToLastWithMirrorQuery_ShouldWork() {
var collection = TestCollection();
// TODO(b/149105903): Uncomment this line when exception can be raised from SWIG and below.
// Assert.Throws(typeof(InvalidOperationException), () =>
// Await(c.LimitToLast(2).GetSnapshotAsync())
// Initialize data with a few test documents to query against.
collection.Document("a").SetAsync(new Dictionary<string, object> {
{ "k", "a" },
{ "sort", 0 },
});
collection.Document("b").SetAsync(new Dictionary<string, object> {
{ "k", "b" },
{ "sort", 1 },
});
collection.Document("c").SetAsync(new Dictionary<string, object> {
{ "k", "c" },
{ "sort", 1 },
});
collection.Document("d").SetAsync(new Dictionary<string, object> {
{ "k", "d" },
{ "sort", 2 },
});
yield return AwaitSuccess(db.WaitForPendingWritesAsync());
// Setup `limit` query.
var limit = collection.Limit(2).OrderBy("sort");
var limitAccumulator = new EventAccumulator<QuerySnapshot>();
var limitRegistration = limit.Listen(limitAccumulator.Listener);
// Setup mirroring `limitToLast` query.
var limitToLast = collection.LimitToLast(2).OrderByDescending("sort");
var limitToLastAccumulator = new EventAccumulator<QuerySnapshot>();
var limitToLastRegistration = limitToLast.Listen(limitToLastAccumulator.Listener);
// Verify both query get expected result.
var lastEventTask = limitAccumulator.LastEventAsync();
yield return AwaitSuccess(lastEventTask);
var data = QuerySnapshotToValues(lastEventTask.Result);
Assert.That(data, Is.EquivalentTo(new List<Dictionary<string, object>> {
new Dictionary<string, object> { { "k", "a" }, { "sort", 0L } },
new Dictionary<string, object> { { "k", "b" }, { "sort", 1L } }
}));
lastEventTask = limitToLastAccumulator.LastEventAsync();
yield return AwaitSuccess(lastEventTask);
data = QuerySnapshotToValues(lastEventTask.Result);
Assert.That(data, Is.EquivalentTo(new List<Dictionary<string, object>> {
new Dictionary<string, object> { { "k", "b" }, { "sort", 1L } },
new Dictionary<string, object> { { "k", "a" }, { "sort", 0L } }
}));
// Unlisten then re-listen limit query.
limitRegistration.Stop();
limit.Listen(limitAccumulator.Listener);
// Verify `limit` query still works.
lastEventTask = limitAccumulator.LastEventAsync();
yield return AwaitSuccess(lastEventTask);
data = QuerySnapshotToValues(lastEventTask.Result);
Assert.That(data, Is.EquivalentTo(new List<Dictionary<string, object>> {
new Dictionary<string, object> { { "k", "a" }, { "sort", 0L } },
new Dictionary<string, object> { { "k", "b" }, { "sort", 1L } }
}));
// Add a document that would change the result set.
yield return AwaitSuccess(collection.Document("d").SetAsync(new Dictionary<string, object> {
{ "k", "e" },
{ "sort", -1 },
}));
// Verify both query get expected result.
lastEventTask = limitAccumulator.LastEventAsync();
yield return AwaitSuccess(lastEventTask);
data = QuerySnapshotToValues(lastEventTask.Result);
Assert.That(data, Is.EquivalentTo(new List<Dictionary<string, object>> {
new Dictionary<string, object> { { "k", "e" }, { "sort", -1L } },
new Dictionary<string, object> { { "k", "a" }, { "sort", 0L } }
}));
lastEventTask = limitToLastAccumulator.LastEventAsync();
yield return AwaitSuccess(lastEventTask);
data = QuerySnapshotToValues(lastEventTask.Result);
Assert.That(data, Is.EquivalentTo(new List<Dictionary<string, object>> {
new Dictionary<string, object> { { "k", "a" }, { "sort", 0L } },
new Dictionary<string, object> { { "k", "e" }, { "sort", -1L } }
}));
// Unlisten to limitToLast, update a doc, then relisten to limitToLast
limitToLastRegistration.Stop();
yield return AwaitSuccess(collection.Document("a").UpdateAsync("sort", -2));
limitToLast.Listen(limitToLastAccumulator.Listener);
// Verify both query get expected result.
lastEventTask = limitAccumulator.LastEventAsync();
yield return AwaitSuccess(lastEventTask);
data = QuerySnapshotToValues(lastEventTask.Result);
Assert.That(data, Is.EquivalentTo(new List<Dictionary<string, object>> {
new Dictionary<string, object> { { "k", "a" }, { "sort", -2L } },
new Dictionary<string, object> { { "k", "e" }, { "sort", -1L } }
}));
lastEventTask = limitToLastAccumulator.LastEventAsync();
yield return AwaitSuccess(lastEventTask);
data = QuerySnapshotToValues(lastEventTask.Result);
Assert.That(data, Is.EquivalentTo(new List<Dictionary<string, object>> {
new Dictionary<string, object> { { "k", "e" }, { "sort", -1L } },
new Dictionary<string, object> { { "k", "a" }, { "sort", -2L } }
}));
}
private static List<Dictionary<string, object>> QuerySnapshotToValues(QuerySnapshot snap) {
List<Dictionary<string, object>> result = new List<Dictionary<string, object>>();
foreach (DocumentSnapshot doc in snap) {
result.Add(doc.ToDictionary());
}
return result;
}
[UnityTest]
public IEnumerator ArrayContainsQuery_ShouldReturnCorrectDocuments() {
// Initialize collection with a few test documents to query against.
var collection = TestCollection();
collection.Document("a").SetAsync(new Dictionary<string, object> {
{ "array", new List<object> { 42 } },
});
collection.Document("b").SetAsync(new Dictionary<string, object> {
{ "array", new List<object> { "a", 42, "c" } },
});
collection.Document("c").SetAsync(new Dictionary<string, object> {
{ "array",
new List<object> {
41.999, "42", new Dictionary<string, object> { { "array", new List<object> { 42 } } }
} }
});
collection.Document("d").SetAsync(new Dictionary<string, object> {
{ "array", new List<object> { 42 } },
{ "array2", new List<object> { "bingo" } },
});
yield return AwaitSuccess(db.WaitForPendingWritesAsync());
yield return AssertQueryResults(
desc: "ArrayContains", query: collection.WhereArrayContains(new FieldPath("array"), 42),
docIds: AsList("a", "b", "d"));
yield return AssertQueryResults(desc: "ArrayContains",
query: collection.WhereArrayContains("array", 42),
docIds: AsList("a", "b", "d"));
}
[UnityTest]
public IEnumerator ArrayContainsAnyQuery_ShouldReturnCorrectDocuments() {
// Initialize collection with a few test documents to query against.
var collection = TestCollection();
collection.Document("a").SetAsync(new Dictionary<string, object> {
{ "array", new List<object> { 42 } },
});
collection.Document("b").SetAsync(new Dictionary<string, object> {
{ "array", new List<object> { "a", 42, "c" } },
});
collection.Document("c").SetAsync(new Dictionary<string, object> {
{ "array",
new List<object> {
41.999, "42", new Dictionary<string, object> { { "array", new List<object> { 42 } } }
} }
});
collection.Document("d").SetAsync(new Dictionary<string, object> {
{ "array", new List<object> { 42 } },
{ "array2", new List<object> { "bingo" } },
});
collection.Document("e").SetAsync(
new Dictionary<string, object> { { "array", new List<object> { 43 } } });
collection.Document("f").SetAsync(new Dictionary<string, object> {
{ "array", new List<object> { new Dictionary<string, object> { { "a", 42 } } } }
});
collection.Document("g").SetAsync(new Dictionary<string, object> {
{ "array", 42 },
});
yield return AwaitSuccess(db.WaitForPendingWritesAsync());
yield return AssertQueryResults(
desc: "ArrayContainsAny",
query: collection.WhereArrayContainsAny("array", new List<object> { 42, 43 }),
docIds: AsList("a", "b", "d", "e"));
yield return AssertQueryResults(
desc: "ArrayContainsAnyObject",
query: collection.WhereArrayContainsAny(
new FieldPath("array"),
new List<object> { new Dictionary<string, object> { { "a", 42 } } }),
docIds: AsList("f"));
}
[UnityTest]
public IEnumerator InQuery_ShouldReturnCorrectDocuments() {
// Initialize collection with a few test documents to query against.
var collection = TestCollection();
collection.Document("a").SetAsync(new Dictionary<string, object> {
{ "zip", 98101 },
{ "nullable", null },
});
collection.Document("b").SetAsync(new Dictionary<string, object> {
{ "zip", 98102 },
{ "nullable", "value" },
});
collection.Document("c").SetAsync(new Dictionary<string, object> {
{ "zip", 98103 },
{ "nullable", null },
});
collection.Document("d").SetAsync(
new Dictionary<string, object> { { "zip", new List<object> { 98101 } } });
collection.Document("e").SetAsync(new Dictionary<string, object> {
{ "zip", new List<object> { "98101", new Dictionary<string, object> { { "zip", 98101 } } } }
});
collection.Document("f").SetAsync(new Dictionary<string, object> {
{ "zip", new Dictionary<string, object> { { "code", 500 } } },
{ "nullable", 123 },
});
collection.Document("g").SetAsync(new Dictionary<string, object> {
{ "zip", new List<object> { 98101, 98102 } },
{ "nullable", null },
});
yield return AwaitSuccess(db.WaitForPendingWritesAsync());
yield return AssertQueryResults(
desc: "InQuery",
query: collection.WhereIn(
"zip", new List<object> { 98101, 98103, new List<object> { 98101, 98102 } }),
docIds: AsList("a", "c", "g"));
yield return AssertQueryResults(
desc: "InQueryWithObject",
query: collection.WhereIn(
new FieldPath("zip"),
new List<object> { new Dictionary<string, object> { { "code", 500 } } }),
docIds: AsList("f"));
yield return AssertQueryResults(
desc: "InQueryWithDocIds",
query: collection.WhereIn(FieldPath.DocumentId, new List<object> { "c", "e" }),
docIds: AsList("c", "e"));
yield return AssertQueryResults(
desc: "NotInQuery",
query: collection.WhereNotIn(
"zip", new List<object> { 98101, 98103, new List<object> { 98101, 98102 } }),
docIds: AsList("b", "d", "e", "f"));
yield return AssertQueryResults(
desc: "NotInQueryWithObject",
query: collection.WhereNotIn(
new FieldPath("zip"),
new List<object> { new List<object> { 98101, 98102 },
new Dictionary<string, object> { { "code", 500 } } }),
docIds: AsList("a", "b", "c", "d", "e"));
yield return AssertQueryResults(
desc: "NotInQueryWithDocIds",
query: collection.WhereNotIn(FieldPath.DocumentId, new List<object> { "a", "c", "e" }),
docIds: AsList("b", "d", "f", "g"));
yield return AssertQueryResults(
desc: "NotInQueryWithNulls",
query: collection.WhereNotIn(new FieldPath("nullable"), new List<object> { null }),
docIds: new List<String> {});
}
[UnityTest]
// Tests that DocumentReference and Query respect the Source parameter passed to
// GetSnapshotAsync(). We don't exhaustively test the behavior. We just do enough
// checks to verify that cache, default, and server produce distinct results.
public IEnumerator GetBySource_ShouldWork() {
DocumentReference doc = TestDocument();
yield return AwaitSuccess(doc.SetAsync(TestData()));
// Verify FromCache gives us cached results even when online.
{
var getByCache = doc.GetSnapshotAsync(Source.Cache);
yield return AwaitSuccess(getByCache);
DocumentSnapshot docSnap = getByCache.Result;
Assert.That(docSnap.Metadata.IsFromCache, Is.True);
var getParentByCache = doc.Parent.GetSnapshotAsync(Source.Cache);
yield return AwaitSuccess(getParentByCache);
QuerySnapshot querySnap = getParentByCache.Result;
Assert.That(querySnap.Metadata.IsFromCache, Is.True);
}
// Verify Default gives us non-cached results when online.
{
var getByDefault = doc.GetSnapshotAsync(Source.Default);
yield return AwaitSuccess(getByDefault);
DocumentSnapshot docSnap = getByDefault.Result;
Assert.That(docSnap.Metadata.IsFromCache, Is.False);
var getParentByDefault = doc.Parent.GetSnapshotAsync(Source.Default);
yield return AwaitSuccess(getParentByDefault);
QuerySnapshot querySnap = getParentByDefault.Result;
Assert.That(querySnap.Metadata.IsFromCache, Is.False);
}
{
// Disable network so we can test offline behavior.
yield return AwaitSuccess(doc.Firestore.DisableNetworkAsync());
// Verify Default gives us cached results when offline.
var getByDefault = doc.GetSnapshotAsync(Source.Default);
yield return AwaitSuccess(getByDefault);
DocumentSnapshot docSnap = getByDefault.Result;
Assert.That(docSnap.Metadata.IsFromCache, Is.True);
var getParentByDefault = doc.Parent.GetSnapshotAsync(Source.Default);
yield return AwaitSuccess(getParentByDefault);
QuerySnapshot querySnap = getParentByDefault.Result;
Assert.That(querySnap.Metadata.IsFromCache, Is.True);
var getByServer = doc.GetSnapshotAsync(Source.Server);
yield return AwaitCompletion(getByServer);
AssertTaskFaulted(getByServer, FirestoreError.Unavailable);
var getParentByServer = doc.Parent.GetSnapshotAsync(Source.Server);
yield return AwaitCompletion(getParentByServer);
AssertTaskFaulted(getParentByServer, FirestoreError.Unavailable);
yield return AwaitSuccess(doc.Firestore.EnableNetworkAsync());
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
$Pref::WorldEditor::FileSpec = "Torque Mission Files (*.mis)|*.mis|All Files (*.*)|*.*|";
//////////////////////////////////////////////////////////////////////////
// File Menu Handlers
//////////////////////////////////////////////////////////////////////////
function EditorFileMenu::onMenuSelect(%this)
{
%this.enableItem(2, EditorIsDirty());
}
//////////////////////////////////////////////////////////////////////////
// Package that gets temporarily activated to toggle editor after mission loading.
// Deactivates itself.
package BootEditor {
function GameConnection::initialControlSet( %this )
{
Parent::initialControlSet( %this );
toggleEditor( true );
deactivatePackage( "BootEditor" );
}
};
//////////////////////////////////////////////////////////////////////////
/// Checks the various dirty flags and returns true if the
/// mission or other related resources need to be saved.
function EditorIsDirty()
{
// We kept a hard coded test here, but we could break these
// into the registered tools if we wanted to.
%isDirty = ( isObject( "ETerrainEditor" ) && ( ETerrainEditor.isMissionDirty || ETerrainEditor.isDirty ) )
|| ( isObject( "EWorldEditor" ) && EWorldEditor.isDirty )
|| ( isObject( "ETerrainPersistMan" ) && ETerrainPersistMan.hasDirty() );
// Give the editor plugins a chance to set the dirty flag.
for ( %i = 0; %i < EditorPluginSet.getCount(); %i++ )
{
%obj = EditorPluginSet.getObject(%i);
%isDirty |= %obj.isDirty();
}
return %isDirty;
}
/// Clears all the dirty state without saving.
function EditorClearDirty()
{
EWorldEditor.isDirty = false;
ETerrainEditor.isDirty = false;
ETerrainEditor.isMissionDirty = false;
ETerrainPersistMan.clearAll();
for ( %i = 0; %i < EditorPluginSet.getCount(); %i++ )
{
%obj = EditorPluginSet.getObject(%i);
%obj.clearDirty();
}
}
function EditorQuitGame()
{
if( EditorIsDirty())
{
MessageBoxYesNoCancel("Level Modified", "Would you like to save your changes before quitting?", "EditorSaveMissionMenu(); quit();", "quit();", "" );
}
else
quit();
}
function EditorExitMission()
{
if( EditorIsDirty())
{
MessageBoxYesNoCancel("Level Modified", "Would you like to save your changes before exiting?", "EditorDoExitMission(true);", "EditorDoExitMission(false);", "");
}
else
EditorDoExitMission(false);
}
function EditorDoExitMission(%saveFirst)
{
if(%saveFirst)
{
EditorSaveMissionMenu();
}
else
{
EditorClearDirty();
}
if (isObject( MainMenuGui ))
Editor.close("MainMenuGui");
disconnect();
}
function EditorOpenTorsionProject( %projectFile )
{
// Make sure we have a valid path to the Torsion installation.
%torsionPath = EditorSettings.value( "WorldEditor/torsionPath" );
if( !isFile( %torsionPath ) )
{
MessageBoxOK(
"Torsion Not Found",
"Torsion not found at '" @ %torsionPath @ "'. Please set the correct path in the preferences."
);
return;
}
// Determine the path to the .torsion file.
if( %projectFile $= "" )
{
%projectName = fileBase( getExecutableName() );
%projectFile = makeFullPath( %projectName @ ".torsion" );
if( !isFile( %projectFile ) )
{
%projectFile = findFirstFile( "*.torsion", false );
if( !isFile( %projectFile ) )
{
MessageBoxOK(
"Project File Not Found",
"Cannot find .torsion project file in '" @ getMainDotCsDir() @ "'."
);
return;
}
}
}
// Open the project in Torsion.
shellExecute( %torsionPath, "\"" @ %projectFile @ "\"" );
}
function EditorOpenFileInTorsion( %file, %line )
{
// Make sure we have a valid path to the Torsion installation.
%torsionPath = EditorSettings.value( "WorldEditor/torsionPath" );
if( !isFile( %torsionPath ) )
{
MessageBoxOK(
"Torsion Not Found",
"Torsion not found at '" @ %torsionPath @ "'. Please set the correct path in the preferences."
);
return;
}
// If no file was specified, take the current mission file.
if( %file $= "" )
%file = makeFullPath( $Server::MissionFile );
// Open the file in Torsion.
%args = "\"" @ %file;
if( %line !$= "" )
%args = %args @ ":" @ %line;
%args = %args @ "\"";
shellExecute( %torsionPath, %args );
}
function EditorOpenDeclarationInTorsion( %object )
{
%fileName = %object.getFileName();
if( %fileName $= "" )
return;
EditorOpenFileInTorsion( makeFullPath( %fileName ), %object.getDeclarationLine() );
}
function EditorNewLevel( %file )
{
%saveFirst = false;
if ( EditorIsDirty() )
{
error(knob);
%saveFirst = MessageBox("Mission Modified", "Would you like to save changes to the current mission \"" @
$Server::MissionFile @ "\" before creating a new mission?", "SaveDontSave", "Question") == $MROk;
}
if(%saveFirst)
EditorSaveMission();
// Clear dirty flags first to avoid duplicate dialog box from EditorOpenMission()
if( isObject( Editor ) )
{
EditorClearDirty();
Editor.getUndoManager().clearAll();
}
if( %file $= "" )
%file = EditorSettings.value( "WorldEditor/newLevelFile" );
if( !$missionRunning )
{
activatePackage( "BootEditor" );
StartLevel( %file );
}
else
EditorOpenMission(%file);
//EWorldEditor.isDirty = true;
//ETerrainEditor.isDirty = true;
EditorGui.saveAs = true;
}
function EditorSaveMissionMenu()
{
if(EditorGui.saveAs)
EditorSaveMissionAs();
else
EditorSaveMission();
}
function EditorSaveMission()
{
// just save the mission without renaming it
// first check for dirty and read-only files:
if((EWorldEditor.isDirty || ETerrainEditor.isMissionDirty) && !isWriteableFileName($Server::MissionFile))
{
MessageBox("Error", "Mission file \""@ $Server::MissionFile @ "\" is read-only. Continue?", "Ok", "Stop");
return false;
}
if(ETerrainEditor.isDirty)
{
// Find all of the terrain files
initContainerTypeSearch($TypeMasks::TerrainObjectType);
while ((%terrainObject = containerSearchNext()) != 0)
{
if (!isWriteableFileName(%terrainObject.terrainFile))
{
if (MessageBox("Error", "Terrain file \""@ %terrainObject.terrainFile @ "\" is read-only. Continue?", "Ok", "Stop") == $MROk)
continue;
else
return false;
}
}
}
// now write the terrain and mission files out:
if(EWorldEditor.isDirty || ETerrainEditor.isMissionDirty)
MissionGroup.save($Server::MissionFile);
if(ETerrainEditor.isDirty)
{
// Find all of the terrain files
initContainerTypeSearch($TypeMasks::TerrainObjectType);
while ((%terrainObject = containerSearchNext()) != 0)
%terrainObject.save(%terrainObject.terrainFile);
}
ETerrainPersistMan.saveDirty();
// Give EditorPlugins a chance to save.
for ( %i = 0; %i < EditorPluginSet.getCount(); %i++ )
{
%obj = EditorPluginSet.getObject(%i);
if ( %obj.isDirty() )
%obj.onSaveMission( $Server::MissionFile );
}
EditorClearDirty();
EditorGui.saveAs = false;
return true;
}
function EditorSaveMissionAs( %missionName )
{
// If we didn't get passed a new mission name then
// prompt the user for one.
if ( %missionName $= "" )
{
%dlg = new SaveFileDialog()
{
Filters = $Pref::WorldEditor::FileSpec;
DefaultPath = EditorSettings.value("LevelInformation/levelsDirectory");
ChangePath = false;
OverwritePrompt = true;
};
%ret = %dlg.Execute();
if(%ret)
{
// Immediately override/set the levelsDirectory
EditorSettings.setValue( "LevelInformation/levelsDirectory", collapseFilename(filePath( %dlg.FileName )) );
%missionName = %dlg.FileName;
}
%dlg.delete();
if(! %ret)
return;
}
if( fileExt( %missionName ) !$= ".mis" )
%missionName = %missionName @ ".mis";
EWorldEditor.isDirty = true;
%saveMissionFile = $Server::MissionFile;
$Server::MissionFile = %missionName;
%copyTerrainsFailed = false;
// Rename all the terrain files. Save all previous names so we can
// reset them if saving fails.
%newMissionName = fileBase(%missionName);
%oldMissionName = fileBase(%saveMissionFile);
initContainerTypeSearch( $TypeMasks::TerrainObjectType );
%savedTerrNames = new ScriptObject();
for( %i = 0;; %i ++ )
{
%terrainObject = containerSearchNext();
if( !%terrainObject )
break;
%savedTerrNames.array[ %i ] = %terrainObject.terrainFile;
%terrainFilePath = makeRelativePath( filePath( %terrainObject.terrainFile ), getMainDotCsDir() );
%terrainFileName = fileName( %terrainObject.terrainFile );
// Workaround to have terrains created in an unsaved "New Level..." mission
// moved to the correct place.
if( EditorGui.saveAs && %terrainFilePath $= "tools/art/terrains" )
%terrainFilePath = "art/terrains";
// Try and follow the existing naming convention.
// If we can't, use systematic terrain file names.
if( strstr( %terrainFileName, %oldMissionName ) >= 0 )
%terrainFileName = strreplace( %terrainFileName, %oldMissionName, %newMissionName );
else
%terrainFileName = %newMissionName @ "_" @ %i @ ".ter";
%newTerrainFile = %terrainFilePath @ "/" @ %terrainFileName;
if (!isWriteableFileName(%newTerrainFile))
{
if (MessageBox("Error", "Terrain file \""@ %newTerrainFile @ "\" is read-only. Continue?", "Ok", "Stop") == $MROk)
continue;
else
{
%copyTerrainsFailed = true;
break;
}
}
if( !%terrainObject.save( %newTerrainFile ) )
{
error( "Failed to save '" @ %newTerrainFile @ "'" );
%copyTerrainsFailed = true;
break;
}
%terrainObject.terrainFile = %newTerrainFile;
}
ETerrainEditor.isDirty = false;
// Save the mission.
if(%copyTerrainsFailed || !EditorSaveMission())
{
// It failed, so restore the mission and terrain filenames.
$Server::MissionFile = %saveMissionFile;
initContainerTypeSearch( $TypeMasks::TerrainObjectType );
for( %i = 0;; %i ++ )
{
%terrainObject = containerSearchNext();
if( !%terrainObject )
break;
%terrainObject.terrainFile = %savedTerrNames.array[ %i ];
}
}
%savedTerrNames.delete();
}
function EditorOpenMission(%filename)
{
if( EditorIsDirty())
{
// "EditorSaveBeforeLoad();", "getLoadFilename(\"*.mis\", \"EditorDoLoadMission\");"
if(MessageBox("Mission Modified", "Would you like to save changes to the current mission \"" @
$Server::MissionFile @ "\" before opening a new mission?", SaveDontSave, Question) == $MROk)
{
if(! EditorSaveMission())
return;
}
}
if(%filename $= "")
{
%dlg = new OpenFileDialog()
{
Filters = $Pref::WorldEditor::FileSpec;
DefaultPath = EditorSettings.value("LevelInformation/levelsDirectory");
ChangePath = false;
MustExist = true;
};
%ret = %dlg.Execute();
if(%ret)
{
// Immediately override/set the levelsDirectory
EditorSettings.setValue( "LevelInformation/levelsDirectory", collapseFilename(filePath( %dlg.FileName )) );
%filename = %dlg.FileName;
}
%dlg.delete();
if(! %ret)
return;
}
// close the current editor, it will get cleaned up by MissionCleanup
if( isObject( "Editor" ) )
Editor.close( LoadingGui );
EditorClearDirty();
// If we haven't yet connnected, create a server now.
// Otherwise just load the mission.
if( !$missionRunning )
{
activatePackage( "BootEditor" );
StartLevel( %filename );
}
else
{
loadMission( %filename, true ) ;
pushInstantGroup();
// recreate and open the editor
Editor::create();
MissionCleanup.add( Editor );
MissionCleanup.add( Editor.getUndoManager() );
EditorGui.loadingMission = true;
Editor.open();
popInstantGroup();
}
}
function EditorExportToCollada()
{
%dlg = new SaveFileDialog()
{
Filters = "COLLADA Files (*.dae)|*.dae|";
DefaultPath = $Pref::WorldEditor::LastPath;
DefaultFile = "";
ChangePath = false;
OverwritePrompt = true;
};
%ret = %dlg.Execute();
if ( %ret )
{
$Pref::WorldEditor::LastPath = filePath( %dlg.FileName );
%exportFile = %dlg.FileName;
}
if( fileExt( %exportFile ) !$= ".dae" )
%exportFile = %exportFile @ ".dae";
%dlg.delete();
if ( !%ret )
return;
if ( EditorGui.currentEditor.getId() == ShapeEditorPlugin.getId() )
ShapeEdShapeView.exportToCollada( %exportFile );
else
EWorldEditor.colladaExportSelection( %exportFile );
}
function EditorMakePrefab()
{
%dlg = new SaveFileDialog()
{
Filters = "Prefab Files (*.prefab)|*.prefab|";
DefaultPath = $Pref::WorldEditor::LastPath;
DefaultFile = "";
ChangePath = false;
OverwritePrompt = true;
};
%ret = %dlg.Execute();
if ( %ret )
{
$Pref::WorldEditor::LastPath = filePath( %dlg.FileName );
%saveFile = %dlg.FileName;
}
if( fileExt( %saveFile ) !$= ".prefab" )
%saveFile = %saveFile @ ".prefab";
%dlg.delete();
if ( !%ret )
return;
EWorldEditor.makeSelectionPrefab( %saveFile );
EditorTree.buildVisibleTree( true );
}
function EditorExplodePrefab()
{
//echo( "EditorExplodePrefab()" );
EWorldEditor.explodeSelectedPrefab();
EditorTree.buildVisibleTree( true );
}
function makeSelectedAMesh()
{
%dlg = new SaveFileDialog()
{
Filters = "Collada file (*.dae)|*.dae|";
DefaultPath = $Pref::WorldEditor::LastPath;
DefaultFile = "";
ChangePath = false;
OverwritePrompt = true;
};
%ret = %dlg.Execute();
if ( %ret )
{
$Pref::WorldEditor::LastPath = filePath( %dlg.FileName );
%saveFile = %dlg.FileName;
}
if( fileExt( %saveFile ) !$= ".dae" )
%saveFile = %saveFile @ ".dae";
%dlg.delete();
if ( !%ret )
return;
EWorldEditor.makeSelectionAMesh( %saveFile );
EditorTree.buildVisibleTree( true );
}
function EditorMount()
{
echo( "EditorMount" );
%size = EWorldEditor.getSelectionSize();
if ( %size != 2 )
return;
%a = EWorldEditor.getSelectedObject(0);
%b = EWorldEditor.getSelectedObject(1);
//%a.mountObject( %b, 0 );
EWorldEditor.mountRelative( %a, %b );
}
function EditorUnmount()
{
echo( "EditorUnmount" );
%obj = EWorldEditor.getSelectedObject(0);
%obj.unmount();
}
//////////////////////////////////////////////////////////////////////////
// View Menu Handlers
//////////////////////////////////////////////////////////////////////////
function EditorViewMenu::onMenuSelect( %this )
{
%this.checkItem( 1, EWorldEditor.renderOrthoGrid );
}
//////////////////////////////////////////////////////////////////////////
// Edit Menu Handlers
//////////////////////////////////////////////////////////////////////////
function EditorEditMenu::onMenuSelect( %this )
{
// UndoManager is in charge of enabling or disabling the undo/redo items.
Editor.getUndoManager().updateUndoMenu( %this );
// SICKHEAD: It a perfect world we would abstract
// cut/copy/paste with a generic selection object
// which would know how to process itself.
// Give the active editor a chance at fixing up
// the state of the edit menu.
// Do we really need this check here?
if ( isObject( EditorGui.currentEditor ) )
EditorGui.currentEditor.onEditMenuSelect( %this );
}
//////////////////////////////////////////////////////////////////////////
function EditorMenuEditDelete()
{
if ( isObject( EditorGui.currentEditor ) )
EditorGui.currentEditor.handleDelete();
}
function EditorMenuEditDeselect()
{
if ( isObject( EditorGui.currentEditor ) )
EditorGui.currentEditor.handleDeselect();
}
function EditorMenuEditCut()
{
if ( isObject( EditorGui.currentEditor ) )
EditorGui.currentEditor.handleCut();
}
function EditorMenuEditCopy()
{
if ( isObject( EditorGui.currentEditor ) )
EditorGui.currentEditor.handleCopy();
}
function EditorMenuEditPaste()
{
if ( isObject( EditorGui.currentEditor ) )
EditorGui.currentEditor.handlePaste();
}
//////////////////////////////////////////////////////////////////////////
// Window Menu Handler
//////////////////////////////////////////////////////////////////////////
function EditorToolsMenu::onSelectItem(%this, %id)
{
%toolName = getField( %this.item[%id], 2 );
EditorGui.setEditor(%toolName, %paletteName );
%this.checkRadioItem(0, %this.getItemCount(), %id);
return true;
}
function EditorToolsMenu::setupDefaultState(%this)
{
Parent::setupDefaultState(%this);
}
//////////////////////////////////////////////////////////////////////////
// Camera Menu Handler
//////////////////////////////////////////////////////////////////////////
function EditorCameraMenu::onSelectItem(%this, %id, %text)
{
if(%id == 0 || %id == 1)
{
// Handle the Free Camera/Orbit Camera toggle
%this.checkRadioItem(0, 1, %id);
}
return Parent::onSelectItem(%this, %id, %text);
}
function EditorCameraMenu::setupDefaultState(%this)
{
// Set the Free Camera/Orbit Camera check marks
%this.checkRadioItem(0, 1, 0);
Parent::setupDefaultState(%this);
}
function EditorFreeCameraTypeMenu::onSelectItem(%this, %id, %text)
{
// Handle the camera type radio
%this.checkRadioItem(0, 2, %id);
return Parent::onSelectItem(%this, %id, %text);
}
function EditorFreeCameraTypeMenu::setupDefaultState(%this)
{
// Set the camera type check marks
%this.checkRadioItem(0, 2, 0);
Parent::setupDefaultState(%this);
}
function EditorCameraSpeedMenu::onSelectItem(%this, %id, %text)
{
// Grab and set speed
%speed = getField( %this.item[%id], 2 );
$Camera::movementSpeed = %speed;
// Update Editor
%this.checkRadioItem(0, 6, %id);
// Update Toolbar TextEdit
EWorldEditorCameraSpeed.setText( $Camera::movementSpeed );
// Update Toolbar Slider
CameraSpeedDropdownCtrlContainer-->Slider.setValue( $Camera::movementSpeed );
return true;
}
function EditorCameraSpeedMenu::setupDefaultState(%this)
{
// Setup camera speed gui's. Both menu and editorgui
%this.setupGuiControls();
//Grab and set speed
%defaultSpeed = EditorSettings.value("LevelInformation/levels/" @ EditorGui.levelName @ "/cameraSpeed");
if( %defaultSpeed $= "" )
{
// Update Editor with default speed
%defaultSpeed = 25;
}
$Camera::movementSpeed = %defaultSpeed;
// Update Toolbar TextEdit
EWorldEditorCameraSpeed.setText( %defaultSpeed );
// Update Toolbar Slider
CameraSpeedDropdownCtrlContainer-->Slider.setValue( %defaultSpeed );
Parent::setupDefaultState(%this);
}
function EditorCameraSpeedMenu::setupGuiControls(%this)
{
// Default levelInfo params
%minSpeed = 5;
%maxSpeed = 200;
%speedA = EditorSettings.value("LevelInformation/levels/" @ EditorGui.levelName @ "/cameraSpeedMin");
%speedB = EditorSettings.value("LevelInformation/levels/" @ EditorGui.levelName @ "/cameraSpeedMax");
if( %speedA < %speedB )
{
if( %speedA == 0 )
{
if( %speedB > 1 )
%minSpeed = 1;
else
%minSpeed = 0.1;
}
else
{
%minSpeed = %speedA;
}
%maxSpeed = %speedB;
}
// Set up the camera speed items
%inc = ( (%maxSpeed - %minSpeed) / (%this.getItemCount() - 1) );
for( %i = 0; %i < %this.getItemCount(); %i++)
%this.item[%i] = setField( %this.item[%i], 2, (%minSpeed + (%inc * %i)));
// Set up min/max camera slider range
eval("CameraSpeedDropdownCtrlContainer-->Slider.range = \"" @ %minSpeed @ " " @ %maxSpeed @ "\";");
}
//////////////////////////////////////////////////////////////////////////
// Tools Menu Handler
//////////////////////////////////////////////////////////////////////////
function EditorUtilitiesMenu::onSelectItem(%this, %id, %text)
{
return Parent::onSelectItem(%this, %id, %text);
}
//////////////////////////////////////////////////////////////////////////
// World Menu Handler Object Menu
//////////////////////////////////////////////////////////////////////////
function EditorWorldMenu::onMenuSelect(%this)
{
%selSize = EWorldEditor.getSelectionSize();
%lockCount = EWorldEditor.getSelectionLockCount();
%hideCount = EWorldEditor.getSelectionHiddenCount();
%this.enableItem(0, %lockCount < %selSize); // Lock Selection
%this.enableItem(1, %lockCount > 0); // Unlock Selection
%this.enableItem(3, %hideCount < %selSize); // Hide Selection
%this.enableItem(4, %hideCount > 0); // Show Selection
%this.enableItem(6, %selSize > 1 && %lockCount == 0); // Align bounds
%this.enableItem(7, %selSize > 1 && %lockCount == 0); // Align center
%this.enableItem(9, %selSize > 0 && %lockCount == 0); // Reset Transforms
%this.enableItem(10, %selSize > 0 && %lockCount == 0); // Reset Selected Rotation
%this.enableItem(11, %selSize > 0 && %lockCount == 0); // Reset Selected Scale
%this.enableItem(12, %selSize > 0 && %lockCount == 0); // Transform Selection
%this.enableItem(14, %selSize > 0 && %lockCount == 0); // Drop Selection
%this.enableItem(17, %selSize > 0); // Make Prefab
%this.enableItem(18, %selSize > 0); // Explode Prefab
%this.enableItem(20, %selSize > 1); // Mount
%this.enableItem(21, %selSize > 0); // Unmount
}
//////////////////////////////////////////////////////////////////////////
function EditorDropTypeMenu::onSelectItem(%this, %id, %text)
{
// This sets up which drop script function to use when
// a drop type is selected in the menu.
EWorldEditor.dropType = getField(%this.item[%id], 2);
%this.checkRadioItem(0, (%this.getItemCount() - 1), %id);
return true;
}
function EditorDropTypeMenu::setupDefaultState(%this)
{
// Check the radio item for the currently set drop type.
%numItems = %this.getItemCount();
%dropTypeIndex = 0;
for( ; %dropTypeIndex < %numItems; %dropTypeIndex ++ )
if( getField( %this.item[ %dropTypeIndex ], 2 ) $= EWorldEditor.dropType )
break;
// Default to screenCenter if we didn't match anything.
if( %dropTypeIndex > (%numItems - 1) )
%dropTypeIndex = 4;
%this.checkRadioItem( 0, (%numItems - 1), %dropTypeIndex );
Parent::setupDefaultState(%this);
}
//////////////////////////////////////////////////////////////////////////
function EditorAlignBoundsMenu::onSelectItem(%this, %id, %text)
{
// Have the editor align all selected objects by the selected bounds.
EWorldEditor.alignByBounds(getField(%this.item[%id], 2));
return true;
}
function EditorAlignBoundsMenu::setupDefaultState(%this)
{
// Allow the parent to set the menu's default state
Parent::setupDefaultState(%this);
}
//////////////////////////////////////////////////////////////////////////
function EditorAlignCenterMenu::onSelectItem(%this, %id, %text)
{
// Have the editor align all selected objects by the selected axis.
EWorldEditor.alignByAxis(getField(%this.item[%id], 2));
return true;
}
function EditorAlignCenterMenu::setupDefaultState(%this)
{
// Allow the parent to set the menu's default state
Parent::setupDefaultState(%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;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
namespace MS.Internal.Xml.XPath
{
internal class CompiledXpathExpr : XPathExpression
{
private Query _query;
private string _expr;
private bool _needContext;
internal CompiledXpathExpr(Query query, string expression, bool needContext)
{
_query = query;
_expr = expression;
_needContext = needContext;
}
internal Query QueryTree
{
get
{
if (_needContext)
{
throw XPathException.Create(SR.Xp_NoContext);
}
return _query;
}
}
public override string Expression
{
get { return _expr; }
}
public virtual void CheckErrors()
{
Debug.Assert(_query != null, "In case of error in XPath we create ErrorXPathExpression");
}
public override void AddSort(object expr, IComparer comparer)
{
// sort makes sense only when we are dealing with a query that
// returns a nodeset.
Query evalExpr;
string query = expr as string;
if (query != null)
{
evalExpr = new QueryBuilder().Build(query, out _needContext); // this will throw if expr is invalid
}
else
{
CompiledXpathExpr xpathExpr = expr as CompiledXpathExpr;
if (xpathExpr != null)
{
evalExpr = xpathExpr.QueryTree;
}
else
{
throw XPathException.Create(SR.Xp_BadQueryObject);
}
}
SortQuery sortQuery = _query as SortQuery;
if (sortQuery == null)
{
_query = sortQuery = new SortQuery(_query);
}
sortQuery.AddSort(evalExpr, comparer);
}
public override void AddSort(object expr, XmlSortOrder order, XmlCaseOrder caseOrder, string lang, XmlDataType dataType)
{
AddSort(expr, new XPathComparerHelper(order, caseOrder, lang, dataType));
}
public override XPathExpression Clone()
{
return new CompiledXpathExpr(Query.Clone(_query), _expr, _needContext);
}
public override void SetContext(XmlNamespaceManager nsManager)
{
SetContext((IXmlNamespaceResolver)nsManager);
}
public override void SetContext(IXmlNamespaceResolver nsResolver)
{
XsltContext xsltContext = nsResolver as XsltContext;
if (xsltContext == null)
{
if (nsResolver == null)
{
nsResolver = new XmlNamespaceManager(new NameTable());
}
xsltContext = new UndefinedXsltContext(nsResolver);
}
_query.SetXsltContext(xsltContext);
_needContext = false;
}
public override XPathResultType ReturnType { get { return _query.StaticType; } }
private class UndefinedXsltContext : XsltContext
{
private IXmlNamespaceResolver _nsResolver;
public UndefinedXsltContext(IXmlNamespaceResolver nsResolver)
{
_nsResolver = nsResolver;
}
//----- Namespace support -----
public override string DefaultNamespace
{
get { return string.Empty; }
}
public override string LookupNamespace(string prefix)
{
Debug.Assert(prefix != null);
if (prefix.Length == 0)
{
return string.Empty;
}
string ns = _nsResolver.LookupNamespace(prefix);
if (ns == null)
{
throw XPathException.Create(SR.XmlUndefinedAlias, prefix);
}
return ns;
}
//----- XsltContext support -----
public override IXsltContextVariable ResolveVariable(string prefix, string name)
{
throw XPathException.Create(SR.Xp_UndefinedXsltContext);
}
public override IXsltContextFunction ResolveFunction(string prefix, string name, XPathResultType[] ArgTypes)
{
throw XPathException.Create(SR.Xp_UndefinedXsltContext);
}
public override bool Whitespace { get { return false; } }
public override bool PreserveWhitespace(XPathNavigator node) { return false; }
public override int CompareDocument(string baseUri, string nextbaseUri)
{
return string.CompareOrdinal(baseUri, nextbaseUri);
}
}
}
internal sealed class XPathComparerHelper : IComparer
{
private XmlSortOrder _order;
private XmlCaseOrder _caseOrder;
private CultureInfo _cinfo;
private XmlDataType _dataType;
public XPathComparerHelper(XmlSortOrder order, XmlCaseOrder caseOrder, string lang, XmlDataType dataType)
{
if (lang == null)
{
_cinfo = CultureInfo.CurrentCulture;
}
else
{
try
{
_cinfo = new CultureInfo(lang);
}
catch (System.ArgumentException)
{
throw; // Throwing an XsltException would be a breaking change
}
}
if (order == XmlSortOrder.Descending)
{
if (caseOrder == XmlCaseOrder.LowerFirst)
{
caseOrder = XmlCaseOrder.UpperFirst;
}
else if (caseOrder == XmlCaseOrder.UpperFirst)
{
caseOrder = XmlCaseOrder.LowerFirst;
}
}
_order = order;
_caseOrder = caseOrder;
_dataType = dataType;
}
public int Compare(object x, object y)
{
switch (_dataType)
{
case XmlDataType.Text:
string s1 = Convert.ToString(x, _cinfo);
string s2 = Convert.ToString(y, _cinfo);
int result = _cinfo.CompareInfo.Compare(s1, s2, _caseOrder != XmlCaseOrder.None ? CompareOptions.IgnoreCase : CompareOptions.None);
if (result != 0 || _caseOrder == XmlCaseOrder.None)
return (_order == XmlSortOrder.Ascending) ? result : -result;
// If we came this far, it means that strings s1 and s2 are
// equal to each other when case is ignored. Now it's time to check
// and see if they differ in case only and take into account the user
// requested case order for sorting purposes.
result = _cinfo.CompareInfo.Compare(s1, s2);
return (_caseOrder == XmlCaseOrder.LowerFirst) ? result : -result;
case XmlDataType.Number:
double r1 = XmlConvertEx.ToXPathDouble(x);
double r2 = XmlConvertEx.ToXPathDouble(y);
result = r1.CompareTo(r2);
return (_order == XmlSortOrder.Ascending) ? result : -result;
default:
// dataType doesn't support any other value
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
} // Compare ()
} // class XPathComparerHelper
}
| |
using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Codentia.Common.Net.FTP
{
/// <summary>
/// The FTP Client class, providing the facility to upload and download files via FTP
/// </summary>
public class FTPClient
{
private const int BUFFERSIZE = 512;
private string _remoteHost;
private string _remotePath;
private NetworkCredential _credentials;
private int _port;
private Socket _controlSocket;
private bool _connected;
private IPAddress _connectedToAddress;
private FTPTransferMode _mode;
private byte[] buffer = new byte[BUFFERSIZE];
/// <summary>
/// Initializes a new instance of the <see cref="FTPClient"/> class. (Default constructor)
/// </summary>
/// <remarks>
/// By default the FTPClient class provides a connection on port 21 using ASCII transfers
/// </remarks>
public FTPClient()
{
_port = 21;
_connected = false;
_mode = FTPTransferMode.ASCII;
}
/// <summary>
/// Initializes a new instance of the <see cref="FTPClient"/> class.
/// </summary>
/// <param name="remotePath">The remote path.</param>
/// <param name="mode">The mode.</param>
public FTPClient(string remotePath, FTPTransferMode mode)
: this(ConfigurationManager.AppSettings["DefaultFTPHost"], 21, remotePath, ConfigurationManager.AppSettings["DefaultFTPUser"], ConfigurationManager.AppSettings["DefaultFTPPassword"], mode)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FTPClient"/> class.
/// </summary>
/// <param name="host">The host to connect to</param>
/// <param name="port">The host port to connect to</param>
/// <param name="remotePath">The remote path to connect to on the host</param>
/// <param name="user">The username to use for authentication</param>
/// <param name="password">The password to use for authentication</param>
public FTPClient(string host, int port, string remotePath, string user, string password)
: this()
{
_remoteHost = host;
_port = port;
_remotePath = remotePath;
_credentials = new NetworkCredential(user, password);
}
/// <summary>
/// Initializes a new instance of the <see cref="FTPClient"/> class.
/// </summary>
/// <param name="host">The host to connect to</param>
/// <param name="port">The host port to connect to</param>
/// <param name="remotePath">The remote path to connect to on the host</param>
/// <param name="user">The username to use for authentication</param>
/// <param name="password">The password to use for authentication</param>
/// <param name="mode">The transfer mode to use</param>
public FTPClient(string host, int port, string remotePath, string user, string password, FTPTransferMode mode)
: this(host, port, remotePath, user, password)
{
_mode = mode;
}
/// <summary>
/// Gets a value indicating whether this FTP Client is connected?
/// </summary>
public bool Connected
{
get
{
return _connected;
}
}
/// <summary>
/// Gets or sets the name of the remote host
/// </summary>
/// <remarks>
/// This is read only whilst connected
/// </remarks>
public string RemoteHost
{
get
{
return _remoteHost;
}
set
{
if (this.Connected)
{
throw new FTPException("Cannot change RemoteHost while connected");
}
_remoteHost = value;
}
}
/// <summary>
/// Gets or sets the port to use on the remote host
/// </summary>
/// <remarks>
/// This is read only whilst connected
/// </remarks>
public int Port
{
get
{
return _port;
}
set
{
if (this.Connected)
{
throw new FTPException("Cannot change Port while connected");
}
_port = value;
}
}
/// <summary>
/// Gets or sets the remote path to use on the remote host
/// </summary>
public string RemotePath
{
get
{
return _remotePath;
}
set
{
string safeValue = value.Replace("//", "/");
if (this.Connected)
{
CHDir(safeValue);
}
_remotePath = safeValue;
}
}
/// <summary>
/// Gets or sets the credentials to use
/// </summary>
/// <remarks>
/// This is read only whilst connected
/// </remarks>
public NetworkCredential Credentials
{
get
{
return _credentials;
}
set
{
if (this.Connected)
{
throw new FTPException("Cannot change Credentials while connected");
}
_credentials = value;
}
}
/// <summary>
/// Gets or sets the active transfer mopde
/// </summary>
public FTPTransferMode Mode
{
get
{
return _mode;
}
set
{
_mode = value;
if (this.Connected)
{
FTPResponse response = SendCommand("TYPE " + (_mode == FTPTransferMode.ASCII ? "A" : "I"));
if (response.Code != 200)
{
throw new FTPException(response);
}
}
}
}
/// <summary>
/// Gets the files.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="mask">The mask.</param>
/// <returns>string array</returns>
public string[] GetFiles(string path, string mask)
{
this.RemotePath = path;
return this.GetFiles(mask);
}
/// <summary>
/// Gets the files.
/// </summary>
/// <param name="mask">The mask.</param>
/// <returns>string array</returns>
public string[] GetFiles(string mask)
{
FTPResponse response;
if (!this.Connected)
{
Connect();
}
Socket socket = GetDataSocket();
response = SendCommand("NLST " + mask);
// handle 550 for iis ftp 7.5
if (!(response.Code == 150 || response.Code == 125 || response.Code == 550 || response.Code == 226))
{
throw new FTPException(response);
}
StringBuilder output = new StringBuilder();
while (true && response.Code != 550)
{
int bytes = socket.Receive(buffer, buffer.Length, 0);
output.Append(Encoding.ASCII.GetString(buffer, 0, bytes));
if (bytes < buffer.Length)
{
break;
}
}
string[] lines = output.ToString().Split("\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < lines.Length; i++)
{
lines[i] = lines[i].Trim();
}
socket.Close();
if (response.Code != 550)
{
response = GetResponse();
if (response.Code != 226)
{
throw new FTPException(response);
}
}
return lines;
}
/// <summary>
/// Retrieve the size of a file
/// </summary>
/// <param name="fileName">The URI of the file to obtain the size for</param>
/// <returns>long of the filesize</returns>
public long GetFileSize(string fileName)
{
long size = 0;
if (!this.Connected)
{
Connect();
}
FTPResponse response = SendCommand(string.Format("SIZE {0}", fileName));
if (response.Code == 213)
{
size = long.Parse(response.Message);
}
else
{
throw new FTPException(response);
}
return size;
}
/// <summary>
/// Connect to the remote host
/// </summary>
public void Connect()
{
FTPResponse response;
_controlSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress hostAddress = null;
if (!IPAddress.TryParse(_remoteHost, out hostAddress))
{
hostAddress = Dns.GetHostEntry(_remoteHost).AddressList[0];
}
IPEndPoint endPoint = new IPEndPoint(hostAddress, _port);
try
{
_controlSocket.Connect(endPoint);
}
catch (Exception ex)
{
throw new FTPException("Unable to connect to remote server", ex);
}
_connectedToAddress = hostAddress;
response = GetResponse();
if (response.Code != 220)
{
Close();
throw new FTPException(response);
}
response = SendCommand("USER " + _credentials.UserName);
if (!(response.Code == 331 || response.Code == 230))
{
Close();
throw new FTPException(response);
}
if (response.Code != 230)
{
response = SendCommand("PASS " + _credentials.Password);
if (!(response.Code == 230 || response.Code == 202))
{
Close();
throw new FTPException(response);
}
}
_connected = true;
Console.Out.WriteLine("Connected to " + _remoteHost);
// set transfer mode
this.Mode = _mode;
if (!string.IsNullOrEmpty(_remotePath))
{
CHDir(_remotePath);
}
}
/// <summary>
/// Download a file from the remote host
/// </summary>
/// <param name="remoteFileName">The remote file to download</param>
/// <param name="localFileName">The filename</param>
public void DownloadFile(string remoteFileName, string localFileName)
{
Socket dataSocket;
FileStream outputFile;
FTPResponse response;
if (!this.Connected)
{
Connect();
}
if (string.IsNullOrEmpty(localFileName))
{
throw new FTPException("LocalFileName is required");
}
if (!File.Exists(localFileName))
{
Stream st = File.Create(localFileName);
st.Close();
}
outputFile = File.Create(localFileName);
dataSocket = GetDataSocket();
response = SendCommand("RETR " + remoteFileName);
if (!(response.Code == 150 || response.Code == 125))
{
throw new FTPException(response);
}
int bytes = 0;
byte[] buffer = new byte[BUFFERSIZE];
while (true)
{
bytes = dataSocket.Receive(buffer, buffer.Length, 0);
outputFile.Write(buffer, 0, bytes);
if (bytes <= 0)
{
break;
}
}
outputFile.Close();
outputFile.Dispose();
if (dataSocket.Connected)
{
dataSocket.Close();
}
response = GetResponse();
if (!(response.Code == 226 || response.Code == 250))
{
throw new FTPException(response);
}
}
/// <summary>
/// Upload a file to the remote host
/// </summary>
/// <param name="fileName">The name of the file to upload</param>
public void UploadFile(string fileName)
{
UploadFile(fileName, false);
}
/// <summary>
/// Delete a file on the remote host
/// </summary>
/// <param name="fileName">The name of the file to delete</param>
public void DeleteRemoteFile(string fileName)
{
if (!this.Connected)
{
Connect();
}
FTPResponse response = SendCommand("DELE " + fileName);
if (response.Code != 250)
{
throw new FTPException(response);
}
}
/// <summary>
/// Rename a file on the remote host
/// </summary>
/// <param name="oldFileName">The name of the file to rename</param>
/// <param name="newFileName">The new name to give the remote file</param>
public void RenameRemoteFile(string oldFileName, string newFileName)
{
FTPResponse response;
if (!this.Connected)
{
Connect();
}
response = SendCommand("RNFR " + oldFileName);
if (response.Code != 350)
{
throw new FTPException(response);
}
// known problem
// rnto will not take care of existing file.
// i.e. It will overwrite if newFileName exist
response = SendCommand("RNTO " + newFileName);
if (response.Code != 250)
{
throw new FTPException(response);
}
}
/// <summary>
/// Create a directory on the remote host
/// </summary>
/// <param name="directoryName">The name of the directory to create</param>
public void MKDir(string directoryName)
{
if (!this.Connected)
{
Connect();
}
FTPResponse response = SendCommand("MKD " + directoryName);
if (response.Code != 250 && response.Code != 257)
{
throw new FTPException(response);
}
}
/// <summary>
/// Remove a directory on the remote host
/// </summary>
/// <param name="directoryName">The name of the directory to remove on the remote host</param>
public void RMDir(string directoryName)
{
if (!this.Connected)
{
Connect();
}
FTPResponse response = SendCommand("RMD " + directoryName);
if (response.Code != 250 && response.Code != 257)
{
throw new FTPException(response);
}
}
/// <summary>
/// Close the FTP Connection
/// </summary>
public void Close()
{
if (_controlSocket != null)
{
if (_controlSocket.Connected)
{
SendCommand("QUIT");
_controlSocket.Close();
}
_controlSocket = null;
}
_connected = false;
}
/// <summary>
/// Upload a file to the remote host
/// </summary>
/// <param name="fileName">The name of the file to upload</param>
/// <param name="resumeTransfer">Should interrupted transfers be resumed?</param>
private void UploadFile(string fileName, bool resumeTransfer)
{
Socket dataSocket;
FTPResponse response;
if (!this.Connected)
{
Connect();
}
dataSocket = GetDataSocket();
response = SendCommand("STOR " + Path.GetFileName(fileName));
if (!(response.Code == 125 || response.Code == 150))
{
throw new FTPException(response);
}
// open input stream to read source file
FileStream inputFile = new FileStream(fileName, FileMode.Open);
Console.WriteLine("Uploading file " + fileName + " to " + _remotePath);
int bytes = 0;
byte[] buffer = new byte[BUFFERSIZE];
while ((bytes = inputFile.Read(buffer, 0, buffer.Length)) > 0)
{
dataSocket.Send(buffer, bytes, 0);
}
inputFile.Close();
inputFile.Dispose();
if (dataSocket.Connected)
{
dataSocket.Close();
}
response = GetResponse();
if (!(response.Code == 226 || response.Code == 250))
{
throw new FTPException(response);
}
}
/// <summary>
/// Change the current directory on the remote host
/// </summary>
/// <param name="directoryName">The directory to make current</param>
private void CHDir(string directoryName)
{
if (!directoryName.Equals("."))
{
FTPResponse response = SendCommand("CWD " + directoryName);
if (response.Code != 250)
{
throw new FTPException(response);
}
Console.Out.WriteLine("Current directory is " + _remotePath);
}
}
private FTPResponse SendCommand(string command)
{
byte[] bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r\n", command).ToCharArray());
_controlSocket.Send(bytes);
return GetResponse();
}
private FTPResponse GetResponse()
{
// read response from the socket
byte[] buffer = new byte[BUFFERSIZE];
int bytes = 0;
string message = string.Empty;
while (true)
{
bytes = 0;
try
{
bytes = _controlSocket.Receive(buffer, buffer.Length, 0);
message = string.Format("{0}{1}", message, Encoding.ASCII.GetString(buffer, 0, bytes));
if (bytes < buffer.Length)
{
break;
}
}
catch (Exception)
{
// do nothing, just break
break;
}
}
if (bytes > 0)
{
string[] lines = message.Split('\n');
message = lines.Length > 2 ? lines[lines.Length - 2] : lines[0];
// now interpret it
return message.Substring(3, 1).Equals(" ") ? new FTPResponse(int.Parse(message.Substring(0, 3)), message.Substring(4)) : this.GetResponse();
}
else
{
return new FTPResponse(-1, "Server closed connection");
}
}
private Socket GetDataSocket()
{
FTPResponse response = SendCommand("PASV");
if (response.Code != 227)
{
throw new FTPException(response);
}
int startIndex = response.Message.IndexOf('(');
int endIndex = response.Message.IndexOf(')');
string ipData = response.Message.Substring(startIndex + 1, endIndex - startIndex - 1);
int[] parts = new int[6];
int len = ipData.Length;
int partCount = 0;
string buf = string.Empty;
for (int i = 0; i < len && partCount <= 6; i++)
{
char ch = char.Parse(ipData.Substring(i, 1));
if (char.IsDigit(ch))
{
buf += ch;
}
else
{
if (ch != ',')
{
throw new FTPException(response, "Malformed PASV reply");
}
}
if (ch == ',' || i + 1 == len)
{
parts[partCount++] = int.Parse(buf);
buf = string.Empty;
}
}
string ipAddress = string.Format("{0}.{1}.{2}.{3}", parts[0], parts[1], parts[2], parts[3]);
int port = (parts[4] << 8) + parts[5];
// cope with PASV implementations that send 'same IP' instruction
IPAddress addressToUse = ipAddress == "0.0.0.0" ? _connectedToAddress : IPAddress.Parse(ipAddress);
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint endPoint = new IPEndPoint(addressToUse, port);
try
{
s.Connect(endPoint);
}
catch (Exception ex)
{
throw new FTPException("Unable to connect to remote server", ex);
}
return s;
}
}
}
| |
// 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.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime;
using Internal.Runtime.CompilerServices;
namespace System.Threading
{
//
// Methods for accessing memory with volatile semantics.
//
public static unsafe class Volatile
{
#region Boolean
private struct VolatileBoolean { public volatile Boolean Value; }
public static Boolean Read(ref Boolean location)
{
return Unsafe.As<Boolean, VolatileBoolean>(ref location).Value;
}
public static void Write(ref Boolean location, Boolean value)
{
Unsafe.As<Boolean, VolatileBoolean>(ref location).Value = value;
}
#endregion
#region Byte
private struct VolatileByte { public volatile Byte Value; }
public static Byte Read(ref Byte location)
{
return Unsafe.As<Byte, VolatileByte>(ref location).Value;
}
public static void Write(ref Byte location, Byte value)
{
Unsafe.As<Byte, VolatileByte>(ref location).Value = value;
}
#endregion
#region Double
public static Double Read(ref Double location)
{
Int64 result = Read(ref Unsafe.As<Double, Int64>(ref location));
return *(double*)&result;
}
public static void Write(ref Double location, Double value)
{
Write(ref Unsafe.As<Double, Int64>(ref location), *(Int64*)&value);
}
#endregion
#region Int16
private struct VolatileInt16 { public volatile Int16 Value; }
public static Int16 Read(ref Int16 location)
{
return Unsafe.As<Int16, VolatileInt16>(ref location).Value;
}
public static void Write(ref Int16 location, Int16 value)
{
Unsafe.As<Int16, VolatileInt16>(ref location).Value = value;
}
#endregion
#region Int32
private struct VolatileInt32 { public volatile Int32 Value; }
public static Int32 Read(ref Int32 location)
{
return Unsafe.As<Int32, VolatileInt32>(ref location).Value;
}
public static void Write(ref Int32 location, Int32 value)
{
Unsafe.As<Int32, VolatileInt32>(ref location).Value = value;
}
#endregion
#region Int64
public static Int64 Read(ref Int64 location)
{
#if BIT64
return (Int64)Unsafe.As<Int64, VolatileIntPtr>(ref location).Value;
#else
return Interlocked.CompareExchange(ref location, 0, 0);
#endif
}
public static void Write(ref Int64 location, Int64 value)
{
#if BIT64
Unsafe.As<Int64, VolatileIntPtr>(ref location).Value = (IntPtr)value;
#else
Interlocked.Exchange(ref location, value);
#endif
}
#endregion
#region IntPtr
private struct VolatileIntPtr { public volatile IntPtr Value; }
public static IntPtr Read(ref IntPtr location)
{
return Unsafe.As<IntPtr, VolatileIntPtr>(ref location).Value;
}
public static void Write(ref IntPtr location, IntPtr value)
{
fixed (IntPtr* p = &location)
{
((VolatileIntPtr*)p)->Value = value;
}
}
#endregion
#region SByte
private struct VolatileSByte { public volatile SByte Value; }
[CLSCompliant(false)]
public static SByte Read(ref SByte location)
{
return Unsafe.As<SByte, VolatileSByte>(ref location).Value;
}
[CLSCompliant(false)]
public static void Write(ref SByte location, SByte value)
{
Unsafe.As<SByte, VolatileSByte>(ref location).Value = value;
}
#endregion
#region Single
private struct VolatileSingle { public volatile Single Value; }
public static Single Read(ref Single location)
{
return Unsafe.As<Single, VolatileSingle>(ref location).Value;
}
public static void Write(ref Single location, Single value)
{
Unsafe.As<Single, VolatileSingle>(ref location).Value = value;
}
#endregion
#region UInt16
private struct VolatileUInt16 { public volatile UInt16 Value; }
[CLSCompliant(false)]
public static UInt16 Read(ref UInt16 location)
{
return Unsafe.As<UInt16, VolatileUInt16>(ref location).Value;
}
[CLSCompliant(false)]
public static void Write(ref UInt16 location, UInt16 value)
{
Unsafe.As<UInt16, VolatileUInt16>(ref location).Value = value;
}
#endregion
#region UInt32
private struct VolatileUInt32 { public volatile UInt32 Value; }
[CLSCompliant(false)]
public static UInt32 Read(ref UInt32 location)
{
return Unsafe.As<UInt32, VolatileUInt32>(ref location).Value;
}
[CLSCompliant(false)]
public static void Write(ref UInt32 location, UInt32 value)
{
Unsafe.As<UInt32, VolatileUInt32>(ref location).Value = value;
}
#endregion
#region UInt64
[CLSCompliant(false)]
public static UInt64 Read(ref UInt64 location)
{
return (UInt64)Read(ref Unsafe.As<UInt64, Int64>(ref location));
}
[CLSCompliant(false)]
public static void Write(ref UInt64 location, UInt64 value)
{
Write(ref Unsafe.As<UInt64, Int64>(ref location), (Int64)value);
}
#endregion
#region UIntPtr
private struct VolatileUIntPtr { public volatile UIntPtr Value; }
[CLSCompliant(false)]
public static UIntPtr Read(ref UIntPtr location)
{
return Unsafe.As<UIntPtr, VolatileUIntPtr>(ref location).Value;
}
[CLSCompliant(false)]
public static void Write(ref UIntPtr location, UIntPtr value)
{
Unsafe.As<UIntPtr, VolatileUIntPtr>(ref location).Value = value;
}
#endregion
#region T
private struct VolatileObject { public volatile Object Value; }
public static T Read<T>(ref T location) where T : class
{
return Unsafe.As<T>(Unsafe.As<T, VolatileObject>(ref location).Value);
}
public static void Write<T>(ref T location, T value) where T : class
{
Unsafe.As<T, VolatileObject>(ref location).Value = value;
}
#endregion
}
}
| |
using XenAdmin.Alerts;
using XenAdmin.Network;
using XenAdmin.Commands;
using XenAdmin.Controls;
using XenAdmin.Plugins;
using XenAPI;
using System;
using System.Windows.Forms;
using System.ComponentModel;
namespace XenAdmin
{
partial class MainWindow
{
/// <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)
{
Program.Exiting = true;
XenAdmin.Core.Clip.UnregisterClipboardViewer();
pluginManager.PluginsChanged -= pluginManager_PluginsChanged;
pluginManager.Dispose();
OtherConfigAndTagsWatcher.DeregisterEventHandlers();
ConnectionsManager.History.CollectionChanged -= History_CollectionChanged;
Alert.DeregisterAlertCollectionChanged(XenCenterAlerts_CollectionChanged);
XenAdmin.Core.Updates.DeregisterCollectionChanged(Updates_CollectionChanged);
ConnectionsManager.XenConnections.CollectionChanged -= XenConnection_CollectionChanged;
Properties.Settings.Default.SettingChanging -= new System.Configuration.SettingChangingEventHandler(Default_SettingChanging);
SearchPage.SearchChanged -= SearchPanel_SearchChanged;
if (disposing && (components != null))
{
components.Dispose();
log.Debug("MainWindow disoposing license timer");
if (licenseTimer != null)
licenseTimer.Dispose();
}
log.Debug("Before MainWindow base.Dispose()");
base.Dispose(disposing);
log.Debug("After MainWindow base.Dispose()");
}
#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();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainWindow));
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.navigationPane = new XenAdmin.Controls.MainWindowControls.NavigationPane();
this.TheTabControl = new System.Windows.Forms.TabControl();
this.TabPageHome = new System.Windows.Forms.TabPage();
this.TabPageGeneral = new System.Windows.Forms.TabPage();
this.TabPageBallooning = new System.Windows.Forms.TabPage();
this.TabPageBallooningUpsell = new System.Windows.Forms.TabPage();
this.TabPageConsole = new System.Windows.Forms.TabPage();
this.TabPageStorage = new System.Windows.Forms.TabPage();
this.TabPagePhysicalStorage = new System.Windows.Forms.TabPage();
this.TabPageSR = new System.Windows.Forms.TabPage();
this.TabPageNetwork = new System.Windows.Forms.TabPage();
this.TabPageNICs = new System.Windows.Forms.TabPage();
this.TabPagePeformance = new System.Windows.Forms.TabPage();
this.TabPageHA = new System.Windows.Forms.TabPage();
this.TabPageHAUpsell = new System.Windows.Forms.TabPage();
this.TabPageSnapshots = new System.Windows.Forms.TabPage();
this.snapshotPage = new XenAdmin.TabPages.SnapshotsPage();
this.TabPageWLB = new System.Windows.Forms.TabPage();
this.TabPageWLBUpsell = new System.Windows.Forms.TabPage();
this.TabPageAD = new System.Windows.Forms.TabPage();
this.TabPageGPU = new System.Windows.Forms.TabPage();
this.TabPageSearch = new System.Windows.Forms.TabPage();
this.TabPageDockerProcess = new System.Windows.Forms.TabPage();
this.TabPageDockerDetails = new System.Windows.Forms.TabPage();
this.alertPage = new XenAdmin.TabPages.AlertSummaryPage();
this.updatesPage = new XenAdmin.TabPages.ManageUpdatesPage();
this.eventsPage = new XenAdmin.TabPages.HistoryPage();
this.TitleBackPanel = new XenAdmin.Controls.GradientPanel.GradientPanel();
this.TitleIcon = new System.Windows.Forms.PictureBox();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.toolTipContainer1 = new XenAdmin.Controls.ToolTipContainer();
this.loggedInLabel1 = new XenAdmin.Controls.LoggedInLabel();
this.TitleLabel = new System.Windows.Forms.Label();
this.ToolStrip = new XenAdmin.Controls.ToolStripEx();
this.backButton = new System.Windows.Forms.ToolStripSplitButton();
this.forwardButton = new System.Windows.Forms.ToolStripSplitButton();
this.toolStripSeparator17 = new System.Windows.Forms.ToolStripSeparator();
this.AddServerToolbarButton = new XenAdmin.Commands.CommandToolStripButton();
this.toolStripSeparator11 = new System.Windows.Forms.ToolStripSeparator();
this.AddPoolToolbarButton = new XenAdmin.Commands.CommandToolStripButton();
this.newStorageToolbarButton = new XenAdmin.Commands.CommandToolStripButton();
this.NewVmToolbarButton = new XenAdmin.Commands.CommandToolStripButton();
this.toolStripSeparator12 = new System.Windows.Forms.ToolStripSeparator();
this.shutDownToolStripButton = new XenAdmin.Commands.CommandToolStripButton();
this.powerOnHostToolStripButton = new XenAdmin.Commands.CommandToolStripButton();
this.startVMToolStripButton = new XenAdmin.Commands.CommandToolStripButton();
this.RebootToolbarButton = new XenAdmin.Commands.CommandToolStripButton();
this.resumeToolStripButton = new XenAdmin.Commands.CommandToolStripButton();
this.SuspendToolbarButton = new XenAdmin.Commands.CommandToolStripButton();
this.ForceShutdownToolbarButton = new XenAdmin.Commands.CommandToolStripButton();
this.ForceRebootToolbarButton = new XenAdmin.Commands.CommandToolStripButton();
this.stopContainerToolStripButton = new XenAdmin.Commands.CommandToolStripButton();
this.startContainerToolStripButton = new XenAdmin.Commands.CommandToolStripButton();
this.restartContainerToolStripButton = new XenAdmin.Commands.CommandToolStripButton();
this.resumeContainerToolStripButton = new XenAdmin.Commands.CommandToolStripButton();
this.pauseContainerToolStripButton = new XenAdmin.Commands.CommandToolStripButton();
this.statusToolTip = new System.Windows.Forms.ToolTip(this.components);
this.ToolBarContextMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
this.ShowToolbarMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.FileImportVMToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.importSearchToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator21 = new System.Windows.Forms.ToolStripSeparator();
this.importSettingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exportSettingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator31 = new System.Windows.Forms.ToolStripSeparator();
this.pluginItemsPlaceHolderToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.customTemplatesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.templatesToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.localStorageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.ShowHiddenObjectsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator24 = new System.Windows.Forms.ToolStripSeparator();
this.pluginItemsPlaceHolderToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolbarToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.poolToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.AddPoolToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator();
this.addServerToolStripMenuItem = new XenAdmin.Commands.AddHostToSelectedPoolToolStripMenuItem();
this.removeServerToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.poolReconnectAsToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.disconnectPoolToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator27 = new System.Windows.Forms.ToolStripSeparator();
this.virtualAppliancesToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator30 = new System.Windows.Forms.ToolStripSeparator();
this.highAvailabilityToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.disasterRecoveryToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.drConfigureToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.DrWizardToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.vMProtectionAndRecoveryToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.exportResourceReportPoolToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.wlbReportsToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.wlbDisconnectToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator();
this.changePoolPasswordToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.deleteToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator26 = new System.Windows.Forms.ToolStripSeparator();
this.pluginItemsPlaceHolderToolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem();
this.PoolPropertiesToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.HostMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.AddHostToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripMenuItem11 = new System.Windows.Forms.ToolStripSeparator();
this.RebootHostToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.powerOnToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.ShutdownHostToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.restartToolstackToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.connectDisconnectToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.ReconnectToolStripMenuItem1 = new XenAdmin.Commands.CommandToolStripMenuItem();
this.DisconnectToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.reconnectAsToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.connectAllToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.disconnectAllToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.addServerToPoolMenuItem = new XenAdmin.Commands.AddSelectedHostToPoolToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.backupToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.restoreFromBackupToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator23 = new System.Windows.Forms.ToolStripSeparator();
this.maintenanceModeToolStripMenuItem1 = new XenAdmin.Commands.CommandToolStripMenuItem();
this.RemoveCrashdumpsToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.HostPasswordToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.ChangeRootPasswordToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.forgetSavedPasswordToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator25 = new System.Windows.Forms.ToolStripSeparator();
this.destroyServerToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.removeHostToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator15 = new System.Windows.Forms.ToolStripSeparator();
this.pluginItemsPlaceHolderToolStripMenuItem3 = new System.Windows.Forms.ToolStripMenuItem();
this.ServerPropertiesToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.VMToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.NewVmToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.startShutdownToolStripMenuItem = new XenAdmin.Commands.VMLifeCycleToolStripMenuItem();
this.resumeOnToolStripMenuItem = new XenAdmin.Commands.ResumeVMOnHostToolStripMenuItem();
this.relocateToolStripMenuItem = new XenAdmin.Commands.MigrateVMToolStripMenuItem();
this.startOnHostToolStripMenuItem = new XenAdmin.Commands.StartVMOnHostToolStripMenuItem();
this.toolStripSeparator20 = new System.Windows.Forms.ToolStripSeparator();
this.assignPolicyToolStripMenuItem = new XenAdmin.Commands.AssignGroupToolStripMenuItemVMPP();
this.assignToVirtualApplianceToolStripMenuItem = new XenAdmin.Commands.AssignGroupToolStripMenuItemVM_appliance();
this.toolStripMenuItem9 = new System.Windows.Forms.ToolStripSeparator();
this.copyVMtoSharedStorageMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.MoveVMToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.snapshotToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.convertToTemplateToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.exportToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripMenuItem12 = new System.Windows.Forms.ToolStripSeparator();
this.installToolsToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.sendCtrlAltDelToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.uninstallToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator10 = new System.Windows.Forms.ToolStripSeparator();
this.pluginItemsPlaceHolderToolStripMenuItem4 = new System.Windows.Forms.ToolStripMenuItem();
this.VMPropertiesToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripMenuItem8 = new System.Windows.Forms.ToolStripSeparator();
this.StorageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.AddStorageToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator22 = new System.Windows.Forms.ToolStripSeparator();
this.RepairStorageToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.DefaultSRToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.virtualDisksToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.addVirtualDiskToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.attachVirtualDiskToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.reclaimFreedSpacetripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator19 = new System.Windows.Forms.ToolStripSeparator();
this.DetachStorageToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.ReattachStorageRepositoryToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.ForgetStorageRepositoryToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.DestroyStorageRepositoryToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.ConvertToThinStorageRepositoryToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator18 = new System.Windows.Forms.ToolStripSeparator();
this.pluginItemsPlaceHolderToolStripMenuItem5 = new System.Windows.Forms.ToolStripMenuItem();
this.SRPropertiesToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.templatesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.CreateVmFromTemplateToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.newVMFromTemplateToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.InstantVmToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator29 = new System.Windows.Forms.ToolStripSeparator();
this.exportTemplateToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.duplicateTemplateToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator16 = new System.Windows.Forms.ToolStripSeparator();
this.uninstallTemplateToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator28 = new System.Windows.Forms.ToolStripSeparator();
this.pluginItemsPlaceHolderToolStripMenuItem6 = new System.Windows.Forms.ToolStripMenuItem();
this.templatePropertiesToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.bugToolToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.healthCheckToolStripMenuItem1 = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator14 = new System.Windows.Forms.ToolStripSeparator();
this.LicenseManagerMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator13 = new System.Windows.Forms.ToolStripSeparator();
this.installNewUpdateToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.rollingUpgradeToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.pluginItemsPlaceHolderToolStripMenuItem7 = new System.Windows.Forms.ToolStripMenuItem();
this.preferencesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.windowToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pluginItemsPlaceHolderToolStripMenuItem9 = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpTopicsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpContextMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem15 = new System.Windows.Forms.ToolStripSeparator();
this.viewApplicationLogToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem17 = new System.Windows.Forms.ToolStripSeparator();
this.xenSourceOnTheWebToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.xenCenterPluginsOnlineToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
this.pluginItemsPlaceHolderToolStripMenuItem8 = new System.Windows.Forms.ToolStripMenuItem();
this.aboutXenSourceAdminToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.MainMenuBar = new XenAdmin.Controls.MenuStripEx();
this.securityGroupsToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.MenuPanel = new System.Windows.Forms.Panel();
this.StatusStrip = new System.Windows.Forms.StatusStrip();
this.statusLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.statusProgressBar = new System.Windows.Forms.ToolStripProgressBar();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.TheTabControl.SuspendLayout();
this.TabPageSnapshots.SuspendLayout();
this.TitleBackPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.TitleIcon)).BeginInit();
this.tableLayoutPanel1.SuspendLayout();
this.toolTipContainer1.SuspendLayout();
this.ToolStrip.SuspendLayout();
this.ToolBarContextMenu.SuspendLayout();
this.MainMenuBar.SuspendLayout();
this.MenuPanel.SuspendLayout();
this.StatusStrip.SuspendLayout();
this.SuspendLayout();
//
// splitContainer1
//
this.splitContainer1.BackColor = System.Drawing.SystemColors.Control;
resources.ApplyResources(this.splitContainer1, "splitContainer1");
this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.navigationPane);
resources.ApplyResources(this.splitContainer1.Panel1, "splitContainer1.Panel1");
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.BackColor = System.Drawing.SystemColors.Control;
this.splitContainer1.Panel2.Controls.Add(this.TheTabControl);
this.splitContainer1.Panel2.Controls.Add(this.alertPage);
this.splitContainer1.Panel2.Controls.Add(this.updatesPage);
this.splitContainer1.Panel2.Controls.Add(this.eventsPage);
this.splitContainer1.Panel2.Controls.Add(this.TitleBackPanel);
resources.ApplyResources(this.splitContainer1.Panel2, "splitContainer1.Panel2");
//
// navigationPane
//
resources.ApplyResources(this.navigationPane, "navigationPane");
this.navigationPane.Name = "navigationPane";
this.navigationPane.NavigationModeChanged += new System.Action<XenAdmin.Controls.MainWindowControls.NavigationPane.NavigationMode>(this.navigationPane_NavigationModeChanged);
this.navigationPane.NotificationsSubModeChanged += new System.Action<XenAdmin.Controls.MainWindowControls.NotificationsSubModeItem>(this.navigationPane_NotificationsSubModeChanged);
this.navigationPane.TreeViewSelectionChanged += new System.Action(this.navigationPane_TreeViewSelectionChanged);
this.navigationPane.TreeNodeBeforeSelected += new System.Action(this.navigationPane_TreeNodeBeforeSelected);
this.navigationPane.TreeNodeClicked += new System.Action(this.navigationPane_TreeNodeClicked);
this.navigationPane.TreeNodeRightClicked += new System.Action(this.navigationPane_TreeNodeRightClicked);
this.navigationPane.TreeViewRefreshed += new System.Action(this.navigationPane_TreeViewRefreshed);
this.navigationPane.TreeViewRefreshSuspended += new System.Action(this.navigationPane_TreeViewRefreshSuspended);
this.navigationPane.TreeViewRefreshResumed += new System.Action(this.navigationPane_TreeViewRefreshResumed);
//
// TheTabControl
//
resources.ApplyResources(this.TheTabControl, "TheTabControl");
this.TheTabControl.Controls.Add(this.TabPageHome);
this.TheTabControl.Controls.Add(this.TabPageGeneral);
this.TheTabControl.Controls.Add(this.TabPageBallooning);
this.TheTabControl.Controls.Add(this.TabPageBallooningUpsell);
this.TheTabControl.Controls.Add(this.TabPageConsole);
this.TheTabControl.Controls.Add(this.TabPageStorage);
this.TheTabControl.Controls.Add(this.TabPagePhysicalStorage);
this.TheTabControl.Controls.Add(this.TabPageSR);
this.TheTabControl.Controls.Add(this.TabPageNetwork);
this.TheTabControl.Controls.Add(this.TabPageNICs);
this.TheTabControl.Controls.Add(this.TabPagePeformance);
this.TheTabControl.Controls.Add(this.TabPageHA);
this.TheTabControl.Controls.Add(this.TabPageHAUpsell);
this.TheTabControl.Controls.Add(this.TabPageSnapshots);
this.TheTabControl.Controls.Add(this.TabPageWLB);
this.TheTabControl.Controls.Add(this.TabPageWLBUpsell);
this.TheTabControl.Controls.Add(this.TabPageAD);
this.TheTabControl.Controls.Add(this.TabPageGPU);
this.TheTabControl.Controls.Add(this.TabPageSearch);
this.TheTabControl.Controls.Add(this.TabPageDockerProcess);
this.TheTabControl.Controls.Add(this.TabPageDockerDetails);
this.TheTabControl.Name = "TheTabControl";
this.TheTabControl.SelectedIndex = 4;
//
// TabPageHome
//
resources.ApplyResources(this.TabPageHome, "TabPageHome");
this.TabPageHome.Name = "TabPageHome";
this.TabPageHome.UseVisualStyleBackColor = true;
//
// TabPageGeneral
//
resources.ApplyResources(this.TabPageGeneral, "TabPageGeneral");
this.TabPageGeneral.Name = "TabPageGeneral";
this.TabPageGeneral.UseVisualStyleBackColor = true;
//
// TabPageBallooning
//
resources.ApplyResources(this.TabPageBallooning, "TabPageBallooning");
this.TabPageBallooning.Name = "TabPageBallooning";
this.TabPageBallooning.UseVisualStyleBackColor = true;
//
// TabPageBallooningUpsell
//
resources.ApplyResources(this.TabPageBallooningUpsell, "TabPageBallooningUpsell");
this.TabPageBallooningUpsell.Name = "TabPageBallooningUpsell";
this.TabPageBallooningUpsell.UseVisualStyleBackColor = true;
//
// TabPageConsole
//
resources.ApplyResources(this.TabPageConsole, "TabPageConsole");
this.TabPageConsole.Name = "TabPageConsole";
this.TabPageConsole.UseVisualStyleBackColor = true;
//
// TabPageStorage
//
resources.ApplyResources(this.TabPageStorage, "TabPageStorage");
this.TabPageStorage.Name = "TabPageStorage";
this.TabPageStorage.UseVisualStyleBackColor = true;
//
// TabPagePhysicalStorage
//
resources.ApplyResources(this.TabPagePhysicalStorage, "TabPagePhysicalStorage");
this.TabPagePhysicalStorage.Name = "TabPagePhysicalStorage";
this.TabPagePhysicalStorage.UseVisualStyleBackColor = true;
//
// TabPageSR
//
resources.ApplyResources(this.TabPageSR, "TabPageSR");
this.TabPageSR.Name = "TabPageSR";
this.TabPageSR.UseVisualStyleBackColor = true;
//
// TabPageNetwork
//
resources.ApplyResources(this.TabPageNetwork, "TabPageNetwork");
this.TabPageNetwork.Name = "TabPageNetwork";
this.TabPageNetwork.UseVisualStyleBackColor = true;
//
// TabPageNICs
//
resources.ApplyResources(this.TabPageNICs, "TabPageNICs");
this.TabPageNICs.Name = "TabPageNICs";
this.TabPageNICs.UseVisualStyleBackColor = true;
//
// TabPagePeformance
//
resources.ApplyResources(this.TabPagePeformance, "TabPagePeformance");
this.TabPagePeformance.Name = "TabPagePeformance";
this.TabPagePeformance.UseVisualStyleBackColor = true;
//
// TabPageHA
//
resources.ApplyResources(this.TabPageHA, "TabPageHA");
this.TabPageHA.Name = "TabPageHA";
this.TabPageHA.UseVisualStyleBackColor = true;
//
// TabPageHAUpsell
//
resources.ApplyResources(this.TabPageHAUpsell, "TabPageHAUpsell");
this.TabPageHAUpsell.Name = "TabPageHAUpsell";
this.TabPageHAUpsell.UseVisualStyleBackColor = true;
//
// TabPageSnapshots
//
this.TabPageSnapshots.Controls.Add(this.snapshotPage);
resources.ApplyResources(this.TabPageSnapshots, "TabPageSnapshots");
this.TabPageSnapshots.Name = "TabPageSnapshots";
this.TabPageSnapshots.UseVisualStyleBackColor = true;
//
// snapshotPage
//
resources.ApplyResources(this.snapshotPage, "snapshotPage");
this.snapshotPage.Name = "snapshotPage";
this.snapshotPage.VM = null;
//
// TabPageWLB
//
resources.ApplyResources(this.TabPageWLB, "TabPageWLB");
this.TabPageWLB.Name = "TabPageWLB";
this.TabPageWLB.UseVisualStyleBackColor = true;
//
// TabPageWLBUpsell
//
resources.ApplyResources(this.TabPageWLBUpsell, "TabPageWLBUpsell");
this.TabPageWLBUpsell.Name = "TabPageWLBUpsell";
this.TabPageWLBUpsell.UseVisualStyleBackColor = true;
//
// TabPageAD
//
resources.ApplyResources(this.TabPageAD, "TabPageAD");
this.TabPageAD.Name = "TabPageAD";
this.TabPageAD.UseVisualStyleBackColor = true;
//
// TabPageGPU
//
resources.ApplyResources(this.TabPageGPU, "TabPageGPU");
this.TabPageGPU.Name = "TabPageGPU";
this.TabPageGPU.UseVisualStyleBackColor = true;
//
// TabPageSearch
//
resources.ApplyResources(this.TabPageSearch, "TabPageSearch");
this.TabPageSearch.Name = "TabPageSearch";
this.TabPageSearch.UseVisualStyleBackColor = true;
//
// TabPageDockerProcess
//
resources.ApplyResources(this.TabPageDockerProcess, "TabPageDockerProcess");
this.TabPageDockerProcess.Name = "TabPageDockerProcess";
this.TabPageDockerProcess.UseVisualStyleBackColor = true;
//
// TabPageDockerDetails
//
resources.ApplyResources(this.TabPageDockerDetails, "TabPageDockerDetails");
this.TabPageDockerDetails.Name = "TabPageDockerDetails";
this.TabPageDockerDetails.UseVisualStyleBackColor = true;
//
// alertPage
//
resources.ApplyResources(this.alertPage, "alertPage");
this.alertPage.BackColor = System.Drawing.SystemColors.Window;
this.alertPage.Name = "alertPage";
//
// updatesPage
//
resources.ApplyResources(this.updatesPage, "updatesPage");
this.updatesPage.BackColor = System.Drawing.SystemColors.Window;
this.updatesPage.Name = "updatesPage";
//
// eventsPage
//
resources.ApplyResources(this.eventsPage, "eventsPage");
this.eventsPage.BackColor = System.Drawing.SystemColors.Window;
this.eventsPage.Name = "eventsPage";
//
// TitleBackPanel
//
resources.ApplyResources(this.TitleBackPanel, "TitleBackPanel");
this.TitleBackPanel.BackColor = System.Drawing.Color.Transparent;
this.TitleBackPanel.Controls.Add(this.TitleIcon);
this.TitleBackPanel.Controls.Add(this.tableLayoutPanel1);
this.TitleBackPanel.Name = "TitleBackPanel";
this.TitleBackPanel.Scheme = XenAdmin.Controls.GradientPanel.GradientPanel.Schemes.Title;
//
// TitleIcon
//
resources.ApplyResources(this.TitleIcon, "TitleIcon");
this.TitleIcon.Name = "TitleIcon";
this.TitleIcon.TabStop = false;
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.toolTipContainer1, 2, 0);
this.tableLayoutPanel1.Controls.Add(this.TitleLabel, 0, 0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// toolTipContainer1
//
resources.ApplyResources(this.toolTipContainer1, "toolTipContainer1");
this.toolTipContainer1.Controls.Add(this.loggedInLabel1);
this.toolTipContainer1.Name = "toolTipContainer1";
//
// loggedInLabel1
//
resources.ApplyResources(this.loggedInLabel1, "loggedInLabel1");
this.loggedInLabel1.BackColor = System.Drawing.Color.Transparent;
this.loggedInLabel1.Connection = null;
this.loggedInLabel1.Name = "loggedInLabel1";
//
// TitleLabel
//
resources.ApplyResources(this.TitleLabel, "TitleLabel");
this.TitleLabel.AutoEllipsis = true;
this.TitleLabel.ForeColor = System.Drawing.SystemColors.HighlightText;
this.TitleLabel.Name = "TitleLabel";
this.TitleLabel.UseMnemonic = false;
//
// ToolStrip
//
resources.ApplyResources(this.ToolStrip, "ToolStrip");
this.ToolStrip.ClickThrough = true;
this.ToolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.ToolStrip.ImageScalingSize = new System.Drawing.Size(24, 24);
this.ToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.backButton,
this.forwardButton,
this.toolStripSeparator17,
this.AddServerToolbarButton,
this.toolStripSeparator11,
this.AddPoolToolbarButton,
this.newStorageToolbarButton,
this.NewVmToolbarButton,
this.toolStripSeparator12,
this.shutDownToolStripButton,
this.powerOnHostToolStripButton,
this.startVMToolStripButton,
this.RebootToolbarButton,
this.resumeToolStripButton,
this.SuspendToolbarButton,
this.ForceShutdownToolbarButton,
this.ForceRebootToolbarButton,
this.stopContainerToolStripButton,
this.startContainerToolStripButton,
this.restartContainerToolStripButton,
this.resumeContainerToolStripButton,
this.pauseContainerToolStripButton});
this.ToolStrip.Name = "ToolStrip";
this.ToolStrip.Stretch = true;
this.ToolStrip.TabStop = true;
this.ToolStrip.MouseClick += new System.Windows.Forms.MouseEventHandler(this.MainMenuBar_MouseClick);
//
// backButton
//
this.backButton.Image = global::XenAdmin.Properties.Resources._001_Back_h32bit_24;
resources.ApplyResources(this.backButton, "backButton");
this.backButton.Name = "backButton";
this.backButton.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
this.backButton.ButtonClick += new System.EventHandler(this.backButton_Click);
this.backButton.DropDownOpening += new System.EventHandler(this.backButton_DropDownOpening);
//
// forwardButton
//
this.forwardButton.Image = global::XenAdmin.Properties.Resources._001_Forward_h32bit_24;
resources.ApplyResources(this.forwardButton, "forwardButton");
this.forwardButton.Margin = new System.Windows.Forms.Padding(0, 2, 0, 2);
this.forwardButton.Name = "forwardButton";
this.forwardButton.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
this.forwardButton.ButtonClick += new System.EventHandler(this.forwardButton_Click);
this.forwardButton.DropDownOpening += new System.EventHandler(this.forwardButton_DropDownOpening);
//
// toolStripSeparator17
//
resources.ApplyResources(this.toolStripSeparator17, "toolStripSeparator17");
this.toolStripSeparator17.Margin = new System.Windows.Forms.Padding(2, 0, 7, 0);
this.toolStripSeparator17.Name = "toolStripSeparator17";
this.toolStripSeparator17.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
//
// AddServerToolbarButton
//
this.AddServerToolbarButton.Command = new XenAdmin.Commands.AddHostCommand();
resources.ApplyResources(this.AddServerToolbarButton, "AddServerToolbarButton");
this.AddServerToolbarButton.Image = global::XenAdmin.Properties.Resources._000_AddApplicationServer_h32bit_24;
this.AddServerToolbarButton.Name = "AddServerToolbarButton";
this.AddServerToolbarButton.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
//
// toolStripSeparator11
//
resources.ApplyResources(this.toolStripSeparator11, "toolStripSeparator11");
this.toolStripSeparator11.Margin = new System.Windows.Forms.Padding(2, 0, 7, 0);
this.toolStripSeparator11.Name = "toolStripSeparator11";
this.toolStripSeparator11.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
//
// AddPoolToolbarButton
//
this.AddPoolToolbarButton.Command = new XenAdmin.Commands.NewPoolCommand();
resources.ApplyResources(this.AddPoolToolbarButton, "AddPoolToolbarButton");
this.AddPoolToolbarButton.Image = global::XenAdmin.Properties.Resources._000_PoolNew_h32bit_24;
this.AddPoolToolbarButton.Name = "AddPoolToolbarButton";
this.AddPoolToolbarButton.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
//
// newStorageToolbarButton
//
this.newStorageToolbarButton.Command = new XenAdmin.Commands.NewSRCommand();
resources.ApplyResources(this.newStorageToolbarButton, "newStorageToolbarButton");
this.newStorageToolbarButton.Image = global::XenAdmin.Properties.Resources._000_NewStorage_h32bit_24;
this.newStorageToolbarButton.Name = "newStorageToolbarButton";
this.newStorageToolbarButton.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
//
// NewVmToolbarButton
//
this.NewVmToolbarButton.Command = new XenAdmin.Commands.NewVMCommand();
resources.ApplyResources(this.NewVmToolbarButton, "NewVmToolbarButton");
this.NewVmToolbarButton.Image = global::XenAdmin.Properties.Resources._000_CreateVM_h32bit_24;
this.NewVmToolbarButton.Name = "NewVmToolbarButton";
this.NewVmToolbarButton.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
//
// toolStripSeparator12
//
resources.ApplyResources(this.toolStripSeparator12, "toolStripSeparator12");
this.toolStripSeparator12.Margin = new System.Windows.Forms.Padding(2, 0, 7, 0);
this.toolStripSeparator12.Name = "toolStripSeparator12";
//
// shutDownToolStripButton
//
this.shutDownToolStripButton.Command = new XenAdmin.Commands.ShutDownCommand();
resources.ApplyResources(this.shutDownToolStripButton, "shutDownToolStripButton");
this.shutDownToolStripButton.Name = "shutDownToolStripButton";
//
// powerOnHostToolStripButton
//
this.powerOnHostToolStripButton.Command = new XenAdmin.Commands.PowerOnHostCommand();
resources.ApplyResources(this.powerOnHostToolStripButton, "powerOnHostToolStripButton");
this.powerOnHostToolStripButton.Name = "powerOnHostToolStripButton";
//
// startVMToolStripButton
//
this.startVMToolStripButton.Command = new XenAdmin.Commands.StartVMCommand();
resources.ApplyResources(this.startVMToolStripButton, "startVMToolStripButton");
this.startVMToolStripButton.Name = "startVMToolStripButton";
//
// RebootToolbarButton
//
this.RebootToolbarButton.Command = new XenAdmin.Commands.RebootCommand();
resources.ApplyResources(this.RebootToolbarButton, "RebootToolbarButton");
this.RebootToolbarButton.Name = "RebootToolbarButton";
//
// resumeToolStripButton
//
this.resumeToolStripButton.Command = new XenAdmin.Commands.ResumeVMCommand();
resources.ApplyResources(this.resumeToolStripButton, "resumeToolStripButton");
this.resumeToolStripButton.Image = global::XenAdmin.Properties.Resources._000_Paused_h32bit_24;
this.resumeToolStripButton.Name = "resumeToolStripButton";
//
// SuspendToolbarButton
//
this.SuspendToolbarButton.Command = new XenAdmin.Commands.SuspendVMCommand();
resources.ApplyResources(this.SuspendToolbarButton, "SuspendToolbarButton");
this.SuspendToolbarButton.Image = global::XenAdmin.Properties.Resources._000_Paused_h32bit_24;
this.SuspendToolbarButton.Name = "SuspendToolbarButton";
//
// ForceShutdownToolbarButton
//
this.ForceShutdownToolbarButton.Command = new XenAdmin.Commands.ForceVMShutDownCommand();
resources.ApplyResources(this.ForceShutdownToolbarButton, "ForceShutdownToolbarButton");
this.ForceShutdownToolbarButton.Image = global::XenAdmin.Properties.Resources._001_ForceShutDown_h32bit_24;
this.ForceShutdownToolbarButton.Name = "ForceShutdownToolbarButton";
//
// ForceRebootToolbarButton
//
this.ForceRebootToolbarButton.Command = new XenAdmin.Commands.ForceVMRebootCommand();
resources.ApplyResources(this.ForceRebootToolbarButton, "ForceRebootToolbarButton");
this.ForceRebootToolbarButton.Image = global::XenAdmin.Properties.Resources._001_ForceReboot_h32bit_24;
this.ForceRebootToolbarButton.Name = "ForceRebootToolbarButton";
//
// stopContainerToolStripButton
//
this.stopContainerToolStripButton.Command = new XenAdmin.Commands.StopDockerContainerCommand();
resources.ApplyResources(this.stopContainerToolStripButton, "stopContainerToolStripButton");
this.stopContainerToolStripButton.Image = global::XenAdmin.Properties.Resources._001_ShutDown_h32bit_24;
this.stopContainerToolStripButton.Name = "stopContainerToolStripButton";
//
// startContainerToolStripButton
//
this.startContainerToolStripButton.Command = new XenAdmin.Commands.StartDockerContainerCommand();
resources.ApplyResources(this.startContainerToolStripButton, "startContainerToolStripButton");
this.startContainerToolStripButton.Image = global::XenAdmin.Properties.Resources._001_PowerOn_h32bit_24;
this.startContainerToolStripButton.Name = "startContainerToolStripButton";
//
// restartContainerToolStripButton
//
this.restartContainerToolStripButton.Command = new XenAdmin.Commands.RestartDockerContainerCommand();
resources.ApplyResources(this.restartContainerToolStripButton, "restartContainerToolStripButton");
this.restartContainerToolStripButton.Image = global::XenAdmin.Properties.Resources._001_Reboot_h32bit_24;
this.restartContainerToolStripButton.Name = "restartContainerToolStripButton";
//
// resumeContainerToolStripButton
//
this.resumeContainerToolStripButton.Command = new XenAdmin.Commands.ResumeDockerContainerCommand();
resources.ApplyResources(this.resumeContainerToolStripButton, "resumeContainerToolStripButton");
this.resumeContainerToolStripButton.Image = global::XenAdmin.Properties.Resources._000_Resumed_h32bit_24;
this.resumeContainerToolStripButton.Name = "resumeContainerToolStripButton";
//
// pauseContainerToolStripButton
//
this.pauseContainerToolStripButton.Command = new XenAdmin.Commands.PauseDockerContainerCommand();
resources.ApplyResources(this.pauseContainerToolStripButton, "pauseContainerToolStripButton");
this.pauseContainerToolStripButton.Image = global::XenAdmin.Properties.Resources._000_Paused_h32bit_24;
this.pauseContainerToolStripButton.Name = "pauseContainerToolStripButton";
//
// ToolBarContextMenu
//
this.ToolBarContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ShowToolbarMenuItem});
this.ToolBarContextMenu.Name = "ToolBarContextMenu";
resources.ApplyResources(this.ToolBarContextMenu, "ToolBarContextMenu");
//
// ShowToolbarMenuItem
//
this.ShowToolbarMenuItem.Checked = true;
this.ShowToolbarMenuItem.CheckOnClick = true;
this.ShowToolbarMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;
this.ShowToolbarMenuItem.Name = "ShowToolbarMenuItem";
resources.ApplyResources(this.ShowToolbarMenuItem, "ShowToolbarMenuItem");
this.ShowToolbarMenuItem.Click += new System.EventHandler(this.ShowToolbarMenuItem_Click);
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.FileImportVMToolStripMenuItem,
this.importSearchToolStripMenuItem,
this.toolStripSeparator21,
this.importSettingsToolStripMenuItem,
this.exportSettingsToolStripMenuItem,
this.toolStripSeparator31,
this.pluginItemsPlaceHolderToolStripMenuItem1,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
resources.ApplyResources(this.fileToolStripMenuItem, "fileToolStripMenuItem");
//
// FileImportVMToolStripMenuItem
//
this.FileImportVMToolStripMenuItem.Command = new XenAdmin.Commands.ImportCommand();
this.FileImportVMToolStripMenuItem.Name = "FileImportVMToolStripMenuItem";
resources.ApplyResources(this.FileImportVMToolStripMenuItem, "FileImportVMToolStripMenuItem");
//
// importSearchToolStripMenuItem
//
this.importSearchToolStripMenuItem.Command = new XenAdmin.Commands.ImportSearchCommand();
this.importSearchToolStripMenuItem.Name = "importSearchToolStripMenuItem";
resources.ApplyResources(this.importSearchToolStripMenuItem, "importSearchToolStripMenuItem");
//
// toolStripSeparator21
//
this.toolStripSeparator21.Name = "toolStripSeparator21";
resources.ApplyResources(this.toolStripSeparator21, "toolStripSeparator21");
//
// importSettingsToolStripMenuItem
//
this.importSettingsToolStripMenuItem.Name = "importSettingsToolStripMenuItem";
resources.ApplyResources(this.importSettingsToolStripMenuItem, "importSettingsToolStripMenuItem");
this.importSettingsToolStripMenuItem.Click += new System.EventHandler(this.importSettingsToolStripMenuItem_Click);
//
// exportSettingsToolStripMenuItem
//
this.exportSettingsToolStripMenuItem.Name = "exportSettingsToolStripMenuItem";
resources.ApplyResources(this.exportSettingsToolStripMenuItem, "exportSettingsToolStripMenuItem");
this.exportSettingsToolStripMenuItem.Click += new System.EventHandler(this.exportSettingsToolStripMenuItem_Click);
//
// toolStripSeparator31
//
this.toolStripSeparator31.Name = "toolStripSeparator31";
resources.ApplyResources(this.toolStripSeparator31, "toolStripSeparator31");
//
// pluginItemsPlaceHolderToolStripMenuItem1
//
this.pluginItemsPlaceHolderToolStripMenuItem1.Name = "pluginItemsPlaceHolderToolStripMenuItem1";
resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem1, "pluginItemsPlaceHolderToolStripMenuItem1");
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
resources.ApplyResources(this.exitToolStripMenuItem, "exitToolStripMenuItem");
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// viewToolStripMenuItem
//
this.viewToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.viewToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.customTemplatesToolStripMenuItem,
this.templatesToolStripMenuItem1,
this.localStorageToolStripMenuItem,
this.ShowHiddenObjectsToolStripMenuItem,
this.toolStripSeparator24,
this.pluginItemsPlaceHolderToolStripMenuItem,
this.toolbarToolStripMenuItem});
this.viewToolStripMenuItem.Name = "viewToolStripMenuItem";
resources.ApplyResources(this.viewToolStripMenuItem, "viewToolStripMenuItem");
//
// customTemplatesToolStripMenuItem
//
this.customTemplatesToolStripMenuItem.Name = "customTemplatesToolStripMenuItem";
resources.ApplyResources(this.customTemplatesToolStripMenuItem, "customTemplatesToolStripMenuItem");
this.customTemplatesToolStripMenuItem.Click += new System.EventHandler(this.customTemplatesToolStripMenuItem_Click);
//
// templatesToolStripMenuItem1
//
this.templatesToolStripMenuItem1.Name = "templatesToolStripMenuItem1";
resources.ApplyResources(this.templatesToolStripMenuItem1, "templatesToolStripMenuItem1");
this.templatesToolStripMenuItem1.Click += new System.EventHandler(this.templatesToolStripMenuItem1_Click);
//
// localStorageToolStripMenuItem
//
this.localStorageToolStripMenuItem.Name = "localStorageToolStripMenuItem";
resources.ApplyResources(this.localStorageToolStripMenuItem, "localStorageToolStripMenuItem");
this.localStorageToolStripMenuItem.Click += new System.EventHandler(this.localStorageToolStripMenuItem_Click);
//
// ShowHiddenObjectsToolStripMenuItem
//
this.ShowHiddenObjectsToolStripMenuItem.Name = "ShowHiddenObjectsToolStripMenuItem";
resources.ApplyResources(this.ShowHiddenObjectsToolStripMenuItem, "ShowHiddenObjectsToolStripMenuItem");
this.ShowHiddenObjectsToolStripMenuItem.Click += new System.EventHandler(this.ShowHiddenObjectsToolStripMenuItem_Click);
//
// toolStripSeparator24
//
this.toolStripSeparator24.Name = "toolStripSeparator24";
resources.ApplyResources(this.toolStripSeparator24, "toolStripSeparator24");
//
// pluginItemsPlaceHolderToolStripMenuItem
//
this.pluginItemsPlaceHolderToolStripMenuItem.Name = "pluginItemsPlaceHolderToolStripMenuItem";
resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem, "pluginItemsPlaceHolderToolStripMenuItem");
//
// toolbarToolStripMenuItem
//
this.toolbarToolStripMenuItem.Name = "toolbarToolStripMenuItem";
resources.ApplyResources(this.toolbarToolStripMenuItem, "toolbarToolStripMenuItem");
this.toolbarToolStripMenuItem.Click += new System.EventHandler(this.ShowToolbarMenuItem_Click);
//
// poolToolStripMenuItem
//
this.poolToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.AddPoolToolStripMenuItem,
this.toolStripSeparator8,
this.addServerToolStripMenuItem,
this.removeServerToolStripMenuItem,
this.poolReconnectAsToolStripMenuItem,
this.disconnectPoolToolStripMenuItem,
this.toolStripSeparator27,
this.virtualAppliancesToolStripMenuItem,
this.toolStripSeparator30,
this.highAvailabilityToolStripMenuItem,
this.disasterRecoveryToolStripMenuItem,
this.vMProtectionAndRecoveryToolStripMenuItem,
this.exportResourceReportPoolToolStripMenuItem,
this.wlbReportsToolStripMenuItem,
this.wlbDisconnectToolStripMenuItem,
this.toolStripSeparator9,
this.changePoolPasswordToolStripMenuItem,
this.toolStripMenuItem1,
this.deleteToolStripMenuItem,
this.toolStripSeparator26,
this.pluginItemsPlaceHolderToolStripMenuItem2,
this.PoolPropertiesToolStripMenuItem});
this.poolToolStripMenuItem.Name = "poolToolStripMenuItem";
resources.ApplyResources(this.poolToolStripMenuItem, "poolToolStripMenuItem");
//
// AddPoolToolStripMenuItem
//
this.AddPoolToolStripMenuItem.Command = new XenAdmin.Commands.NewPoolCommand();
this.AddPoolToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._000_PoolNew_h32bit_16;
this.AddPoolToolStripMenuItem.Name = "AddPoolToolStripMenuItem";
resources.ApplyResources(this.AddPoolToolStripMenuItem, "AddPoolToolStripMenuItem");
//
// toolStripSeparator8
//
this.toolStripSeparator8.Name = "toolStripSeparator8";
resources.ApplyResources(this.toolStripSeparator8, "toolStripSeparator8");
//
// addServerToolStripMenuItem
//
this.addServerToolStripMenuItem.Name = "addServerToolStripMenuItem";
resources.ApplyResources(this.addServerToolStripMenuItem, "addServerToolStripMenuItem");
//
// removeServerToolStripMenuItem
//
this.removeServerToolStripMenuItem.Command = new XenAdmin.Commands.RemoveHostFromPoolCommand();
this.removeServerToolStripMenuItem.Name = "removeServerToolStripMenuItem";
resources.ApplyResources(this.removeServerToolStripMenuItem, "removeServerToolStripMenuItem");
//
// poolReconnectAsToolStripMenuItem
//
this.poolReconnectAsToolStripMenuItem.Command = new XenAdmin.Commands.PoolReconnectAsCommand();
this.poolReconnectAsToolStripMenuItem.Name = "poolReconnectAsToolStripMenuItem";
resources.ApplyResources(this.poolReconnectAsToolStripMenuItem, "poolReconnectAsToolStripMenuItem");
//
// disconnectPoolToolStripMenuItem
//
this.disconnectPoolToolStripMenuItem.Command = new XenAdmin.Commands.DisconnectPoolCommand();
this.disconnectPoolToolStripMenuItem.Name = "disconnectPoolToolStripMenuItem";
resources.ApplyResources(this.disconnectPoolToolStripMenuItem, "disconnectPoolToolStripMenuItem");
//
// toolStripSeparator27
//
this.toolStripSeparator27.Name = "toolStripSeparator27";
resources.ApplyResources(this.toolStripSeparator27, "toolStripSeparator27");
//
// virtualAppliancesToolStripMenuItem
//
this.virtualAppliancesToolStripMenuItem.Command = new XenAdmin.Commands.VMGroupCommandVM_appliance();
this.virtualAppliancesToolStripMenuItem.Name = "virtualAppliancesToolStripMenuItem";
resources.ApplyResources(this.virtualAppliancesToolStripMenuItem, "virtualAppliancesToolStripMenuItem");
//
// toolStripSeparator30
//
this.toolStripSeparator30.Name = "toolStripSeparator30";
resources.ApplyResources(this.toolStripSeparator30, "toolStripSeparator30");
//
// highAvailabilityToolStripMenuItem
//
this.highAvailabilityToolStripMenuItem.Command = new XenAdmin.Commands.HACommand();
this.highAvailabilityToolStripMenuItem.Name = "highAvailabilityToolStripMenuItem";
resources.ApplyResources(this.highAvailabilityToolStripMenuItem, "highAvailabilityToolStripMenuItem");
//
// disasterRecoveryToolStripMenuItem
//
this.disasterRecoveryToolStripMenuItem.Command = new XenAdmin.Commands.DRCommand();
this.disasterRecoveryToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.drConfigureToolStripMenuItem,
this.DrWizardToolStripMenuItem});
this.disasterRecoveryToolStripMenuItem.Name = "disasterRecoveryToolStripMenuItem";
resources.ApplyResources(this.disasterRecoveryToolStripMenuItem, "disasterRecoveryToolStripMenuItem");
//
// drConfigureToolStripMenuItem
//
this.drConfigureToolStripMenuItem.Command = new XenAdmin.Commands.DRConfigureCommand();
this.drConfigureToolStripMenuItem.Name = "drConfigureToolStripMenuItem";
resources.ApplyResources(this.drConfigureToolStripMenuItem, "drConfigureToolStripMenuItem");
//
// DrWizardToolStripMenuItem
//
this.DrWizardToolStripMenuItem.Command = new XenAdmin.Commands.DisasterRecoveryCommand();
this.DrWizardToolStripMenuItem.Name = "DrWizardToolStripMenuItem";
resources.ApplyResources(this.DrWizardToolStripMenuItem, "DrWizardToolStripMenuItem");
//
// vMProtectionAndRecoveryToolStripMenuItem
//
this.vMProtectionAndRecoveryToolStripMenuItem.Command = new XenAdmin.Commands.VMGroupCommandVMPP();
this.vMProtectionAndRecoveryToolStripMenuItem.Name = "vMProtectionAndRecoveryToolStripMenuItem";
resources.ApplyResources(this.vMProtectionAndRecoveryToolStripMenuItem, "vMProtectionAndRecoveryToolStripMenuItem");
//
// exportResourceReportPoolToolStripMenuItem
//
this.exportResourceReportPoolToolStripMenuItem.Command = new XenAdmin.Commands.ExportResourceReportCommand();
this.exportResourceReportPoolToolStripMenuItem.Name = "exportResourceReportPoolToolStripMenuItem";
resources.ApplyResources(this.exportResourceReportPoolToolStripMenuItem, "exportResourceReportPoolToolStripMenuItem");
//
// wlbReportsToolStripMenuItem
//
this.wlbReportsToolStripMenuItem.Command = new XenAdmin.Commands.ViewWorkloadReportsCommand();
this.wlbReportsToolStripMenuItem.Name = "wlbReportsToolStripMenuItem";
resources.ApplyResources(this.wlbReportsToolStripMenuItem, "wlbReportsToolStripMenuItem");
//
// wlbDisconnectToolStripMenuItem
//
this.wlbDisconnectToolStripMenuItem.Command = new XenAdmin.Commands.DisconnectWlbServerCommand();
this.wlbDisconnectToolStripMenuItem.Name = "wlbDisconnectToolStripMenuItem";
resources.ApplyResources(this.wlbDisconnectToolStripMenuItem, "wlbDisconnectToolStripMenuItem");
//
// toolStripSeparator9
//
this.toolStripSeparator9.Name = "toolStripSeparator9";
resources.ApplyResources(this.toolStripSeparator9, "toolStripSeparator9");
//
// changePoolPasswordToolStripMenuItem
//
this.changePoolPasswordToolStripMenuItem.Command = new XenAdmin.Commands.ChangeHostPasswordCommand();
this.changePoolPasswordToolStripMenuItem.Name = "changePoolPasswordToolStripMenuItem";
resources.ApplyResources(this.changePoolPasswordToolStripMenuItem, "changePoolPasswordToolStripMenuItem");
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
resources.ApplyResources(this.toolStripMenuItem1, "toolStripMenuItem1");
//
// deleteToolStripMenuItem
//
this.deleteToolStripMenuItem.Command = new XenAdmin.Commands.DeletePoolCommand();
this.deleteToolStripMenuItem.Name = "deleteToolStripMenuItem";
resources.ApplyResources(this.deleteToolStripMenuItem, "deleteToolStripMenuItem");
//
// toolStripSeparator26
//
this.toolStripSeparator26.Name = "toolStripSeparator26";
resources.ApplyResources(this.toolStripSeparator26, "toolStripSeparator26");
//
// pluginItemsPlaceHolderToolStripMenuItem2
//
this.pluginItemsPlaceHolderToolStripMenuItem2.Name = "pluginItemsPlaceHolderToolStripMenuItem2";
resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem2, "pluginItemsPlaceHolderToolStripMenuItem2");
//
// PoolPropertiesToolStripMenuItem
//
this.PoolPropertiesToolStripMenuItem.Command = new XenAdmin.Commands.PoolPropertiesCommand();
this.PoolPropertiesToolStripMenuItem.Image = global::XenAdmin.Properties.Resources.edit_16;
this.PoolPropertiesToolStripMenuItem.Name = "PoolPropertiesToolStripMenuItem";
resources.ApplyResources(this.PoolPropertiesToolStripMenuItem, "PoolPropertiesToolStripMenuItem");
//
// HostMenuItem
//
this.HostMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.AddHostToolStripMenuItem,
this.toolStripMenuItem11,
this.RebootHostToolStripMenuItem,
this.powerOnToolStripMenuItem,
this.ShutdownHostToolStripMenuItem,
this.restartToolstackToolStripMenuItem,
this.toolStripSeparator1,
this.connectDisconnectToolStripMenuItem,
this.addServerToPoolMenuItem,
this.toolStripSeparator3,
this.backupToolStripMenuItem,
this.restoreFromBackupToolStripMenuItem,
this.toolStripSeparator23,
this.maintenanceModeToolStripMenuItem1,
this.RemoveCrashdumpsToolStripMenuItem,
this.HostPasswordToolStripMenuItem,
this.toolStripSeparator25,
this.destroyServerToolStripMenuItem,
this.removeHostToolStripMenuItem,
this.toolStripSeparator15,
this.pluginItemsPlaceHolderToolStripMenuItem3,
this.ServerPropertiesToolStripMenuItem});
this.HostMenuItem.Name = "HostMenuItem";
resources.ApplyResources(this.HostMenuItem, "HostMenuItem");
//
// AddHostToolStripMenuItem
//
this.AddHostToolStripMenuItem.Command = new XenAdmin.Commands.AddHostCommand();
this.AddHostToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._000_AddApplicationServer_h32bit_16;
this.AddHostToolStripMenuItem.Name = "AddHostToolStripMenuItem";
resources.ApplyResources(this.AddHostToolStripMenuItem, "AddHostToolStripMenuItem");
//
// toolStripMenuItem11
//
this.toolStripMenuItem11.Name = "toolStripMenuItem11";
resources.ApplyResources(this.toolStripMenuItem11, "toolStripMenuItem11");
//
// RebootHostToolStripMenuItem
//
this.RebootHostToolStripMenuItem.Command = new XenAdmin.Commands.RebootHostCommand();
this.RebootHostToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._001_Reboot_h32bit_16;
this.RebootHostToolStripMenuItem.Name = "RebootHostToolStripMenuItem";
resources.ApplyResources(this.RebootHostToolStripMenuItem, "RebootHostToolStripMenuItem");
//
// powerOnToolStripMenuItem
//
this.powerOnToolStripMenuItem.Command = new XenAdmin.Commands.PowerOnHostCommand();
resources.ApplyResources(this.powerOnToolStripMenuItem, "powerOnToolStripMenuItem");
this.powerOnToolStripMenuItem.Name = "powerOnToolStripMenuItem";
//
// ShutdownHostToolStripMenuItem
//
this.ShutdownHostToolStripMenuItem.Command = new XenAdmin.Commands.ShutDownHostCommand();
resources.ApplyResources(this.ShutdownHostToolStripMenuItem, "ShutdownHostToolStripMenuItem");
this.ShutdownHostToolStripMenuItem.Name = "ShutdownHostToolStripMenuItem";
//
// restartToolstackToolStripMenuItem
//
this.restartToolstackToolStripMenuItem.Command = new XenAdmin.Commands.RestartToolstackCommand();
this.restartToolstackToolStripMenuItem.Name = "restartToolstackToolStripMenuItem";
resources.ApplyResources(this.restartToolstackToolStripMenuItem, "restartToolstackToolStripMenuItem");
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1");
//
// connectDisconnectToolStripMenuItem
//
this.connectDisconnectToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ReconnectToolStripMenuItem1,
this.DisconnectToolStripMenuItem,
this.reconnectAsToolStripMenuItem,
this.toolStripSeparator4,
this.connectAllToolStripMenuItem,
this.disconnectAllToolStripMenuItem});
this.connectDisconnectToolStripMenuItem.Name = "connectDisconnectToolStripMenuItem";
resources.ApplyResources(this.connectDisconnectToolStripMenuItem, "connectDisconnectToolStripMenuItem");
//
// ReconnectToolStripMenuItem1
//
this.ReconnectToolStripMenuItem1.Command = new XenAdmin.Commands.ReconnectHostCommand();
this.ReconnectToolStripMenuItem1.Name = "ReconnectToolStripMenuItem1";
resources.ApplyResources(this.ReconnectToolStripMenuItem1, "ReconnectToolStripMenuItem1");
//
// DisconnectToolStripMenuItem
//
this.DisconnectToolStripMenuItem.Command = new XenAdmin.Commands.DisconnectHostCommand();
this.DisconnectToolStripMenuItem.Name = "DisconnectToolStripMenuItem";
resources.ApplyResources(this.DisconnectToolStripMenuItem, "DisconnectToolStripMenuItem");
//
// reconnectAsToolStripMenuItem
//
this.reconnectAsToolStripMenuItem.Command = new XenAdmin.Commands.HostReconnectAsCommand();
this.reconnectAsToolStripMenuItem.Name = "reconnectAsToolStripMenuItem";
resources.ApplyResources(this.reconnectAsToolStripMenuItem, "reconnectAsToolStripMenuItem");
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
resources.ApplyResources(this.toolStripSeparator4, "toolStripSeparator4");
//
// connectAllToolStripMenuItem
//
this.connectAllToolStripMenuItem.Command = new XenAdmin.Commands.ConnectAllHostsCommand();
this.connectAllToolStripMenuItem.Name = "connectAllToolStripMenuItem";
resources.ApplyResources(this.connectAllToolStripMenuItem, "connectAllToolStripMenuItem");
//
// disconnectAllToolStripMenuItem
//
this.disconnectAllToolStripMenuItem.Command = new XenAdmin.Commands.DisconnectAllHostsCommand();
this.disconnectAllToolStripMenuItem.Name = "disconnectAllToolStripMenuItem";
resources.ApplyResources(this.disconnectAllToolStripMenuItem, "disconnectAllToolStripMenuItem");
//
// addServerToPoolMenuItem
//
this.addServerToPoolMenuItem.Name = "addServerToPoolMenuItem";
resources.ApplyResources(this.addServerToPoolMenuItem, "addServerToPoolMenuItem");
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
resources.ApplyResources(this.toolStripSeparator3, "toolStripSeparator3");
//
// backupToolStripMenuItem
//
this.backupToolStripMenuItem.Command = new XenAdmin.Commands.BackupHostCommand();
this.backupToolStripMenuItem.Name = "backupToolStripMenuItem";
resources.ApplyResources(this.backupToolStripMenuItem, "backupToolStripMenuItem");
//
// restoreFromBackupToolStripMenuItem
//
this.restoreFromBackupToolStripMenuItem.Command = new XenAdmin.Commands.RestoreHostFromBackupCommand();
this.restoreFromBackupToolStripMenuItem.Name = "restoreFromBackupToolStripMenuItem";
resources.ApplyResources(this.restoreFromBackupToolStripMenuItem, "restoreFromBackupToolStripMenuItem");
//
// toolStripSeparator23
//
this.toolStripSeparator23.Name = "toolStripSeparator23";
resources.ApplyResources(this.toolStripSeparator23, "toolStripSeparator23");
//
// maintenanceModeToolStripMenuItem1
//
this.maintenanceModeToolStripMenuItem1.Command = new XenAdmin.Commands.HostMaintenanceModeCommand();
this.maintenanceModeToolStripMenuItem1.Name = "maintenanceModeToolStripMenuItem1";
resources.ApplyResources(this.maintenanceModeToolStripMenuItem1, "maintenanceModeToolStripMenuItem1");
//
// RemoveCrashdumpsToolStripMenuItem
//
this.RemoveCrashdumpsToolStripMenuItem.Command = new XenAdmin.Commands.RemoveHostCrashDumpsCommand();
this.RemoveCrashdumpsToolStripMenuItem.Name = "RemoveCrashdumpsToolStripMenuItem";
resources.ApplyResources(this.RemoveCrashdumpsToolStripMenuItem, "RemoveCrashdumpsToolStripMenuItem");
//
// HostPasswordToolStripMenuItem
//
this.HostPasswordToolStripMenuItem.Command = new XenAdmin.Commands.HostPasswordCommand();
this.HostPasswordToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ChangeRootPasswordToolStripMenuItem,
this.forgetSavedPasswordToolStripMenuItem});
this.HostPasswordToolStripMenuItem.Name = "HostPasswordToolStripMenuItem";
resources.ApplyResources(this.HostPasswordToolStripMenuItem, "HostPasswordToolStripMenuItem");
//
// ChangeRootPasswordToolStripMenuItem
//
this.ChangeRootPasswordToolStripMenuItem.Command = new XenAdmin.Commands.ChangeHostPasswordCommand();
this.ChangeRootPasswordToolStripMenuItem.Name = "ChangeRootPasswordToolStripMenuItem";
resources.ApplyResources(this.ChangeRootPasswordToolStripMenuItem, "ChangeRootPasswordToolStripMenuItem");
//
// forgetSavedPasswordToolStripMenuItem
//
this.forgetSavedPasswordToolStripMenuItem.Command = new XenAdmin.Commands.ForgetSavedPasswordCommand();
this.forgetSavedPasswordToolStripMenuItem.Name = "forgetSavedPasswordToolStripMenuItem";
resources.ApplyResources(this.forgetSavedPasswordToolStripMenuItem, "forgetSavedPasswordToolStripMenuItem");
//
// toolStripSeparator25
//
this.toolStripSeparator25.Name = "toolStripSeparator25";
resources.ApplyResources(this.toolStripSeparator25, "toolStripSeparator25");
//
// destroyServerToolStripMenuItem
//
this.destroyServerToolStripMenuItem.Command = new XenAdmin.Commands.DestroyHostCommand();
this.destroyServerToolStripMenuItem.Name = "destroyServerToolStripMenuItem";
resources.ApplyResources(this.destroyServerToolStripMenuItem, "destroyServerToolStripMenuItem");
//
// removeHostToolStripMenuItem
//
this.removeHostToolStripMenuItem.Command = new XenAdmin.Commands.RemoveHostCommand();
this.removeHostToolStripMenuItem.Name = "removeHostToolStripMenuItem";
resources.ApplyResources(this.removeHostToolStripMenuItem, "removeHostToolStripMenuItem");
//
// toolStripSeparator15
//
this.toolStripSeparator15.Name = "toolStripSeparator15";
resources.ApplyResources(this.toolStripSeparator15, "toolStripSeparator15");
//
// pluginItemsPlaceHolderToolStripMenuItem3
//
this.pluginItemsPlaceHolderToolStripMenuItem3.Name = "pluginItemsPlaceHolderToolStripMenuItem3";
resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem3, "pluginItemsPlaceHolderToolStripMenuItem3");
//
// ServerPropertiesToolStripMenuItem
//
this.ServerPropertiesToolStripMenuItem.Command = new XenAdmin.Commands.HostPropertiesCommand();
this.ServerPropertiesToolStripMenuItem.Image = global::XenAdmin.Properties.Resources.edit_16;
this.ServerPropertiesToolStripMenuItem.Name = "ServerPropertiesToolStripMenuItem";
resources.ApplyResources(this.ServerPropertiesToolStripMenuItem, "ServerPropertiesToolStripMenuItem");
//
// VMToolStripMenuItem
//
this.VMToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.NewVmToolStripMenuItem,
this.startShutdownToolStripMenuItem,
this.resumeOnToolStripMenuItem,
this.relocateToolStripMenuItem,
this.startOnHostToolStripMenuItem,
this.toolStripSeparator20,
this.assignPolicyToolStripMenuItem,
this.assignToVirtualApplianceToolStripMenuItem,
this.toolStripMenuItem9,
this.copyVMtoSharedStorageMenuItem,
this.MoveVMToolStripMenuItem,
this.snapshotToolStripMenuItem,
this.convertToTemplateToolStripMenuItem,
this.exportToolStripMenuItem,
this.toolStripMenuItem12,
this.installToolsToolStripMenuItem,
this.sendCtrlAltDelToolStripMenuItem,
this.toolStripSeparator5,
this.uninstallToolStripMenuItem,
this.toolStripSeparator10,
this.pluginItemsPlaceHolderToolStripMenuItem4,
this.VMPropertiesToolStripMenuItem});
this.VMToolStripMenuItem.Name = "VMToolStripMenuItem";
resources.ApplyResources(this.VMToolStripMenuItem, "VMToolStripMenuItem");
//
// NewVmToolStripMenuItem
//
this.NewVmToolStripMenuItem.Command = new XenAdmin.Commands.NewVMCommand();
this.NewVmToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._001_CreateVM_h32bit_16;
this.NewVmToolStripMenuItem.Name = "NewVmToolStripMenuItem";
resources.ApplyResources(this.NewVmToolStripMenuItem, "NewVmToolStripMenuItem");
//
// startShutdownToolStripMenuItem
//
this.startShutdownToolStripMenuItem.Name = "startShutdownToolStripMenuItem";
resources.ApplyResources(this.startShutdownToolStripMenuItem, "startShutdownToolStripMenuItem");
//
// resumeOnToolStripMenuItem
//
this.resumeOnToolStripMenuItem.Name = "resumeOnToolStripMenuItem";
resources.ApplyResources(this.resumeOnToolStripMenuItem, "resumeOnToolStripMenuItem");
//
// relocateToolStripMenuItem
//
this.relocateToolStripMenuItem.Name = "relocateToolStripMenuItem";
resources.ApplyResources(this.relocateToolStripMenuItem, "relocateToolStripMenuItem");
//
// startOnHostToolStripMenuItem
//
this.startOnHostToolStripMenuItem.Name = "startOnHostToolStripMenuItem";
resources.ApplyResources(this.startOnHostToolStripMenuItem, "startOnHostToolStripMenuItem");
//
// toolStripSeparator20
//
this.toolStripSeparator20.Name = "toolStripSeparator20";
resources.ApplyResources(this.toolStripSeparator20, "toolStripSeparator20");
//
// assignPolicyToolStripMenuItem
//
this.assignPolicyToolStripMenuItem.Name = "assignPolicyToolStripMenuItem";
resources.ApplyResources(this.assignPolicyToolStripMenuItem, "assignPolicyToolStripMenuItem");
//
// assignToVirtualApplianceToolStripMenuItem
//
this.assignToVirtualApplianceToolStripMenuItem.Name = "assignToVirtualApplianceToolStripMenuItem";
resources.ApplyResources(this.assignToVirtualApplianceToolStripMenuItem, "assignToVirtualApplianceToolStripMenuItem");
//
// toolStripMenuItem9
//
this.toolStripMenuItem9.Name = "toolStripMenuItem9";
resources.ApplyResources(this.toolStripMenuItem9, "toolStripMenuItem9");
//
// copyVMtoSharedStorageMenuItem
//
this.copyVMtoSharedStorageMenuItem.Command = new XenAdmin.Commands.CopyVMCommand();
this.copyVMtoSharedStorageMenuItem.Name = "copyVMtoSharedStorageMenuItem";
resources.ApplyResources(this.copyVMtoSharedStorageMenuItem, "copyVMtoSharedStorageMenuItem");
//
// MoveVMToolStripMenuItem
//
this.MoveVMToolStripMenuItem.Command = new XenAdmin.Commands.MoveVMCommand();
this.MoveVMToolStripMenuItem.Name = "MoveVMToolStripMenuItem";
resources.ApplyResources(this.MoveVMToolStripMenuItem, "MoveVMToolStripMenuItem");
//
// snapshotToolStripMenuItem
//
this.snapshotToolStripMenuItem.Command = new XenAdmin.Commands.TakeSnapshotCommand();
this.snapshotToolStripMenuItem.Name = "snapshotToolStripMenuItem";
resources.ApplyResources(this.snapshotToolStripMenuItem, "snapshotToolStripMenuItem");
//
// convertToTemplateToolStripMenuItem
//
this.convertToTemplateToolStripMenuItem.Command = new XenAdmin.Commands.ConvertVMToTemplateCommand();
this.convertToTemplateToolStripMenuItem.Name = "convertToTemplateToolStripMenuItem";
resources.ApplyResources(this.convertToTemplateToolStripMenuItem, "convertToTemplateToolStripMenuItem");
//
// exportToolStripMenuItem
//
this.exportToolStripMenuItem.Command = new XenAdmin.Commands.ExportCommand();
this.exportToolStripMenuItem.Name = "exportToolStripMenuItem";
resources.ApplyResources(this.exportToolStripMenuItem, "exportToolStripMenuItem");
//
// toolStripMenuItem12
//
this.toolStripMenuItem12.Name = "toolStripMenuItem12";
resources.ApplyResources(this.toolStripMenuItem12, "toolStripMenuItem12");
//
// installToolsToolStripMenuItem
//
this.installToolsToolStripMenuItem.Command = new XenAdmin.Commands.InstallToolsCommand();
this.installToolsToolStripMenuItem.Name = "installToolsToolStripMenuItem";
resources.ApplyResources(this.installToolsToolStripMenuItem, "installToolsToolStripMenuItem");
//
// sendCtrlAltDelToolStripMenuItem
//
this.sendCtrlAltDelToolStripMenuItem.Name = "sendCtrlAltDelToolStripMenuItem";
resources.ApplyResources(this.sendCtrlAltDelToolStripMenuItem, "sendCtrlAltDelToolStripMenuItem");
this.sendCtrlAltDelToolStripMenuItem.Click += new System.EventHandler(this.sendCtrlAltDelToolStripMenuItem_Click);
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
resources.ApplyResources(this.toolStripSeparator5, "toolStripSeparator5");
//
// uninstallToolStripMenuItem
//
this.uninstallToolStripMenuItem.Command = new XenAdmin.Commands.DeleteVMCommand();
this.uninstallToolStripMenuItem.Name = "uninstallToolStripMenuItem";
resources.ApplyResources(this.uninstallToolStripMenuItem, "uninstallToolStripMenuItem");
//
// toolStripSeparator10
//
this.toolStripSeparator10.Name = "toolStripSeparator10";
resources.ApplyResources(this.toolStripSeparator10, "toolStripSeparator10");
//
// pluginItemsPlaceHolderToolStripMenuItem4
//
this.pluginItemsPlaceHolderToolStripMenuItem4.Name = "pluginItemsPlaceHolderToolStripMenuItem4";
resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem4, "pluginItemsPlaceHolderToolStripMenuItem4");
//
// VMPropertiesToolStripMenuItem
//
this.VMPropertiesToolStripMenuItem.Command = new XenAdmin.Commands.VMPropertiesCommand();
this.VMPropertiesToolStripMenuItem.Image = global::XenAdmin.Properties.Resources.edit_16;
this.VMPropertiesToolStripMenuItem.Name = "VMPropertiesToolStripMenuItem";
resources.ApplyResources(this.VMPropertiesToolStripMenuItem, "VMPropertiesToolStripMenuItem");
//
// toolStripMenuItem8
//
this.toolStripMenuItem8.Name = "toolStripMenuItem8";
resources.ApplyResources(this.toolStripMenuItem8, "toolStripMenuItem8");
//
// StorageToolStripMenuItem
//
this.StorageToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.AddStorageToolStripMenuItem,
this.toolStripSeparator22,
this.RepairStorageToolStripMenuItem,
this.DefaultSRToolStripMenuItem,
this.toolStripSeparator2,
this.virtualDisksToolStripMenuItem,
this.reclaimFreedSpacetripMenuItem,
this.toolStripSeparator19,
this.DetachStorageToolStripMenuItem,
this.ReattachStorageRepositoryToolStripMenuItem,
this.ForgetStorageRepositoryToolStripMenuItem,
this.DestroyStorageRepositoryToolStripMenuItem,
this.ConvertToThinStorageRepositoryToolStripMenuItem,
this.toolStripSeparator18,
this.pluginItemsPlaceHolderToolStripMenuItem5,
this.SRPropertiesToolStripMenuItem});
this.StorageToolStripMenuItem.Name = "StorageToolStripMenuItem";
resources.ApplyResources(this.StorageToolStripMenuItem, "StorageToolStripMenuItem");
//
// AddStorageToolStripMenuItem
//
this.AddStorageToolStripMenuItem.Command = new XenAdmin.Commands.NewSRCommand();
this.AddStorageToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._000_NewStorage_h32bit_16;
this.AddStorageToolStripMenuItem.Name = "AddStorageToolStripMenuItem";
resources.ApplyResources(this.AddStorageToolStripMenuItem, "AddStorageToolStripMenuItem");
//
// toolStripSeparator22
//
this.toolStripSeparator22.Name = "toolStripSeparator22";
resources.ApplyResources(this.toolStripSeparator22, "toolStripSeparator22");
//
// RepairStorageToolStripMenuItem
//
this.RepairStorageToolStripMenuItem.Command = new XenAdmin.Commands.RepairSRCommand();
this.RepairStorageToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._000_StorageBroken_h32bit_16;
this.RepairStorageToolStripMenuItem.Name = "RepairStorageToolStripMenuItem";
resources.ApplyResources(this.RepairStorageToolStripMenuItem, "RepairStorageToolStripMenuItem");
//
// DefaultSRToolStripMenuItem
//
this.DefaultSRToolStripMenuItem.Command = new XenAdmin.Commands.SetAsDefaultSRCommand();
this.DefaultSRToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._000_StorageDefault_h32bit_16;
this.DefaultSRToolStripMenuItem.Name = "DefaultSRToolStripMenuItem";
resources.ApplyResources(this.DefaultSRToolStripMenuItem, "DefaultSRToolStripMenuItem");
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
resources.ApplyResources(this.toolStripSeparator2, "toolStripSeparator2");
//
// virtualDisksToolStripMenuItem
//
this.virtualDisksToolStripMenuItem.Command = new XenAdmin.Commands.VirtualDiskCommand();
this.virtualDisksToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.addVirtualDiskToolStripMenuItem,
this.attachVirtualDiskToolStripMenuItem});
this.virtualDisksToolStripMenuItem.Name = "virtualDisksToolStripMenuItem";
resources.ApplyResources(this.virtualDisksToolStripMenuItem, "virtualDisksToolStripMenuItem");
//
// addVirtualDiskToolStripMenuItem
//
this.addVirtualDiskToolStripMenuItem.Command = new XenAdmin.Commands.AddVirtualDiskCommand();
this.addVirtualDiskToolStripMenuItem.Name = "addVirtualDiskToolStripMenuItem";
resources.ApplyResources(this.addVirtualDiskToolStripMenuItem, "addVirtualDiskToolStripMenuItem");
//
// attachVirtualDiskToolStripMenuItem
//
this.attachVirtualDiskToolStripMenuItem.Command = new XenAdmin.Commands.AttachVirtualDiskCommand();
this.attachVirtualDiskToolStripMenuItem.Name = "attachVirtualDiskToolStripMenuItem";
resources.ApplyResources(this.attachVirtualDiskToolStripMenuItem, "attachVirtualDiskToolStripMenuItem");
//
// reclaimFreedSpacetripMenuItem
//
this.reclaimFreedSpacetripMenuItem.Command = new XenAdmin.Commands.TrimSRCommand();
this.reclaimFreedSpacetripMenuItem.Name = "reclaimFreedSpacetripMenuItem";
resources.ApplyResources(this.reclaimFreedSpacetripMenuItem, "reclaimFreedSpacetripMenuItem");
//
// toolStripSeparator19
//
this.toolStripSeparator19.Name = "toolStripSeparator19";
resources.ApplyResources(this.toolStripSeparator19, "toolStripSeparator19");
//
// DetachStorageToolStripMenuItem
//
this.DetachStorageToolStripMenuItem.Command = new XenAdmin.Commands.DetachSRCommand();
this.DetachStorageToolStripMenuItem.Name = "DetachStorageToolStripMenuItem";
resources.ApplyResources(this.DetachStorageToolStripMenuItem, "DetachStorageToolStripMenuItem");
//
// ReattachStorageRepositoryToolStripMenuItem
//
this.ReattachStorageRepositoryToolStripMenuItem.Command = new XenAdmin.Commands.ReattachSRCommand();
this.ReattachStorageRepositoryToolStripMenuItem.Name = "ReattachStorageRepositoryToolStripMenuItem";
resources.ApplyResources(this.ReattachStorageRepositoryToolStripMenuItem, "ReattachStorageRepositoryToolStripMenuItem");
//
// ForgetStorageRepositoryToolStripMenuItem
//
this.ForgetStorageRepositoryToolStripMenuItem.Command = new XenAdmin.Commands.ForgetSRCommand();
this.ForgetStorageRepositoryToolStripMenuItem.Name = "ForgetStorageRepositoryToolStripMenuItem";
resources.ApplyResources(this.ForgetStorageRepositoryToolStripMenuItem, "ForgetStorageRepositoryToolStripMenuItem");
//
// DestroyStorageRepositoryToolStripMenuItem
//
this.DestroyStorageRepositoryToolStripMenuItem.Command = new XenAdmin.Commands.DestroySRCommand();
this.DestroyStorageRepositoryToolStripMenuItem.Name = "DestroyStorageRepositoryToolStripMenuItem";
resources.ApplyResources(this.DestroyStorageRepositoryToolStripMenuItem, "DestroyStorageRepositoryToolStripMenuItem");
//
// ConvertToThinStorageRepositoryToolStripMenuItem
//
this.ConvertToThinStorageRepositoryToolStripMenuItem.Command = new XenAdmin.Commands.ConvertToThinSRCommand();
this.ConvertToThinStorageRepositoryToolStripMenuItem.Name = "ConvertToThinStorageRepositoryToolStripMenuItem";
resources.ApplyResources(this.ConvertToThinStorageRepositoryToolStripMenuItem, "ConvertToThinStorageRepositoryToolStripMenuItem");
//
// toolStripSeparator18
//
this.toolStripSeparator18.Name = "toolStripSeparator18";
resources.ApplyResources(this.toolStripSeparator18, "toolStripSeparator18");
//
// pluginItemsPlaceHolderToolStripMenuItem5
//
this.pluginItemsPlaceHolderToolStripMenuItem5.Name = "pluginItemsPlaceHolderToolStripMenuItem5";
resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem5, "pluginItemsPlaceHolderToolStripMenuItem5");
//
// SRPropertiesToolStripMenuItem
//
this.SRPropertiesToolStripMenuItem.Command = new XenAdmin.Commands.SRPropertiesCommand();
this.SRPropertiesToolStripMenuItem.Image = global::XenAdmin.Properties.Resources.edit_16;
this.SRPropertiesToolStripMenuItem.Name = "SRPropertiesToolStripMenuItem";
resources.ApplyResources(this.SRPropertiesToolStripMenuItem, "SRPropertiesToolStripMenuItem");
//
// templatesToolStripMenuItem
//
this.templatesToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.CreateVmFromTemplateToolStripMenuItem,
this.toolStripSeparator29,
this.exportTemplateToolStripMenuItem,
this.duplicateTemplateToolStripMenuItem,
this.toolStripSeparator16,
this.uninstallTemplateToolStripMenuItem,
this.toolStripSeparator28,
this.pluginItemsPlaceHolderToolStripMenuItem6,
this.templatePropertiesToolStripMenuItem});
this.templatesToolStripMenuItem.Name = "templatesToolStripMenuItem";
resources.ApplyResources(this.templatesToolStripMenuItem, "templatesToolStripMenuItem");
//
// CreateVmFromTemplateToolStripMenuItem
//
this.CreateVmFromTemplateToolStripMenuItem.Command = new XenAdmin.Commands.CreateVMFromTemplateCommand();
this.CreateVmFromTemplateToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newVMFromTemplateToolStripMenuItem,
this.InstantVmToolStripMenuItem});
this.CreateVmFromTemplateToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._001_CreateVM_h32bit_16;
this.CreateVmFromTemplateToolStripMenuItem.Name = "CreateVmFromTemplateToolStripMenuItem";
resources.ApplyResources(this.CreateVmFromTemplateToolStripMenuItem, "CreateVmFromTemplateToolStripMenuItem");
//
// newVMFromTemplateToolStripMenuItem
//
this.newVMFromTemplateToolStripMenuItem.Command = new XenAdmin.Commands.NewVMFromTemplateCommand();
this.newVMFromTemplateToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._001_CreateVM_h32bit_16;
this.newVMFromTemplateToolStripMenuItem.Name = "newVMFromTemplateToolStripMenuItem";
resources.ApplyResources(this.newVMFromTemplateToolStripMenuItem, "newVMFromTemplateToolStripMenuItem");
//
// InstantVmToolStripMenuItem
//
this.InstantVmToolStripMenuItem.Command = new XenAdmin.Commands.InstantVMFromTemplateCommand();
this.InstantVmToolStripMenuItem.Name = "InstantVmToolStripMenuItem";
resources.ApplyResources(this.InstantVmToolStripMenuItem, "InstantVmToolStripMenuItem");
//
// toolStripSeparator29
//
this.toolStripSeparator29.Name = "toolStripSeparator29";
resources.ApplyResources(this.toolStripSeparator29, "toolStripSeparator29");
//
// exportTemplateToolStripMenuItem
//
this.exportTemplateToolStripMenuItem.Command = new XenAdmin.Commands.ExportTemplateCommand();
this.exportTemplateToolStripMenuItem.Name = "exportTemplateToolStripMenuItem";
resources.ApplyResources(this.exportTemplateToolStripMenuItem, "exportTemplateToolStripMenuItem");
//
// duplicateTemplateToolStripMenuItem
//
this.duplicateTemplateToolStripMenuItem.Command = new XenAdmin.Commands.CopyTemplateCommand();
this.duplicateTemplateToolStripMenuItem.Name = "duplicateTemplateToolStripMenuItem";
resources.ApplyResources(this.duplicateTemplateToolStripMenuItem, "duplicateTemplateToolStripMenuItem");
//
// toolStripSeparator16
//
this.toolStripSeparator16.Name = "toolStripSeparator16";
resources.ApplyResources(this.toolStripSeparator16, "toolStripSeparator16");
//
// uninstallTemplateToolStripMenuItem
//
this.uninstallTemplateToolStripMenuItem.Command = new XenAdmin.Commands.DeleteTemplateCommand();
this.uninstallTemplateToolStripMenuItem.Name = "uninstallTemplateToolStripMenuItem";
resources.ApplyResources(this.uninstallTemplateToolStripMenuItem, "uninstallTemplateToolStripMenuItem");
//
// toolStripSeparator28
//
this.toolStripSeparator28.Name = "toolStripSeparator28";
resources.ApplyResources(this.toolStripSeparator28, "toolStripSeparator28");
//
// pluginItemsPlaceHolderToolStripMenuItem6
//
this.pluginItemsPlaceHolderToolStripMenuItem6.Name = "pluginItemsPlaceHolderToolStripMenuItem6";
resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem6, "pluginItemsPlaceHolderToolStripMenuItem6");
//
// templatePropertiesToolStripMenuItem
//
this.templatePropertiesToolStripMenuItem.Command = new XenAdmin.Commands.TemplatePropertiesCommand();
this.templatePropertiesToolStripMenuItem.Image = global::XenAdmin.Properties.Resources.edit_16;
this.templatePropertiesToolStripMenuItem.Name = "templatePropertiesToolStripMenuItem";
resources.ApplyResources(this.templatePropertiesToolStripMenuItem, "templatePropertiesToolStripMenuItem");
//
// toolsToolStripMenuItem
//
this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.bugToolToolStripMenuItem,
this.healthCheckToolStripMenuItem1,
this.toolStripSeparator14,
this.LicenseManagerMenuItem,
this.toolStripSeparator13,
this.installNewUpdateToolStripMenuItem,
this.rollingUpgradeToolStripMenuItem,
this.toolStripSeparator6,
this.pluginItemsPlaceHolderToolStripMenuItem7,
this.preferencesToolStripMenuItem});
this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem";
resources.ApplyResources(this.toolsToolStripMenuItem, "toolsToolStripMenuItem");
//
// bugToolToolStripMenuItem
//
this.bugToolToolStripMenuItem.Command = new XenAdmin.Commands.BugToolCommand();
this.bugToolToolStripMenuItem.Name = "bugToolToolStripMenuItem";
resources.ApplyResources(this.bugToolToolStripMenuItem, "bugToolToolStripMenuItem");
//
// healthCheckToolStripMenuItem1
//
this.healthCheckToolStripMenuItem1.Command = new XenAdmin.Commands.HealthCheckCommand();
this.healthCheckToolStripMenuItem1.Name = "healthCheckToolStripMenuItem1";
resources.ApplyResources(this.healthCheckToolStripMenuItem1, "healthCheckToolStripMenuItem1");
//
// toolStripSeparator14
//
this.toolStripSeparator14.Name = "toolStripSeparator14";
resources.ApplyResources(this.toolStripSeparator14, "toolStripSeparator14");
//
// LicenseManagerMenuItem
//
this.LicenseManagerMenuItem.Name = "LicenseManagerMenuItem";
resources.ApplyResources(this.LicenseManagerMenuItem, "LicenseManagerMenuItem");
this.LicenseManagerMenuItem.Click += new System.EventHandler(this.LicenseManagerMenuItem_Click);
//
// toolStripSeparator13
//
this.toolStripSeparator13.Name = "toolStripSeparator13";
resources.ApplyResources(this.toolStripSeparator13, "toolStripSeparator13");
//
// installNewUpdateToolStripMenuItem
//
this.installNewUpdateToolStripMenuItem.Command = new XenAdmin.Commands.InstallNewUpdateCommand();
this.installNewUpdateToolStripMenuItem.Name = "installNewUpdateToolStripMenuItem";
resources.ApplyResources(this.installNewUpdateToolStripMenuItem, "installNewUpdateToolStripMenuItem");
//
// rollingUpgradeToolStripMenuItem
//
this.rollingUpgradeToolStripMenuItem.Command = new XenAdmin.Commands.RollingUpgradeCommand();
this.rollingUpgradeToolStripMenuItem.Name = "rollingUpgradeToolStripMenuItem";
resources.ApplyResources(this.rollingUpgradeToolStripMenuItem, "rollingUpgradeToolStripMenuItem");
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
resources.ApplyResources(this.toolStripSeparator6, "toolStripSeparator6");
//
// pluginItemsPlaceHolderToolStripMenuItem7
//
this.pluginItemsPlaceHolderToolStripMenuItem7.Name = "pluginItemsPlaceHolderToolStripMenuItem7";
resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem7, "pluginItemsPlaceHolderToolStripMenuItem7");
//
// preferencesToolStripMenuItem
//
this.preferencesToolStripMenuItem.Name = "preferencesToolStripMenuItem";
resources.ApplyResources(this.preferencesToolStripMenuItem, "preferencesToolStripMenuItem");
this.preferencesToolStripMenuItem.Click += new System.EventHandler(this.preferencesToolStripMenuItem_Click);
//
// windowToolStripMenuItem
//
this.windowToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.pluginItemsPlaceHolderToolStripMenuItem9});
this.windowToolStripMenuItem.Name = "windowToolStripMenuItem";
resources.ApplyResources(this.windowToolStripMenuItem, "windowToolStripMenuItem");
//
// pluginItemsPlaceHolderToolStripMenuItem9
//
this.pluginItemsPlaceHolderToolStripMenuItem9.Name = "pluginItemsPlaceHolderToolStripMenuItem9";
resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem9, "pluginItemsPlaceHolderToolStripMenuItem9");
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.helpTopicsToolStripMenuItem,
this.helpContextMenuItem,
this.toolStripMenuItem15,
this.viewApplicationLogToolStripMenuItem,
this.toolStripMenuItem17,
this.xenSourceOnTheWebToolStripMenuItem,
this.xenCenterPluginsOnlineToolStripMenuItem,
this.toolStripSeparator7,
this.pluginItemsPlaceHolderToolStripMenuItem8,
this.aboutXenSourceAdminToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
resources.ApplyResources(this.helpToolStripMenuItem, "helpToolStripMenuItem");
//
// helpTopicsToolStripMenuItem
//
this.helpTopicsToolStripMenuItem.Name = "helpTopicsToolStripMenuItem";
resources.ApplyResources(this.helpTopicsToolStripMenuItem, "helpTopicsToolStripMenuItem");
this.helpTopicsToolStripMenuItem.Click += new System.EventHandler(this.helpTopicsToolStripMenuItem_Click);
//
// helpContextMenuItem
//
this.helpContextMenuItem.Image = global::XenAdmin.Properties.Resources._000_HelpIM_h32bit_16;
this.helpContextMenuItem.Name = "helpContextMenuItem";
resources.ApplyResources(this.helpContextMenuItem, "helpContextMenuItem");
this.helpContextMenuItem.Click += new System.EventHandler(this.helpContextMenuItem_Click);
//
// toolStripMenuItem15
//
this.toolStripMenuItem15.Name = "toolStripMenuItem15";
resources.ApplyResources(this.toolStripMenuItem15, "toolStripMenuItem15");
//
// viewApplicationLogToolStripMenuItem
//
this.viewApplicationLogToolStripMenuItem.Name = "viewApplicationLogToolStripMenuItem";
resources.ApplyResources(this.viewApplicationLogToolStripMenuItem, "viewApplicationLogToolStripMenuItem");
this.viewApplicationLogToolStripMenuItem.Click += new System.EventHandler(this.viewApplicationLogToolStripMenuItem_Click);
//
// toolStripMenuItem17
//
this.toolStripMenuItem17.Name = "toolStripMenuItem17";
resources.ApplyResources(this.toolStripMenuItem17, "toolStripMenuItem17");
//
// xenSourceOnTheWebToolStripMenuItem
//
this.xenSourceOnTheWebToolStripMenuItem.Name = "xenSourceOnTheWebToolStripMenuItem";
resources.ApplyResources(this.xenSourceOnTheWebToolStripMenuItem, "xenSourceOnTheWebToolStripMenuItem");
this.xenSourceOnTheWebToolStripMenuItem.Click += new System.EventHandler(this.xenSourceOnTheWebToolStripMenuItem_Click);
//
// xenCenterPluginsOnlineToolStripMenuItem
//
this.xenCenterPluginsOnlineToolStripMenuItem.Name = "xenCenterPluginsOnlineToolStripMenuItem";
resources.ApplyResources(this.xenCenterPluginsOnlineToolStripMenuItem, "xenCenterPluginsOnlineToolStripMenuItem");
this.xenCenterPluginsOnlineToolStripMenuItem.Click += new System.EventHandler(this.xenCenterPluginsOnTheWebToolStripMenuItem_Click);
//
// toolStripSeparator7
//
this.toolStripSeparator7.Name = "toolStripSeparator7";
resources.ApplyResources(this.toolStripSeparator7, "toolStripSeparator7");
//
// pluginItemsPlaceHolderToolStripMenuItem8
//
this.pluginItemsPlaceHolderToolStripMenuItem8.Name = "pluginItemsPlaceHolderToolStripMenuItem8";
resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem8, "pluginItemsPlaceHolderToolStripMenuItem8");
//
// aboutXenSourceAdminToolStripMenuItem
//
this.aboutXenSourceAdminToolStripMenuItem.Name = "aboutXenSourceAdminToolStripMenuItem";
resources.ApplyResources(this.aboutXenSourceAdminToolStripMenuItem, "aboutXenSourceAdminToolStripMenuItem");
this.aboutXenSourceAdminToolStripMenuItem.Click += new System.EventHandler(this.aboutXenSourceAdminToolStripMenuItem_Click);
//
// MainMenuBar
//
resources.ApplyResources(this.MainMenuBar, "MainMenuBar");
this.MainMenuBar.ClickThrough = true;
this.MainMenuBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.viewToolStripMenuItem,
this.poolToolStripMenuItem,
this.HostMenuItem,
this.VMToolStripMenuItem,
this.StorageToolStripMenuItem,
this.templatesToolStripMenuItem,
this.toolsToolStripMenuItem,
this.windowToolStripMenuItem,
this.helpToolStripMenuItem});
this.MainMenuBar.Name = "MainMenuBar";
this.MainMenuBar.MenuActivate += new System.EventHandler(this.MainMenuBar_MenuActivate);
this.MainMenuBar.MouseClick += new System.Windows.Forms.MouseEventHandler(this.MainMenuBar_MouseClick);
//
// securityGroupsToolStripMenuItem
//
this.securityGroupsToolStripMenuItem.Name = "securityGroupsToolStripMenuItem";
resources.ApplyResources(this.securityGroupsToolStripMenuItem, "securityGroupsToolStripMenuItem");
//
// MenuPanel
//
this.MenuPanel.Controls.Add(this.MainMenuBar);
resources.ApplyResources(this.MenuPanel, "MenuPanel");
this.MenuPanel.Name = "MenuPanel";
//
// StatusStrip
//
resources.ApplyResources(this.StatusStrip, "StatusStrip");
this.StatusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.statusLabel,
this.statusProgressBar});
this.StatusStrip.Name = "StatusStrip";
this.StatusStrip.ShowItemToolTips = true;
//
// statusLabel
//
this.statusLabel.AutoToolTip = true;
resources.ApplyResources(this.statusLabel, "statusLabel");
this.statusLabel.Name = "statusLabel";
this.statusLabel.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
this.statusLabel.Spring = true;
//
// statusProgressBar
//
resources.ApplyResources(this.statusProgressBar, "statusProgressBar");
this.statusProgressBar.Margin = new System.Windows.Forms.Padding(5);
this.statusProgressBar.Name = "statusProgressBar";
this.statusProgressBar.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
//
// MainWindow
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.Controls.Add(this.splitContainer1);
this.Controls.Add(this.ToolStrip);
this.Controls.Add(this.MenuPanel);
this.Controls.Add(this.StatusStrip);
this.DoubleBuffered = true;
this.KeyPreview = true;
this.MainMenuStrip = this.MainMenuBar;
this.Name = "MainWindow";
this.Load += new System.EventHandler(this.MainWindow_Load);
this.Shown += new System.EventHandler(this.MainWindow_Shown);
this.HelpRequested += new System.Windows.Forms.HelpEventHandler(this.MainWindow_HelpRequested);
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.MainWindow_KeyDown);
this.Resize += new System.EventHandler(this.MainWindow_Resize);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
this.splitContainer1.ResumeLayout(false);
this.TheTabControl.ResumeLayout(false);
this.TabPageSnapshots.ResumeLayout(false);
this.TitleBackPanel.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.TitleIcon)).EndInit();
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.toolTipContainer1.ResumeLayout(false);
this.toolTipContainer1.PerformLayout();
this.ToolStrip.ResumeLayout(false);
this.ToolStrip.PerformLayout();
this.ToolBarContextMenu.ResumeLayout(false);
this.MainMenuBar.ResumeLayout(false);
this.MainMenuBar.PerformLayout();
this.MenuPanel.ResumeLayout(false);
this.StatusStrip.ResumeLayout(false);
this.StatusStrip.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.SplitContainer splitContainer1;
private XenAdmin.Controls.ToolStripEx ToolStrip;
private CommandToolStripButton NewVmToolbarButton;
private CommandToolStripButton AddServerToolbarButton;
private CommandToolStripButton RebootToolbarButton;
private CommandToolStripButton SuspendToolbarButton;
private CommandToolStripButton ForceRebootToolbarButton;
private CommandToolStripButton ForceShutdownToolbarButton;
private System.Windows.Forms.ToolTip statusToolTip;
private CommandToolStripButton AddPoolToolbarButton;
private CommandToolStripButton newStorageToolbarButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator11;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator12;
private System.Windows.Forms.Label TitleLabel;
private System.Windows.Forms.PictureBox TitleIcon;
private XenAdmin.Controls.GradientPanel.GradientPanel TitleBackPanel;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator17;
internal System.Windows.Forms.ToolStripSplitButton backButton;
internal System.Windows.Forms.ToolStripSplitButton forwardButton;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.ContextMenuStrip ToolBarContextMenu;
private System.Windows.Forms.ToolStripMenuItem ShowToolbarMenuItem;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private CommandToolStripMenuItem FileImportVMToolStripMenuItem;
private CommandToolStripMenuItem importSearchToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator21;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem poolToolStripMenuItem;
private CommandToolStripMenuItem AddPoolToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator8;
private CommandToolStripMenuItem PoolPropertiesToolStripMenuItem;
private CommandToolStripMenuItem highAvailabilityToolStripMenuItem;
private CommandToolStripMenuItem wlbReportsToolStripMenuItem;
private CommandToolStripMenuItem wlbDisconnectToolStripMenuItem;
private AddHostToSelectedPoolToolStripMenuItem addServerToolStripMenuItem;
private CommandToolStripMenuItem removeServerToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator9;
private CommandToolStripMenuItem deleteToolStripMenuItem;
private CommandToolStripMenuItem disconnectPoolToolStripMenuItem;
private CommandToolStripMenuItem exportResourceReportPoolToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem HostMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem11;
private CommandToolStripMenuItem ServerPropertiesToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator15;
private CommandToolStripMenuItem RebootHostToolStripMenuItem;
private CommandToolStripMenuItem ShutdownHostToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private CommandToolStripMenuItem AddHostToolStripMenuItem;
private CommandToolStripMenuItem removeHostToolStripMenuItem;
private AddSelectedHostToPoolToolStripMenuItem addServerToPoolMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private CommandToolStripMenuItem RemoveCrashdumpsToolStripMenuItem;
private CommandToolStripMenuItem maintenanceModeToolStripMenuItem1;
private CommandToolStripMenuItem backupToolStripMenuItem;
private CommandToolStripMenuItem restoreFromBackupToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem VMToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator10;
private CommandToolStripMenuItem VMPropertiesToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator20;
private CommandToolStripMenuItem snapshotToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem9;
private CommandToolStripMenuItem copyVMtoSharedStorageMenuItem;
private CommandToolStripMenuItem exportToolStripMenuItem;
private CommandToolStripMenuItem convertToTemplateToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem12;
private CommandToolStripMenuItem installToolsToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private CommandToolStripMenuItem uninstallToolStripMenuItem;
internal System.Windows.Forms.ToolStripMenuItem StorageToolStripMenuItem;
private CommandToolStripMenuItem AddStorageToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator18;
private CommandToolStripMenuItem SRPropertiesToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator22;
private CommandToolStripMenuItem RepairStorageToolStripMenuItem;
private CommandToolStripMenuItem DefaultSRToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator19;
private CommandToolStripMenuItem DetachStorageToolStripMenuItem;
private CommandToolStripMenuItem ReattachStorageRepositoryToolStripMenuItem;
private CommandToolStripMenuItem ForgetStorageRepositoryToolStripMenuItem;
private CommandToolStripMenuItem DestroyStorageRepositoryToolStripMenuItem;
private CommandToolStripMenuItem ConvertToThinStorageRepositoryToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem templatesToolStripMenuItem;
private CommandToolStripMenuItem exportTemplateToolStripMenuItem;
private CommandToolStripMenuItem duplicateTemplateToolStripMenuItem;
private CommandToolStripMenuItem uninstallTemplateToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem;
private CommandToolStripMenuItem bugToolToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator14;
private System.Windows.Forms.ToolStripMenuItem LicenseManagerMenuItem;
private CommandToolStripMenuItem installNewUpdateToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripMenuItem preferencesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem windowToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpTopicsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpContextMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem15;
private System.Windows.Forms.ToolStripMenuItem viewApplicationLogToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem17;
private System.Windows.Forms.ToolStripMenuItem xenSourceOnTheWebToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripMenuItem aboutXenSourceAdminToolStripMenuItem;
private XenAdmin.Controls.MenuStripEx MainMenuBar;
private System.Windows.Forms.Panel MenuPanel;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator13;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator24;
private System.Windows.Forms.ToolStripMenuItem toolbarToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem ShowHiddenObjectsToolStripMenuItem;
internal System.Windows.Forms.TabControl TheTabControl;
private System.Windows.Forms.TabPage TabPageHome;
internal System.Windows.Forms.TabPage TabPageSearch;
internal System.Windows.Forms.TabPage TabPageGeneral;
private System.Windows.Forms.TabPage TabPageBallooning;
internal System.Windows.Forms.TabPage TabPageConsole;
private System.Windows.Forms.TabPage TabPageStorage;
private System.Windows.Forms.TabPage TabPagePhysicalStorage;
private System.Windows.Forms.TabPage TabPageSR;
private System.Windows.Forms.TabPage TabPageNetwork;
private System.Windows.Forms.TabPage TabPageNICs;
private System.Windows.Forms.TabPage TabPagePeformance;
private System.Windows.Forms.TabPage TabPageHA;
private System.Windows.Forms.TabPage TabPageHAUpsell;
internal System.Windows.Forms.TabPage TabPageWLB;
private System.Windows.Forms.TabPage TabPageWLBUpsell;
private System.Windows.Forms.TabPage TabPageSnapshots;
private System.Windows.Forms.TabPage TabPageDockerProcess;
internal System.Windows.Forms.TabPage TabPageDockerDetails;
private XenAdmin.TabPages.SnapshotsPage snapshotPage;
private System.Windows.Forms.ToolStripMenuItem connectDisconnectToolStripMenuItem;
private CommandToolStripMenuItem connectAllToolStripMenuItem;
private CommandToolStripMenuItem DisconnectToolStripMenuItem;
private CommandToolStripMenuItem disconnectAllToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem sendCtrlAltDelToolStripMenuItem;
private CommandToolStripMenuItem virtualDisksToolStripMenuItem;
private CommandToolStripMenuItem addVirtualDiskToolStripMenuItem;
private CommandToolStripMenuItem attachVirtualDiskToolStripMenuItem;
private CommandToolStripMenuItem NewVmToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator26;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator27;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator23;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator25;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator28;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator16;
private CommandToolStripMenuItem templatePropertiesToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator29;
private VMLifeCycleToolStripMenuItem startShutdownToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem8;
private CommandToolStripMenuItem ReconnectToolStripMenuItem1;
private XenAdmin.Controls.ToolTipContainer toolTipContainer1;
private XenAdmin.Controls.LoggedInLabel loggedInLabel1;
private CommandToolStripMenuItem reconnectAsToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private CommandToolStripMenuItem poolReconnectAsToolStripMenuItem;
internal System.Windows.Forms.TabPage TabPageAD;
private System.Windows.Forms.TabPage TabPageGPU;
private CommandToolStripMenuItem powerOnToolStripMenuItem;
private CommandToolStripButton shutDownToolStripButton;
private CommandToolStripButton startVMToolStripButton;
private CommandToolStripButton powerOnHostToolStripButton;
private CommandToolStripButton resumeToolStripButton;
private MigrateVMToolStripMenuItem relocateToolStripMenuItem;
private StartVMOnHostToolStripMenuItem startOnHostToolStripMenuItem;
private ResumeVMOnHostToolStripMenuItem resumeOnToolStripMenuItem;
private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem1;
private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem;
private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem2;
private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem3;
private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem4;
private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem5;
private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem6;
private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem7;
private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem9;
private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem8;
private TabPage TabPageBallooningUpsell;
private ToolStripMenuItem xenCenterPluginsOnlineToolStripMenuItem;
private CommandToolStripMenuItem MoveVMToolStripMenuItem;
private CommandToolStripMenuItem rollingUpgradeToolStripMenuItem;
private CommandToolStripMenuItem vMProtectionAndRecoveryToolStripMenuItem;
private AssignGroupToolStripMenuItemVMPP assignPolicyToolStripMenuItem;
private CommandToolStripMenuItem changePoolPasswordToolStripMenuItem;
private ToolStripSeparator toolStripSeparator30;
private CommandToolStripMenuItem virtualAppliancesToolStripMenuItem;
private AssignGroupToolStripMenuItemVM_appliance assignToVirtualApplianceToolStripMenuItem;
private CommandToolStripMenuItem disasterRecoveryToolStripMenuItem;
private CommandToolStripMenuItem DrWizardToolStripMenuItem;
private CommandToolStripMenuItem drConfigureToolStripMenuItem;
private CommandToolStripMenuItem securityGroupsToolStripMenuItem;
private ToolStripSeparator toolStripMenuItem1;
private CommandToolStripMenuItem HostPasswordToolStripMenuItem;
private CommandToolStripMenuItem ChangeRootPasswordToolStripMenuItem;
private CommandToolStripMenuItem forgetSavedPasswordToolStripMenuItem;
private CommandToolStripMenuItem CreateVmFromTemplateToolStripMenuItem;
private CommandToolStripMenuItem newVMFromTemplateToolStripMenuItem;
private CommandToolStripMenuItem InstantVmToolStripMenuItem;
private ToolStripMenuItem importSettingsToolStripMenuItem;
private ToolStripMenuItem exportSettingsToolStripMenuItem;
private ToolStripSeparator toolStripSeparator31;
private CommandToolStripMenuItem destroyServerToolStripMenuItem;
private CommandToolStripMenuItem restartToolstackToolStripMenuItem;
private XenAdmin.Controls.MainWindowControls.NavigationPane navigationPane;
private XenAdmin.TabPages.AlertSummaryPage alertPage;
private XenAdmin.TabPages.ManageUpdatesPage updatesPage;
private XenAdmin.TabPages.HistoryPage eventsPage;
private ToolStripMenuItem customTemplatesToolStripMenuItem;
private ToolStripMenuItem templatesToolStripMenuItem1;
private ToolStripMenuItem localStorageToolStripMenuItem;
private StatusStrip StatusStrip;
private ToolStripStatusLabel statusLabel;
private ToolStripProgressBar statusProgressBar;
private CommandToolStripMenuItem reclaimFreedSpacetripMenuItem;
private CommandToolStripButton startContainerToolStripButton;
private CommandToolStripButton stopContainerToolStripButton;
private CommandToolStripButton pauseContainerToolStripButton;
private CommandToolStripButton resumeContainerToolStripButton;
private CommandToolStripButton restartContainerToolStripButton;
private CommandToolStripMenuItem healthCheckToolStripMenuItem1;
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Android.Graphics.Drawable.Shapes.cs
//
// 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.
#pragma warning disable 1717
namespace Android.Graphics.Drawable.Shapes
{
/// <summary>
/// <para>Defines an oval shape. The oval can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass the OvalShape to a android.graphics.drawable.ShapeDrawable. </para>
/// </summary>
/// <java-name>
/// android/graphics/drawable/shapes/OvalShape
/// </java-name>
[Dot42.DexImport("android/graphics/drawable/shapes/OvalShape", AccessFlags = 33)]
public partial class OvalShape : global::Android.Graphics.Drawable.Shapes.RectShape
/* scope: __dot42__ */
{
/// <summary>
/// <para>OvalShape constructor. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public OvalShape() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para>
/// </summary>
/// <java-name>
/// draw
/// </java-name>
[Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1)]
public override void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Defines a generic graphical "shape." Any Shape can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass it to a android.graphics.drawable.ShapeDrawable. </para>
/// </summary>
/// <java-name>
/// android/graphics/drawable/shapes/Shape
/// </java-name>
[Dot42.DexImport("android/graphics/drawable/shapes/Shape", AccessFlags = 1057)]
public abstract partial class Shape : global::Java.Lang.ICloneable
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public Shape() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the width of the Shape. </para>
/// </summary>
/// <java-name>
/// getWidth
/// </java-name>
[Dot42.DexImport("getWidth", "()F", AccessFlags = 17)]
public float GetWidth() /* MethodBuilder.Create */
{
return default(float);
}
/// <summary>
/// <para>Returns the height of the Shape. </para>
/// </summary>
/// <java-name>
/// getHeight
/// </java-name>
[Dot42.DexImport("getHeight", "()F", AccessFlags = 17)]
public float GetHeight() /* MethodBuilder.Create */
{
return default(float);
}
/// <summary>
/// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para>
/// </summary>
/// <java-name>
/// draw
/// </java-name>
[Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1025)]
public abstract void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Resizes the dimensions of this shape. Must be called before draw(Canvas,Paint).</para><para></para>
/// </summary>
/// <java-name>
/// resize
/// </java-name>
[Dot42.DexImport("resize", "(FF)V", AccessFlags = 17)]
public void Resize(float width, float height) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Checks whether the Shape is opaque. Default impl returns true. Override if your subclass can be opaque.</para><para></para>
/// </summary>
/// <returns>
/// <para>true if any part of the drawable is <b>not</b> opaque. </para>
/// </returns>
/// <java-name>
/// hasAlpha
/// </java-name>
[Dot42.DexImport("hasAlpha", "()Z", AccessFlags = 1)]
public virtual bool HasAlpha() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Callback method called when resize(float,float) is executed.</para><para></para>
/// </summary>
/// <java-name>
/// onResize
/// </java-name>
[Dot42.DexImport("onResize", "(FF)V", AccessFlags = 4)]
protected internal virtual void OnResize(float width, float height) /* MethodBuilder.Create */
{
}
/// <java-name>
/// clone
/// </java-name>
[Dot42.DexImport("clone", "()Landroid/graphics/drawable/shapes/Shape;", AccessFlags = 1)]
public virtual global::Android.Graphics.Drawable.Shapes.Shape Clone() /* MethodBuilder.Create */
{
return default(global::Android.Graphics.Drawable.Shapes.Shape);
}
/// <summary>
/// <para>Returns the width of the Shape. </para>
/// </summary>
/// <java-name>
/// getWidth
/// </java-name>
public float Width
{
[Dot42.DexImport("getWidth", "()F", AccessFlags = 17)]
get{ return GetWidth(); }
}
/// <summary>
/// <para>Returns the height of the Shape. </para>
/// </summary>
/// <java-name>
/// getHeight
/// </java-name>
public float Height
{
[Dot42.DexImport("getHeight", "()F", AccessFlags = 17)]
get{ return GetHeight(); }
}
}
/// <summary>
/// <para>Defines a rectangle shape. The rectangle can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass the RectShape to a android.graphics.drawable.ShapeDrawable. </para>
/// </summary>
/// <java-name>
/// android/graphics/drawable/shapes/RectShape
/// </java-name>
[Dot42.DexImport("android/graphics/drawable/shapes/RectShape", AccessFlags = 33)]
public partial class RectShape : global::Android.Graphics.Drawable.Shapes.Shape
/* scope: __dot42__ */
{
/// <summary>
/// <para>RectShape constructor. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public RectShape() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para>
/// </summary>
/// <java-name>
/// draw
/// </java-name>
[Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1)]
public override void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Callback method called when resize(float,float) is executed.</para><para></para>
/// </summary>
/// <java-name>
/// onResize
/// </java-name>
[Dot42.DexImport("onResize", "(FF)V", AccessFlags = 4)]
protected internal override void OnResize(float width, float height) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the RectF that defines this rectangle's bounds. </para>
/// </summary>
/// <java-name>
/// rect
/// </java-name>
[Dot42.DexImport("rect", "()Landroid/graphics/RectF;", AccessFlags = 20)]
protected internal global::Android.Graphics.RectF Rect() /* MethodBuilder.Create */
{
return default(global::Android.Graphics.RectF);
}
/// <java-name>
/// clone
/// </java-name>
[Dot42.DexImport("clone", "()Landroid/graphics/drawable/shapes/RectShape;", AccessFlags = 1)]
public new virtual global::Android.Graphics.Drawable.Shapes.RectShape Clone() /* MethodBuilder.Create */
{
return default(global::Android.Graphics.Drawable.Shapes.RectShape);
}
}
/// <summary>
/// <para>Creates an arc shape. The arc shape starts at a specified angle and sweeps clockwise, drawing slices of pie. The arc can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass the ArcShape to a android.graphics.drawable.ShapeDrawable. </para>
/// </summary>
/// <java-name>
/// android/graphics/drawable/shapes/ArcShape
/// </java-name>
[Dot42.DexImport("android/graphics/drawable/shapes/ArcShape", AccessFlags = 33)]
public partial class ArcShape : global::Android.Graphics.Drawable.Shapes.RectShape
/* scope: __dot42__ */
{
/// <summary>
/// <para>ArcShape constructor.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(FF)V", AccessFlags = 1)]
public ArcShape(float startAngle, float sweepAngle) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para>
/// </summary>
/// <java-name>
/// draw
/// </java-name>
[Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1)]
public override void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ArcShape() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>Creates geometric paths, utilizing the android.graphics.Path class. The path can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass the PathShape to a android.graphics.drawable.ShapeDrawable. </para>
/// </summary>
/// <java-name>
/// android/graphics/drawable/shapes/PathShape
/// </java-name>
[Dot42.DexImport("android/graphics/drawable/shapes/PathShape", AccessFlags = 33)]
public partial class PathShape : global::Android.Graphics.Drawable.Shapes.Shape
/* scope: __dot42__ */
{
/// <summary>
/// <para>PathShape constructor.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Landroid/graphics/Path;FF)V", AccessFlags = 1)]
public PathShape(global::Android.Graphics.Path path, float stdWidth, float stdHeight) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para>
/// </summary>
/// <java-name>
/// draw
/// </java-name>
[Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1)]
public override void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Callback method called when resize(float,float) is executed.</para><para></para>
/// </summary>
/// <java-name>
/// onResize
/// </java-name>
[Dot42.DexImport("onResize", "(FF)V", AccessFlags = 4)]
protected internal override void OnResize(float width, float height) /* MethodBuilder.Create */
{
}
/// <java-name>
/// clone
/// </java-name>
[Dot42.DexImport("clone", "()Landroid/graphics/drawable/shapes/PathShape;", AccessFlags = 1)]
public new virtual global::Android.Graphics.Drawable.Shapes.PathShape Clone() /* MethodBuilder.Create */
{
return default(global::Android.Graphics.Drawable.Shapes.PathShape);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal PathShape() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>Creates a rounded-corner rectangle. Optionally, an inset (rounded) rectangle can be included (to make a sort of "O" shape). The rounded rectangle can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass the RoundRectShape to a android.graphics.drawable.ShapeDrawable. </para>
/// </summary>
/// <java-name>
/// android/graphics/drawable/shapes/RoundRectShape
/// </java-name>
[Dot42.DexImport("android/graphics/drawable/shapes/RoundRectShape", AccessFlags = 33)]
public partial class RoundRectShape : global::Android.Graphics.Drawable.Shapes.RectShape
/* scope: __dot42__ */
{
/// <summary>
/// <para>RoundRectShape constructor. Specifies an outer (round)rect and an optional inner (round)rect.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "([FLandroid/graphics/RectF;[F)V", AccessFlags = 1)]
public RoundRectShape(float[] outerRadii, global::Android.Graphics.RectF inset, float[] innerRadii) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para>
/// </summary>
/// <java-name>
/// draw
/// </java-name>
[Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1)]
public override void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Callback method called when resize(float,float) is executed.</para><para></para>
/// </summary>
/// <java-name>
/// onResize
/// </java-name>
[Dot42.DexImport("onResize", "(FF)V", AccessFlags = 4)]
protected internal override void OnResize(float width, float height) /* MethodBuilder.Create */
{
}
/// <java-name>
/// clone
/// </java-name>
[Dot42.DexImport("clone", "()Landroid/graphics/drawable/shapes/RoundRectShape;", AccessFlags = 1)]
public new virtual global::Android.Graphics.Drawable.Shapes.RoundRectShape Clone() /* MethodBuilder.Create */
{
return default(global::Android.Graphics.Drawable.Shapes.RoundRectShape);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal RoundRectShape() /* TypeBuilder.AddDefaultConstructor */
{
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using Apache.Ignite.Core;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.ExamplesDll.Binary;
namespace Apache.Ignite.Examples.Datagrid
{
/// <summary>
/// This example populates cache with sample data and runs several SQL and
/// full text queries over this data.
/// <para />
/// 1) Build the project Apache.Ignite.ExamplesDll (select it -> right-click -> Build).
/// Apache.Ignite.ExamplesDll.dll must appear in %IGNITE_HOME%/platforms/dotnet/examples/Apache.Ignite.ExamplesDll/bin/${Platform]/${Configuration} folder.
/// 2) Set this class as startup object (Apache.Ignite.Examples project -> right-click -> Properties ->
/// Application -> Startup object);
/// 3) Start example (F5 or Ctrl+F5).
/// <para />
/// This example can be run with standalone Apache Ignite.NET node:
/// 1) Run %IGNITE_HOME%/platforms/dotnet/bin/Apache.Ignite.exe:
/// Apache.Ignite.exe -IgniteHome="%IGNITE_HOME%" -springConfigUrl=platforms\dotnet\examples\config\examples-config.xml -assembly=[path_to_Apache.Ignite.ExamplesDll.dll]
/// 2) Start example.
/// </summary>
public class QueryExample
{
/// <summary>Cache name.</summary>
private const string CacheName = "dotnet_cache_query";
[STAThread]
public static void Main()
{
using (var ignite = Ignition.Start(@"platforms\dotnet\examples\config\examples-config.xml"))
{
Console.WriteLine();
Console.WriteLine(">>> Cache query example started.");
var cache = ignite.GetOrCreateCache<object, object>(new CacheConfiguration
{
Name = CacheName,
QueryEntities = new[]
{
new QueryEntity(typeof(int), typeof(Organization)),
new QueryEntity(typeof(EmployeeKey), typeof(Employee))
}
});
// Clean up caches on all nodes before run.
cache.Clear();
// Populate cache with sample data entries.
PopulateCache(cache);
// Create cache that will work with specific types.
var employeeCache = ignite.GetCache<EmployeeKey, Employee>(CacheName);
// Run SQL query example.
SqlQueryExample(employeeCache);
// Run SQL query with join example.
SqlJoinQueryExample(employeeCache);
// Run SQL fields query example.
SqlFieldsQueryExample(employeeCache);
// Run full text query example.
FullTextQueryExample(employeeCache);
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine(">>> Example finished, press any key to exit ...");
Console.ReadKey();
}
/// <summary>
/// Queries employees that have provided ZIP code in address.
/// </summary>
/// <param name="cache">Cache.</param>
private static void SqlQueryExample(ICache<EmployeeKey, Employee> cache)
{
const int zip = 94109;
var qry = cache.Query(new SqlQuery(typeof(Employee), "zip = ?", zip));
Console.WriteLine();
Console.WriteLine(">>> Employees with zipcode " + zip + ":");
foreach (var entry in qry)
Console.WriteLine(">>> " + entry.Value);
}
/// <summary>
/// Queries employees that work for organization with provided name.
/// </summary>
/// <param name="cache">Cache.</param>
private static void SqlJoinQueryExample(ICache<EmployeeKey, Employee> cache)
{
const string orgName = "Apache";
var qry = cache.Query(new SqlQuery("Employee",
"from Employee, Organization " +
"where Employee.organizationId = Organization._key and Organization.name = ?", orgName));
Console.WriteLine();
Console.WriteLine(">>> Employees working for " + orgName + ":");
foreach (var entry in qry)
Console.WriteLine(">>> " + entry.Value);
}
/// <summary>
/// Queries names and salaries for all employees.
/// </summary>
/// <param name="cache">Cache.</param>
private static void SqlFieldsQueryExample(ICache<EmployeeKey, Employee> cache)
{
var qry = cache.QueryFields(new SqlFieldsQuery("select name, salary from Employee"));
Console.WriteLine();
Console.WriteLine(">>> Employee names and their salaries:");
foreach (IList row in qry)
Console.WriteLine(">>> [Name=" + row[0] + ", salary=" + row[1] + ']');
}
/// <summary>
/// Queries employees that live in Texas using full-text query API.
/// </summary>
/// <param name="cache">Cache.</param>
private static void FullTextQueryExample(ICache<EmployeeKey, Employee> cache)
{
var qry = cache.Query(new TextQuery("Employee", "TX"));
Console.WriteLine();
Console.WriteLine(">>> Employees living in Texas:");
foreach (var entry in qry)
Console.WriteLine(">>> " + entry.Value);
}
/// <summary>
/// Populate cache with data for this example.
/// </summary>
/// <param name="cache">Cache.</param>
private static void PopulateCache(ICache<object, object> cache)
{
cache.Put(1, new Organization(
"Apache",
new Address("1065 East Hillsdale Blvd, Foster City, CA", 94404),
OrganizationType.Private,
DateTime.Now
));
cache.Put(2, new Organization(
"Microsoft",
new Address("1096 Eddy Street, San Francisco, CA", 94109),
OrganizationType.Private,
DateTime.Now
));
cache.Put(new EmployeeKey(1, 1), new Employee(
"James Wilson",
12500,
new Address("1096 Eddy Street, San Francisco, CA", 94109),
new List<string> { "Human Resources", "Customer Service" }
));
cache.Put(new EmployeeKey(2, 1), new Employee(
"Daniel Adams",
11000,
new Address("184 Fidler Drive, San Antonio, TX", 78130),
new List<string> { "Development", "QA" }
));
cache.Put(new EmployeeKey(3, 1), new Employee(
"Cristian Moss",
12500,
new Address("667 Jerry Dove Drive, Florence, SC", 29501),
new List<string> { "Logistics" }
));
cache.Put(new EmployeeKey(4, 2), new Employee(
"Allison Mathis",
25300,
new Address("2702 Freedom Lane, San Francisco, CA", 94109),
new List<string> { "Development" }
));
cache.Put(new EmployeeKey(5, 2), new Employee(
"Breana Robbin",
6500,
new Address("3960 Sundown Lane, Austin, TX", 78130),
new List<string> { "Sales" }
));
cache.Put(new EmployeeKey(6, 2), new Employee(
"Philip Horsley",
19800,
new Address("2803 Elsie Drive, Sioux Falls, SD", 57104),
new List<string> { "Sales" }
));
cache.Put(new EmployeeKey(7, 2), new Employee(
"Brian Peters",
10600,
new Address("1407 Pearlman Avenue, Boston, MA", 12110),
new List<string> { "Development", "QA" }
));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.IO.Tests
{
public class Directory_Delete_str : FileSystemTest
{
#region Utilities
public virtual void Delete(string path)
{
Directory.Delete(path);
}
#endregion
#region UniversalTests
[Fact]
public void NullParameters()
{
Assert.Throws<ArgumentNullException>(() => Delete(null));
}
[Fact]
public void InvalidParameters()
{
Assert.Throws<ArgumentException>(() => Delete(string.Empty));
}
[Fact]
public void ShouldThrowIOExceptionIfContainedFileInUse()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
using (File.Create(Path.Combine(testDir.FullName, GetTestFileName())))
{
Assert.Throws<IOException>(() => Delete(testDir.FullName));
}
Assert.True(testDir.Exists);
}
[Fact]
public void ShouldThrowIOExceptionForDirectoryWithFiles()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
File.Create(Path.Combine(testDir.FullName, GetTestFileName())).Dispose();
Assert.Throws<IOException>(() => Delete(testDir.FullName));
Assert.True(testDir.Exists);
}
[Fact]
public void DirectoryWithSubdirectories()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.CreateSubdirectory(GetTestFileName());
Assert.Throws<IOException>(() => Delete(testDir.FullName));
Assert.True(testDir.Exists);
}
[Fact]
[OuterLoop]
public void DeleteRoot()
{
Assert.Throws<IOException>(() => Delete(Path.GetPathRoot(Directory.GetCurrentDirectory())));
}
[Fact]
public void PositiveTest()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Delete(testDir.FullName);
Assert.False(testDir.Exists);
}
[Theory, MemberData(nameof(TrailingCharacters))]
public void MissingFile_ThrowsDirectoryNotFound(char trailingChar)
{
string path = GetTestFilePath() + trailingChar;
Assert.Throws<DirectoryNotFoundException>(() => Delete(path));
}
[Theory, MemberData(nameof(TrailingCharacters))]
public void MissingDirectory_ThrowsDirectoryNotFound(char trailingChar)
{
string path = Path.Combine(GetTestFilePath(), "file" + trailingChar);
Assert.Throws<DirectoryNotFoundException>(() => Delete(path));
}
[Fact]
public void ShouldThrowIOExceptionDeletingCurrentDirectory()
{
Assert.Throws<IOException>(() => Delete(Directory.GetCurrentDirectory()));
}
[ConditionalFact(nameof(CanCreateSymbolicLinks))]
public void DeletingSymLinkDoesntDeleteTarget()
{
var path = GetTestFilePath();
var linkPath = GetTestFilePath();
Directory.CreateDirectory(path);
Assert.True(MountHelper.CreateSymbolicLink(linkPath, path, isDirectory: true));
// Both the symlink and the target exist
Assert.True(Directory.Exists(path), "path should exist");
Assert.True(Directory.Exists(linkPath), "linkPath should exist");
// Delete the symlink
Directory.Delete(linkPath);
// Target should still exist
Assert.True(Directory.Exists(path), "path should still exist");
Assert.False(Directory.Exists(linkPath), "linkPath should no longer exist");
}
[ConditionalFact(nameof(UsingNewNormalization))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
public void ExtendedDirectoryWithSubdirectories()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath());
testDir.CreateSubdirectory(GetTestFileName());
Assert.Throws<IOException>(() => Delete(testDir.FullName));
Assert.True(testDir.Exists);
}
[ConditionalFact(nameof(LongPathsAreNotBlocked), nameof(UsingNewNormalization))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
public void LongPathExtendedDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOServices.GetPath(IOInputs.ExtendedPrefix + TestDirectory, characterCount: 500).FullPath);
Delete(testDir.FullName);
Assert.False(testDir.Exists);
}
#endregion
#region PlatformSpecific
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Deleting readonly directory throws IOException
public void WindowsDeleteReadOnlyDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.Attributes = FileAttributes.ReadOnly;
Assert.Throws<IOException>(() => Delete(testDir.FullName));
Assert.True(testDir.Exists);
testDir.Attributes = FileAttributes.Normal;
}
[ConditionalFact(nameof(UsingNewNormalization))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
[PlatformSpecific(TestPlatforms.Windows)] // Deleting extended readonly directory throws IOException
public void WindowsDeleteExtendedReadOnlyDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath());
testDir.Attributes = FileAttributes.ReadOnly;
Assert.Throws<IOException>(() => Delete(testDir.FullName));
Assert.True(testDir.Exists);
testDir.Attributes = FileAttributes.Normal;
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Deleting readOnly directory succeeds
public void UnixDeleteReadOnlyDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.Attributes = FileAttributes.ReadOnly;
Delete(testDir.FullName);
Assert.False(testDir.Exists);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Deleting hidden directory succeeds
public void WindowsShouldBeAbleToDeleteHiddenDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.Attributes = FileAttributes.Hidden;
Delete(testDir.FullName);
Assert.False(testDir.Exists);
}
[ConditionalFact(nameof(UsingNewNormalization))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
[PlatformSpecific(TestPlatforms.Windows)] // Deleting extended hidden directory succeeds
public void WindowsShouldBeAbleToDeleteExtendedHiddenDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath());
testDir.Attributes = FileAttributes.Hidden;
Delete(testDir.FullName);
Assert.False(testDir.Exists);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Deleting hidden directory succeeds
public void UnixShouldBeAbleToDeleteHiddenDirectory()
{
string testDir = "." + GetTestFileName();
Directory.CreateDirectory(Path.Combine(TestDirectory, testDir));
Assert.True(0 != (new DirectoryInfo(Path.Combine(TestDirectory, testDir)).Attributes & FileAttributes.Hidden));
Delete(Path.Combine(TestDirectory, testDir));
Assert.False(Directory.Exists(testDir));
}
#endregion
}
public class Directory_Delete_str_bool : Directory_Delete_str
{
#region Utilities
public override void Delete(string path)
{
Directory.Delete(path, false);
}
public virtual void Delete(string path, bool recursive)
{
Directory.Delete(path, recursive);
}
#endregion
[Fact]
public void RecursiveDelete()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
File.Create(Path.Combine(testDir.FullName, GetTestFileName())).Dispose();
testDir.CreateSubdirectory(GetTestFileName());
Delete(testDir.FullName, true);
Assert.False(testDir.Exists);
}
[Fact]
public void RecursiveDeleteWithTrailingSlash()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Delete(testDir.FullName + Path.DirectorySeparatorChar, true);
Assert.False(testDir.Exists);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Recursive delete throws IOException if directory contains in-use file
public void RecursiveDelete_ShouldThrowIOExceptionIfContainedFileInUse()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
using (File.Create(Path.Combine(testDir.FullName, GetTestFileName())))
{
Assert.Throws<IOException>(() => Delete(testDir.FullName, true));
}
Assert.True(testDir.Exists);
}
}
}
| |
using System;
using System.Collections.Generic;
/// <summary>
/// System.Collections.Generic.List.RemoveAt(Int32)
/// </summary>
public class ListRemoveAt
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: The generic type is int");
try
{
int[] iArray = { 1, 9, 3, 6, -1, 8, 7, 10, 2, 4 };
List<int> listObject = new List<int>(iArray);
int index = this.GetInt32(0, 10);
listObject.RemoveAt(index);
if (listObject.Contains(iArray[index]))
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: The generic type is type of string and the element at the beginning would be removed");
try
{
string[] strArray = { "dog", "apple", "joke", "banana", "chocolate", "dog", "food" };
List<string> listObject = new List<string>(strArray);
listObject.RemoveAt(0);
if (listObject.Count != 6)
{
TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,count is: " + listObject.Count);
retVal = false;
}
for (int i = 0; i < 6; i++)
{
if (listObject[i] != strArray[i + 1])
{
TestLibrary.TestFramework.LogError("004", "The result is not the value as expected,i is: " + i);
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: The generic type is a custom type and the element to be removed is at the end of the list");
try
{
MyClass myclass1 = new MyClass();
MyClass myclass2 = new MyClass();
MyClass myclass3 = new MyClass();
MyClass[] mc = new MyClass[3] { myclass1, myclass2, myclass3 };
List<MyClass> listObject = new List<MyClass>(mc);
listObject.RemoveAt(2);
if (listObject.Count != 2)
{
TestLibrary.TestFramework.LogError("006", "The result is not the value as expected,count is: " + listObject.Count);
retVal = false;
}
if (listObject.Contains(myclass3))
{
TestLibrary.TestFramework.LogError("007", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: The index is negative");
try
{
int[] iArray = { 1, 9, 3, 6, -1, 8, 7, 10, 2, 4 };
List<int> listObject = new List<int>(iArray);
listObject.RemoveAt(-1);
TestLibrary.TestFramework.LogError("103", "The ArgumentOutOfRangeException was not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: The index is greater than the range of the list");
try
{
char?[] chArray = { 'a', 'b', ' ', 'c', null };
List<char?> listObject = new List<char?>(chArray);
listObject.RemoveAt(10);
TestLibrary.TestFramework.LogError("103", "The ArgumentOutOfRangeException was not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ListRemoveAt test = new ListRemoveAt();
TestLibrary.TestFramework.BeginTestCase("ListRemoveAt");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
}
public class MyClass
{
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing.Patterns;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Routing.Matching
{
internal sealed partial class DfaMatcher : Matcher
{
private readonly ILogger _logger;
private readonly EndpointSelector _selector;
private readonly DfaState[] _states;
private readonly int _maxSegmentCount;
private readonly bool _isDefaultEndpointSelector;
public DfaMatcher(ILogger<DfaMatcher> logger, EndpointSelector selector, DfaState[] states, int maxSegmentCount)
{
_logger = logger;
_selector = selector;
_states = states;
_maxSegmentCount = maxSegmentCount;
_isDefaultEndpointSelector = selector is DefaultEndpointSelector;
}
[SkipLocalsInit]
public sealed override Task MatchAsync(HttpContext httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException(nameof(httpContext));
}
// All of the logging we do here is at level debug, so we can get away with doing a single check.
var log = _logger.IsEnabled(LogLevel.Debug);
// The sequence of actions we take is optimized to avoid doing expensive work
// like creating substrings, creating route value dictionaries, and calling
// into policies like versioning.
var path = httpContext.Request.Path.Value!;
// First tokenize the path into series of segments.
Span<PathSegment> buffer = stackalloc PathSegment[_maxSegmentCount];
var count = FastPathTokenizer.Tokenize(path, buffer);
var segments = buffer.Slice(0, count);
// FindCandidateSet will process the DFA and return a candidate set. This does
// some preliminary matching of the URL (mostly the literal segments).
var (candidates, policies) = FindCandidateSet(httpContext, path, segments);
var candidateCount = candidates.Length;
if (candidateCount == 0)
{
if (log)
{
Log.CandidatesNotFound(_logger, path);
}
return Task.CompletedTask;
}
if (log)
{
Log.CandidatesFound(_logger, path, candidates);
}
var policyCount = policies.Length;
// This is a fast path for single candidate, 0 policies and default selector
if (candidateCount == 1 && policyCount == 0 && _isDefaultEndpointSelector)
{
ref readonly var candidate = ref candidates[0];
// Just strict path matching (no route values)
if (candidate.Flags == Candidate.CandidateFlags.None)
{
httpContext.SetEndpoint(candidate.Endpoint);
// We're done
return Task.CompletedTask;
}
}
// At this point we have a candidate set, defined as a list of endpoints in
// priority order.
//
// We don't yet know that any candidate can be considered a match, because
// we haven't processed things like route constraints and complex segments.
//
// Now we'll iterate each endpoint to capture route values, process constraints,
// and process complex segments.
// `candidates` has all of our internal state that we use to process the
// set of endpoints before we call the EndpointSelector.
//
// `candidateSet` is the mutable state that we pass to the EndpointSelector.
var candidateState = new CandidateState[candidateCount];
for (var i = 0; i < candidateCount; i++)
{
// PERF: using ref here to avoid copying around big structs.
//
// Reminder!
// candidate: readonly data about the endpoint and how to match
// state: mutable storarge for our processing
ref readonly var candidate = ref candidates[i];
ref var state = ref candidateState[i];
state = new CandidateState(candidate.Endpoint, candidate.Score);
var flags = candidate.Flags;
// First process all of the parameters and defaults.
if ((flags & Candidate.CandidateFlags.HasSlots) != 0)
{
// The Slots array has the default values of the route values in it.
//
// We want to create a new array for the route values based on Slots
// as a prototype.
var prototype = candidate.Slots;
var slots = new KeyValuePair<string, object?>[prototype.Length];
if ((flags & Candidate.CandidateFlags.HasDefaults) != 0)
{
Array.Copy(prototype, 0, slots, 0, prototype.Length);
}
if ((flags & Candidate.CandidateFlags.HasCaptures) != 0)
{
ProcessCaptures(slots, candidate.Captures, path, segments);
}
if ((flags & Candidate.CandidateFlags.HasCatchAll) != 0)
{
ProcessCatchAll(slots, candidate.CatchAll, path, segments);
}
state.Values = RouteValueDictionary.FromArray(slots);
}
// Now that we have the route values, we need to process complex segments.
// Complex segments go through an old API that requires a fully-materialized
// route value dictionary.
var isMatch = true;
if ((flags & Candidate.CandidateFlags.HasComplexSegments) != 0)
{
state.Values ??= new RouteValueDictionary();
if (!ProcessComplexSegments(candidate.Endpoint, candidate.ComplexSegments, path, segments, state.Values))
{
CandidateSet.SetValidity(ref state, false);
isMatch = false;
}
}
if ((flags & Candidate.CandidateFlags.HasConstraints) != 0)
{
state.Values ??= new RouteValueDictionary();
if (!ProcessConstraints(candidate.Endpoint, candidate.Constraints, httpContext, state.Values))
{
CandidateSet.SetValidity(ref state, false);
isMatch = false;
}
}
if (log)
{
if (isMatch)
{
Log.CandidateValid(_logger, path, candidate.Endpoint);
}
else
{
Log.CandidateNotValid(_logger, path, candidate.Endpoint);
}
}
}
if (policyCount == 0 && _isDefaultEndpointSelector)
{
// Fast path that avoids allocating the candidate set.
//
// We can use this when there are no policies and we're using the default selector.
DefaultEndpointSelector.Select(httpContext, candidateState);
return Task.CompletedTask;
}
else if (policyCount == 0)
{
// Fast path that avoids a state machine.
//
// We can use this when there are no policies and a non-default selector.
return _selector.SelectAsync(httpContext, new CandidateSet(candidateState));
}
return SelectEndpointWithPoliciesAsync(httpContext, policies, new CandidateSet(candidateState));
}
internal (Candidate[] candidates, IEndpointSelectorPolicy[] policies) FindCandidateSet(
HttpContext httpContext,
string path,
ReadOnlySpan<PathSegment> segments)
{
var states = _states;
// Process each path segment
var destination = 0;
for (var i = 0; i < segments.Length; i++)
{
destination = states[destination].PathTransitions.GetDestination(path, segments[i]);
}
// Process an arbitrary number of policy-based decisions
var policyTransitions = states[destination].PolicyTransitions;
while (policyTransitions != null)
{
destination = policyTransitions.GetDestination(httpContext);
policyTransitions = states[destination].PolicyTransitions;
}
return (states[destination].Candidates, states[destination].Policies);
}
private static void ProcessCaptures(
KeyValuePair<string, object?>[] slots,
(string parameterName, int segmentIndex, int slotIndex)[] captures,
string path,
ReadOnlySpan<PathSegment> segments)
{
for (var i = 0; i < captures.Length; i++)
{
(var parameterName, var segmentIndex, var slotIndex) = captures[i];
if ((uint)segmentIndex < (uint)segments.Length)
{
var segment = segments[segmentIndex];
if (parameterName != null && segment.Length > 0)
{
slots[slotIndex] = new KeyValuePair<string, object?>(
parameterName,
path.Substring(segment.Start, segment.Length));
}
}
}
}
private static void ProcessCatchAll(
KeyValuePair<string, object?>[] slots,
in (string parameterName, int segmentIndex, int slotIndex) catchAll,
string path,
ReadOnlySpan<PathSegment> segments)
{
// Read segmentIndex to local both to skip double read from stack value
// and to use the same in-bounds validated variable to access the array.
var segmentIndex = catchAll.segmentIndex;
if ((uint)segmentIndex < (uint)segments.Length)
{
var segment = segments[segmentIndex];
slots[catchAll.slotIndex] = new KeyValuePair<string, object?>(
catchAll.parameterName,
path.Substring(segment.Start));
}
}
private bool ProcessComplexSegments(
Endpoint endpoint,
(RoutePatternPathSegment pathSegment, int segmentIndex)[] complexSegments,
string path,
ReadOnlySpan<PathSegment> segments,
RouteValueDictionary values)
{
for (var i = 0; i < complexSegments.Length; i++)
{
(var complexSegment, var segmentIndex) = complexSegments[i];
var segment = segments[segmentIndex];
var text = path.AsSpan(segment.Start, segment.Length);
if (!RoutePatternMatcher.MatchComplexSegment(complexSegment, text, values))
{
Log.CandidateRejectedByComplexSegment(_logger, path, endpoint, complexSegment);
return false;
}
}
return true;
}
private bool ProcessConstraints(
Endpoint endpoint,
KeyValuePair<string, IRouteConstraint>[] constraints,
HttpContext httpContext,
RouteValueDictionary values)
{
for (var i = 0; i < constraints.Length; i++)
{
var constraint = constraints[i];
if (!constraint.Value.Match(httpContext, NullRouter.Instance, constraint.Key, values, RouteDirection.IncomingRequest))
{
Log.CandidateRejectedByConstraint(_logger, httpContext.Request.Path, endpoint, constraint.Key, constraint.Value, values[constraint.Key]);
return false;
}
}
return true;
}
private async Task SelectEndpointWithPoliciesAsync(
HttpContext httpContext,
IEndpointSelectorPolicy[] policies,
CandidateSet candidateSet)
{
for (var i = 0; i < policies.Length; i++)
{
var policy = policies[i];
await policy.ApplyAsync(httpContext, candidateSet);
if (httpContext.GetEndpoint() != null)
{
// This is a short circuit, the selector chose an endpoint.
return;
}
}
await _selector.SelectAsync(httpContext, candidateSet);
}
private static partial class Log
{
[LoggerMessage(1000, LogLevel.Debug,
"No candidates found for the request path '{Path}'",
EventName = "CandidatesNotFound",
SkipEnabledCheck = true)]
public static partial void CandidatesNotFound(ILogger logger, string path);
public static void CandidatesFound(ILogger logger, string path, Candidate[] candidates)
=> CandidatesFound(logger, candidates.Length, path);
[LoggerMessage(1001, LogLevel.Debug,
"{CandidateCount} candidate(s) found for the request path '{Path}'",
EventName = "CandidatesFound",
SkipEnabledCheck = true)]
private static partial void CandidatesFound(ILogger logger, int candidateCount, string path);
public static void CandidateRejectedByComplexSegment(ILogger logger, string path, Endpoint endpoint, RoutePatternPathSegment segment)
{
// This should return a real pattern since we're processing complex segments.... but just in case.
if (logger.IsEnabled(LogLevel.Debug))
{
var routePattern = GetRoutePattern(endpoint);
CandidateRejectedByComplexSegment(logger, endpoint.DisplayName, routePattern, segment.DebuggerToString(), path);
}
}
[LoggerMessage(1002, LogLevel.Debug,
"Endpoint '{Endpoint}' with route pattern '{RoutePattern}' was rejected by complex segment '{Segment}' for the request path '{Path}'",
EventName = "CandidateRejectedByComplexSegment",
SkipEnabledCheck = true)]
private static partial void CandidateRejectedByComplexSegment(ILogger logger, string? endpoint, string routePattern, string segment, string path);
public static void CandidateRejectedByConstraint(ILogger logger, string path, Endpoint endpoint, string constraintName, IRouteConstraint constraint, object? value)
{
// This should return a real pattern since we're processing constraints.... but just in case.
if (logger.IsEnabled(LogLevel.Debug))
{
var routePattern = GetRoutePattern(endpoint);
CandidateRejectedByConstraint(logger, endpoint.DisplayName, routePattern, constraintName, constraint.ToString(), value, path);
}
}
[LoggerMessage(1003, LogLevel.Debug,
"Endpoint '{Endpoint}' with route pattern '{RoutePattern}' was rejected by constraint '{ConstraintName}':'{Constraint}' with value '{RouteValue}' for the request path '{Path}'",
EventName = "CandidateRejectedByConstraint",
SkipEnabledCheck = true)]
private static partial void CandidateRejectedByConstraint(ILogger logger, string? endpoint, string routePattern, string constraintName, string? constraint, object? routeValue, string path);
public static void CandidateNotValid(ILogger logger, string path, Endpoint endpoint)
{
// This can be the fallback value because it really might not be a route endpoint
if (logger.IsEnabled(LogLevel.Debug))
{
var routePattern = GetRoutePattern(endpoint);
CandidateNotValid(logger, endpoint.DisplayName, routePattern, path);
}
}
[LoggerMessage(1004, LogLevel.Debug,
"Endpoint '{Endpoint}' with route pattern '{RoutePattern}' is not valid for the request path '{Path}'",
EventName = "CandidateNotValid",
SkipEnabledCheck = true)]
private static partial void CandidateNotValid(ILogger logger, string? endpoint, string routePattern, string path);
public static void CandidateValid(ILogger logger, string path, Endpoint endpoint)
{
// This can be the fallback value because it really might not be a route endpoint
if (logger.IsEnabled(LogLevel.Debug))
{
var routePattern = GetRoutePattern(endpoint);
CandidateValid(logger, endpoint.DisplayName, routePattern, path);
}
}
[LoggerMessage(1005, LogLevel.Debug,
"Endpoint '{Endpoint}' with route pattern '{RoutePattern}' is valid for the request path '{Path}'",
EventName = "CandidateValid",
SkipEnabledCheck = true)]
private static partial void CandidateValid(ILogger logger, string? endpoint, string routePattern, string path);
private static string GetRoutePattern(Endpoint endpoint)
{
return (endpoint as RouteEndpoint)?.RoutePattern?.RawText ?? "(none)";
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using hw.DebugFormatter;
using JetBrains.Annotations;
// ReSharper disable CheckNamespace
namespace hw.Helper;
/// <summary>
/// String helper functions.
/// </summary>
[PublicAPI]
public static class StringExtender
{
/// <summary>
/// Indent parameter by 4 times count spaces
/// </summary>
/// <param name="target"> The target. </param>
/// <param name="tabString"></param>
/// <param name="count"> The count. </param>
/// <param name="isLineStart"></param>
/// <returns> </returns>
public static string Indent
(this string target, int count = 1, string tabString = " ", bool isLineStart = false)
{
var effectiveTabString = tabString.Repeat(count);
return (isLineStart? effectiveTabString : "") + target.Replace("\n", "\n" + effectiveTabString);
}
/// <summary>
/// Repeats the specified s.
/// </summary>
/// <param name="s"> The s. </param>
/// <param name="count"> The count. </param>
/// <returns> </returns>
/// created 15.10.2006 14:38
public static string Repeat(this string s, int count)
{
var result = "";
for(var i = 0; i < count; i++)
result += s;
return result;
}
/// <summary>
/// Surrounds string by left and right parenthesis. If string contains any carriage return, some indenting is done also
/// </summary>
/// <param name="left"> </param>
/// <param name="data"> </param>
/// <param name="right"> </param>
/// <returns> </returns>
public static string Surround(this string data, string left, string right = null)
{
if(right == null)
{
var value = left.Single().ToString();
var index = "<({[".IndexOf(value, StringComparison.Ordinal);
right = ">)}]"[index].ToString();
}
if(data.IndexOf("\n", StringComparison.Ordinal) < 0)
return left + data + right;
return "\n" + left + Indent("\n" + data) + "\n" + right;
}
public static string SaveConcat(this string delimiter, params string[] data)
=> data.Where(d => !string.IsNullOrEmpty(d)).Stringify(delimiter);
/// <summary>
/// Converts string to a string literal.
/// </summary>
/// <param name="target"> The target. </param>
/// <returns> </returns>
/// created 08.01.2007 18:37
public static string Quote(this string target)
{
if(target == null)
return "null";
return "\"" + target.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
}
static string CharacterQuote(char character)
{
switch(character)
{
case '\\':
case '"':
return "\\" + character;
case '\n':
return "\\n";
case '\t':
return "\\t";
case '\r':
return "\\r";
case '\f':
return "\\f";
default:
if(character < 32 || character >= 127)
return $"\\0x{(int)character:x2}";
return "" + character;
}
}
/// <summary>
/// Converts string to a string literal suitable for languages like c#.
/// </summary>
/// <param name="target"> The target. </param>
/// <returns> </returns>
public static string CSharpQuote(this string target)
=> target.Aggregate("\"", (head, next) => head + CharacterQuote(next)) + "\"";
/// <summary>
/// Dumps the bytes as hex string.
/// </summary>
/// <param name="bytes"> The bytes. </param>
/// <returns> </returns>
public static string HexDump(this byte[] bytes)
{
var result = "";
for(var i = 0; i < bytes.Length; i++)
{
result += HexDumpFiller(i, bytes.Length);
result += bytes[i].ToString("x2");
}
result += HexDumpFiller(bytes.Length, bytes.Length);
return result;
}
public static string ExecuteCommand(this string command)
{
var procStartInfo = new ProcessStartInfo("cmd", "/c " + command)
{ RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true };
var proc = new Process { StartInfo = procStartInfo };
proc.Start();
return proc.StandardOutput.ReadToEnd();
}
public static SmbFile ToSmbFile
(this string name, bool autoCreateDirectories = true) => SmbFile.Create(name, autoCreateDirectories);
public static string PathCombine
(this string head, params string[] tail) => Path.Combine(head, Path.Combine(tail));
public static string UnderScoreToCamelCase
(this string name) => name.Split('_').Select(ToLowerFirstUpper).Stringify("");
public static string ToLowerFirstUpper
(this string text) => text.Substring(0, 1).ToUpperInvariant() + text.Substring(1).ToLowerInvariant();
public static string TableNameToClassName(this string name) => name.UnderScoreToCamelCase().ToSingular();
[StringFormatMethod("pattern")]
public static string ReplaceArgs(this string pattern, params object[] args) => string.Format(pattern, args);
public static bool Matches(this string input, string pattern) => new Regex(pattern).IsMatch(input);
public static IEnumerable<string> Split(this string target, params int[] sizes)
{
var start = 0;
foreach(var length in sizes.Select(size => Math.Max(0, Math.Min(target.Length - start, size))))
{
yield return target.Substring(start, length);
start += length;
}
yield return target.Substring(start);
}
public static string Format(this string target, StringAligner aligner) => aligner.Format(target);
/// <summary>
/// Provide default string aligner with columnCount columns
/// </summary>
/// <param name="columnCount"></param>
/// <returns></returns>
public static StringAligner StringAligner(this int columnCount)
{
var stringAligner = new StringAligner();
for(var i = 0; i < columnCount; i++)
stringAligner.AddFloatingColumn(" ");
return stringAligner;
}
internal static int BeginMatch(string a, string b)
{
for(var i = 0;; i++)
if(i >= a.Length || i >= b.Length || a[i] != b[i])
return i;
}
static string HexDumpFiller(int i, int length)
{
(length < 16).Assert();
if(0 == length)
return "target[]";
if(i == 0)
return "target[";
if(i == length)
return "]";
if(i % 4 == 0)
return " ";
return "";
}
}
| |
// Copyright (c) 2016 Framefield. All rights reserved.
// Released under the MIT license. (see LICENSE.txt)
using System;
using System.Collections.Generic;
using System.Linq;
using Framefield.Autodesk.FBX;
using Framefield.Core;
using Framefield.Core.Commands;
using Mesh = Framefield.Autodesk.FBX.Mesh;
namespace Framefield.Tooll.Utils
{
public class ImportFbxScene
{
public void ImportFbxAsOperator()
{
var filename = UIHelper.PickFileWithDialog(".", ".", "Select Fbx");
if (!filename.Any())
return;
var scene = Importer.Import(filename, includeTransformMatrix:false);
if (scene == null)
return;
List<Node> roots = scene.CreateAsTrees();
if (roots.Count == 0)
return;
var cgv = App.Current.MainWindow.CompositionView.CompositionGraphView;
var targetOp = cgv.CompositionOperator;
var posX = cgv.ScreenCenter.X;
var posY = cgv.ScreenCenter.Y;
var tmpX = posX;
var importFbxCommandList = new List<ICommand>();
for (var i = 1; i < roots.Count; ++i)
{
BuildTree(targetOp, importFbxCommandList, null, null, roots[i], tmpX, posY, "");
tmpX += TreeWidth(roots[i]);
}
BuildTree(targetOp, importFbxCommandList, null, null, roots[0], posX, posY + 2 * CompositionGraphView.GRID_SIZE, filename.Split('/').Last());
var importFbxSceneCommand = new MacroCommand("ImportFbxSceneCommand", importFbxCommandList);
App.Current.UndoRedoStack.Add(importFbxSceneCommand);
App.Current.UpdateRequiredAfterUserInteraction = true;
}
private void BuildTree(Operator fbxOp, List<ICommand> importFbxCommandList, Operator parent, OperatorPart input, Node node, double x, double y, string rootName = "")
{
Guid metaIDToAdd = GetIDOfNode(node);
var newOpName = "";
if (node is Group)
{
newOpName = "+ " + node.Name;
}
else if (node is Transform)
{
newOpName = "Transform";
}
else if (node is TransformMatrix)
{
newOpName = "TransformMatrix";
}
else if (node is Material)
{
newOpName = "Material";
}
else
{
newOpName = node.Name;
}
if (parent == null)
{
newOpName += rootName;
}
var addOperatorCommand = new AddOperatorCommand(fbxOp, metaIDToAdd, x, y, TreeWidth(node),true,newOpName);
importFbxCommandList.Add(addOperatorCommand);
addOperatorCommand.Do();
var newOp = (from o in fbxOp.InternalOps
where addOperatorCommand.AddedInstanceID == o.ID
select o).Single();
SetupValues(newOp, node);
if (input != null)
{
var newConnection = new MetaConnection(newOp.ID, newOp.Outputs[0].ID,
parent == null ? Guid.Empty : parent.ID, input.ID);
var firstOccuranceOfTargetOpID = fbxOp.Definition.Connections.FindIndex(con => (con.TargetOpID == newConnection.TargetOpID) &&
(con.TargetOpPartID == newConnection.TargetOpPartID));
var lastOccuranceOfTargetOpID = fbxOp.Definition.Connections.FindLastIndex(con => (con.TargetOpID == newConnection.TargetOpID) &&
(con.TargetOpPartID == newConnection.TargetOpPartID));
int index = 0;
if (firstOccuranceOfTargetOpID > -1 && lastOccuranceOfTargetOpID > -1)
index = lastOccuranceOfTargetOpID - firstOccuranceOfTargetOpID + 1;
var addConnectionCommand = new InsertConnectionCommand(fbxOp.Definition, newConnection, index);
addConnectionCommand.Do();
importFbxCommandList.Add(addConnectionCommand);
}
double childX = 0;
foreach (Node child in node.Children)
{
BuildTree(fbxOp, importFbxCommandList, newOp, newOp.Inputs[0], child, x + childX, y + CompositionGraphView.GRID_SIZE);
childX += TreeWidth(child);
}
}
private double TreeWidth(Node node)
{
if (node == null)
return 0;
if (node.Children.Count == 0)
return 100; //default op width
double width = 0;
foreach (Node child in node.Children)
width += TreeWidth(child);
return width;
}
private Guid GetIDOfNode(Node node)
{
Guid metaIDToAdd = Guid.Empty;
if (node is Group)
metaIDToAdd = Guid.Parse("46e0d20b-9ecc-42bc-ad5a-faeaf23e62f1");
else if (node is Transform)
metaIDToAdd = Guid.Parse("5f9364f8-36b4-4c1c-9cc2-5eddfa6774aa");
else if (node is Light)
metaIDToAdd = Guid.Parse("944a5d15-2485-479a-b850-519141237dd2");
else if (node is Camera)
metaIDToAdd = Guid.Parse("43403a8d-9c87-414a-89e2-9393b87d9e47");
else if (node is Mesh)
metaIDToAdd = Guid.Parse("fc2b869e-335a-4123-851c-9aecd3349a50");
else if (node is Material)
metaIDToAdd = Guid.Parse("72c0d6f1-ef64-4df6-b535-000b4b085b1e");
else if(node is TransformMatrix)
metaIDToAdd = Guid.Parse("b7a3b216-37c5-4c36-83c5-f1b823ce1d3f");
return metaIDToAdd;
}
private void SetupValues(Operator op, Node node)
{
if (node is Transform)
SetupValuesTransform(op, node as Transform);
else if (node is TransformMatrix)
SetupValuesTransformMatrix(op, node as TransformMatrix);
else if (node is Light)
SetupValuesLight(op, node as Light);
else if (node is Camera)
SetupValuesCamera(op, node as Camera);
else if (node is Mesh)
SetupValuesMesh(op, node as Mesh);
else if (node is Material)
SetupValuesMaterial(op, node as Material);
}
private void SetupValuesTransform(Operator op, Transform transform)
{
op.Inputs[1].Func = Utilities.CreateValueFunction(new Float(transform.Translation.X));
op.Inputs[2].Func = Utilities.CreateValueFunction(new Float(transform.Translation.Y));
op.Inputs[3].Func = Utilities.CreateValueFunction(new Float(transform.Translation.Z));
op.Inputs[4].Func = Utilities.CreateValueFunction(new Float(transform.Rotation.X));
op.Inputs[5].Func = Utilities.CreateValueFunction(new Float(transform.Rotation.Y));
op.Inputs[6].Func = Utilities.CreateValueFunction(new Float(transform.Rotation.Z));
op.Inputs[7].Func = Utilities.CreateValueFunction(new Float(transform.Scale.X));
op.Inputs[8].Func = Utilities.CreateValueFunction(new Float(transform.Scale.Y));
op.Inputs[9].Func = Utilities.CreateValueFunction(new Float(transform.Scale.Z));
op.Inputs[10].Func = Utilities.CreateValueFunction(new Float(transform.Pivot.X));
op.Inputs[11].Func = Utilities.CreateValueFunction(new Float(transform.Pivot.Y));
op.Inputs[12].Func = Utilities.CreateValueFunction(new Float(transform.Pivot.Z));
}
private void SetupValuesTransformMatrix(Operator op, TransformMatrix matrix)
{
op.Inputs[1].Func = Utilities.CreateValueFunction(new Float(matrix.Row0.X));
op.Inputs[2].Func = Utilities.CreateValueFunction(new Float(matrix.Row0.Y));
op.Inputs[3].Func = Utilities.CreateValueFunction(new Float(matrix.Row0.Z));
op.Inputs[4].Func = Utilities.CreateValueFunction(new Float(matrix.Row0.W));
op.Inputs[5].Func = Utilities.CreateValueFunction(new Float(matrix.Row1.X));
op.Inputs[6].Func = Utilities.CreateValueFunction(new Float(matrix.Row1.Y));
op.Inputs[7].Func = Utilities.CreateValueFunction(new Float(matrix.Row1.Z));
op.Inputs[8].Func = Utilities.CreateValueFunction(new Float(matrix.Row1.W));
op.Inputs[9].Func = Utilities.CreateValueFunction(new Float(matrix.Row2.X));
op.Inputs[10].Func = Utilities.CreateValueFunction(new Float(matrix.Row2.Y));
op.Inputs[11].Func = Utilities.CreateValueFunction(new Float(matrix.Row2.Z));
op.Inputs[12].Func = Utilities.CreateValueFunction(new Float(matrix.Row2.W));
op.Inputs[13].Func = Utilities.CreateValueFunction(new Float(matrix.Row3.X));
op.Inputs[14].Func = Utilities.CreateValueFunction(new Float(matrix.Row3.Y));
op.Inputs[15].Func = Utilities.CreateValueFunction(new Float(matrix.Row3.Z));
op.Inputs[16].Func = Utilities.CreateValueFunction(new Float(matrix.Row3.W));
}
private void SetupValuesLight(Operator op, Light light)
{
op.Inputs[1].Func = Utilities.CreateValueFunction(new Float(light.Position.X));
op.Inputs[2].Func = Utilities.CreateValueFunction(new Float(light.Position.Y));
op.Inputs[3].Func = Utilities.CreateValueFunction(new Float(light.Position.Z));
op.Inputs[8].Func = Utilities.CreateValueFunction(new Float(light.Color.X));
op.Inputs[9].Func = Utilities.CreateValueFunction(new Float(light.Color.Y));
op.Inputs[10].Func = Utilities.CreateValueFunction(new Float(light.Color.Z));
op.Inputs[16].Func = Utilities.CreateValueFunction(new Float((float)light.Intensity/100));
op.Inputs[17].Func = Utilities.CreateValueFunction(new Float((float)light.Intensity/100));
op.Inputs[18].Func = Utilities.CreateValueFunction(new Float((float)light.Intensity/100));
}
private void SetupValuesCamera(Operator op, Camera camera)
{
op.Inputs[1].Func = Utilities.CreateValueFunction(new Float(camera.Position.X));
op.Inputs[2].Func = Utilities.CreateValueFunction(new Float(camera.Position.Y));
op.Inputs[3].Func = Utilities.CreateValueFunction(new Float(camera.Position.Z));
op.Inputs[4].Func = Utilities.CreateValueFunction(new Float(camera.InterestPosition.X));
op.Inputs[5].Func = Utilities.CreateValueFunction(new Float(camera.InterestPosition.Y));
op.Inputs[6].Func = Utilities.CreateValueFunction(new Float(camera.InterestPosition.Z));
op.Inputs[7].Func = Utilities.CreateValueFunction(new Float(camera.Up.X));
op.Inputs[8].Func = Utilities.CreateValueFunction(new Float(camera.Up.Y));
op.Inputs[9].Func = Utilities.CreateValueFunction(new Float(camera.Up.Z));
}
private void SetupValuesMesh(Operator op, Mesh mesh)
{
op.Inputs[0].Func = Utilities.CreateValueFunction(new Text(mesh.FileName));
op.Inputs[1].Func = Utilities.CreateValueFunction(new Float(mesh.Index));
op.Inputs[3].Func = Utilities.CreateValueFunction(new Float(1));
}
private void SetupValuesMaterial(Operator op, Material material)
{
op.Inputs[1].Func = Utilities.CreateValueFunction(new Float(material.Ambient.X));
op.Inputs[2].Func = Utilities.CreateValueFunction(new Float(material.Ambient.Y));
op.Inputs[3].Func = Utilities.CreateValueFunction(new Float(material.Ambient.Z));
//op.Inputs[4].Func = Utilities.CreateValueFunction(new Float(material.Alpha));
op.Inputs[5].Func = Utilities.CreateValueFunction(new Float(material.Diffuse.X));
op.Inputs[6].Func = Utilities.CreateValueFunction(new Float(material.Diffuse.Y));
op.Inputs[7].Func = Utilities.CreateValueFunction(new Float(material.Diffuse.Z));
//op.Inputs[8].Func = Utilities.CreateValueFunction(new Float(material.Alpha));
op.Inputs[9].Func = Utilities.CreateValueFunction(new Float(material.Specular.X));
op.Inputs[10].Func = Utilities.CreateValueFunction(new Float(material.Specular.Y));
op.Inputs[11].Func = Utilities.CreateValueFunction(new Float(material.Specular.Z));
//op.Inputs[12].Func = Utilities.CreateValueFunction(new Float(material.Alpha));
op.Inputs[13].Func = Utilities.CreateValueFunction(new Float(material.Emissive.X));
op.Inputs[14].Func = Utilities.CreateValueFunction(new Float(material.Emissive.Y));
op.Inputs[15].Func = Utilities.CreateValueFunction(new Float(material.Emissive.Z));
//op.Inputs[16].Func = Utilities.CreateValueFunction(new Float(material.Alpha));
//op.Inputs[17].Func = Utilities.CreateValueFunction(new Float(material.Shininess));
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using Nini.Config;
using log4net;
using System;
using System.Reflection;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Services.UserAccountService;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenMetaverse;
namespace OpenSim.Server.Handlers.UserAccounts
{
public class UserAccountServerPostHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IUserAccountService m_UserAccountService;
private bool m_AllowCreateUser = false;
private bool m_AllowSetAccount = false;
public UserAccountServerPostHandler(IUserAccountService service)
: this(service, null) {}
public UserAccountServerPostHandler(IUserAccountService service, IConfig config) :
base("POST", "/accounts")
{
m_UserAccountService = service;
if (config != null)
{
m_AllowCreateUser = config.GetBoolean("AllowCreateUser", m_AllowCreateUser);
m_AllowSetAccount = config.GetBoolean("AllowSetAccount", m_AllowSetAccount);
}
}
protected override byte[] ProcessRequest(string path, Stream requestData,
IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
StreamReader sr = new StreamReader(requestData);
string body = sr.ReadToEnd();
sr.Close();
body = body.Trim();
// We need to check the authorization header
//httpRequest.Headers["authorization"] ...
//m_log.DebugFormat("[XXX]: query String: {0}", body);
string method = string.Empty;
try
{
Dictionary<string, object> request =
ServerUtils.ParseQueryString(body);
if (!request.ContainsKey("METHOD"))
return FailureResult();
method = request["METHOD"].ToString();
switch (method)
{
case "createuser":
if (m_AllowCreateUser)
return CreateUser(request);
else
break;
case "getaccount":
return GetAccount(request);
case "getaccounts":
return GetAccounts(request);
case "setaccount":
if (m_AllowSetAccount)
return StoreAccount(request);
else
break;
}
m_log.DebugFormat("[USER SERVICE HANDLER]: unknown method request: {0}", method);
}
catch (Exception e)
{
m_log.DebugFormat("[USER SERVICE HANDLER]: Exception in method {0}: {1}", method, e);
}
return FailureResult();
}
byte[] GetAccount(Dictionary<string, object> request)
{
UserAccount account = null;
UUID scopeID = UUID.Zero;
Dictionary<string, object> result = new Dictionary<string, object>();
if (request.ContainsKey("ScopeID") && !UUID.TryParse(request["ScopeID"].ToString(), out scopeID))
{
result["result"] = "null";
return ResultToBytes(result);
}
if (request.ContainsKey("UserID") && request["UserID"] != null)
{
UUID userID;
if (UUID.TryParse(request["UserID"].ToString(), out userID))
account = m_UserAccountService.GetUserAccount(scopeID, userID);
}
else if (request.ContainsKey("PrincipalID") && request["PrincipalID"] != null)
{
UUID userID;
if (UUID.TryParse(request["PrincipalID"].ToString(), out userID))
account = m_UserAccountService.GetUserAccount(scopeID, userID);
}
else if (request.ContainsKey("Email") && request["Email"] != null)
{
account = m_UserAccountService.GetUserAccount(scopeID, request["Email"].ToString());
}
else if (request.ContainsKey("FirstName") && request.ContainsKey("LastName") &&
request["FirstName"] != null && request["LastName"] != null)
{
account = m_UserAccountService.GetUserAccount(scopeID, request["FirstName"].ToString(), request["LastName"].ToString());
}
if (account == null)
{
result["result"] = "null";
}
else
{
result["result"] = account.ToKeyValuePairs();
}
return ResultToBytes(result);
}
byte[] GetAccounts(Dictionary<string, object> request)
{
if (!request.ContainsKey("query"))
return FailureResult();
UUID scopeID = UUID.Zero;
if (request.ContainsKey("ScopeID") && !UUID.TryParse(request["ScopeID"].ToString(), out scopeID))
return FailureResult();
string query = request["query"].ToString();
List<UserAccount> accounts = m_UserAccountService.GetUserAccounts(scopeID, query);
Dictionary<string, object> result = new Dictionary<string, object>();
if ((accounts == null) || ((accounts != null) && (accounts.Count == 0)))
{
result["result"] = "null";
}
else
{
int i = 0;
foreach (UserAccount acc in accounts)
{
Dictionary<string, object> rinfoDict = acc.ToKeyValuePairs();
result["account" + i] = rinfoDict;
i++;
}
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] StoreAccount(Dictionary<string, object> request)
{
UUID principalID = UUID.Zero;
if (request.ContainsKey("PrincipalID") && !UUID.TryParse(request["PrincipalID"].ToString(), out principalID))
return FailureResult();
UUID scopeID = UUID.Zero;
if (request.ContainsKey("ScopeID") && !UUID.TryParse(request["ScopeID"].ToString(), out scopeID))
return FailureResult();
UserAccount existingAccount = m_UserAccountService.GetUserAccount(scopeID, principalID);
if (existingAccount == null)
return FailureResult();
Dictionary<string, object> result = new Dictionary<string, object>();
if (request.ContainsKey("FirstName"))
existingAccount.FirstName = request["FirstName"].ToString();
if (request.ContainsKey("LastName"))
existingAccount.LastName = request["LastName"].ToString();
if (request.ContainsKey("Email"))
existingAccount.Email = request["Email"].ToString();
int created = 0;
if (request.ContainsKey("Created") && int.TryParse(request["Created"].ToString(), out created))
existingAccount.Created = created;
int userLevel = 0;
if (request.ContainsKey("UserLevel") && int.TryParse(request["UserLevel"].ToString(), out userLevel))
existingAccount.UserLevel = userLevel;
int userFlags = 0;
if (request.ContainsKey("UserFlags") && int.TryParse(request["UserFlags"].ToString(), out userFlags))
existingAccount.UserFlags = userFlags;
if (request.ContainsKey("UserTitle"))
existingAccount.UserTitle = request["UserTitle"].ToString();
if (!m_UserAccountService.StoreUserAccount(existingAccount))
{
m_log.ErrorFormat(
"[USER ACCOUNT SERVER POST HANDLER]: Account store failed for account {0} {1} {2}",
existingAccount.FirstName, existingAccount.LastName, existingAccount.PrincipalID);
return FailureResult();
}
result["result"] = existingAccount.ToKeyValuePairs();
return ResultToBytes(result);
}
byte[] CreateUser(Dictionary<string, object> request)
{
if (!
request.ContainsKey("FirstName")
&& request.ContainsKey("LastName")
&& request.ContainsKey("Password"))
return FailureResult();
Dictionary<string, object> result = new Dictionary<string, object>();
UUID scopeID = UUID.Zero;
if (request.ContainsKey("ScopeID") && !UUID.TryParse(request["ScopeID"].ToString(), out scopeID))
return FailureResult();
UUID principalID = UUID.Random();
if (request.ContainsKey("PrincipalID") && !UUID.TryParse(request["PrincipalID"].ToString(), out principalID))
return FailureResult();
string firstName = request["FirstName"].ToString();
string lastName = request["LastName"].ToString();
string password = request["Password"].ToString();
string email = "";
if (request.ContainsKey("Email"))
email = request["Email"].ToString();
UserAccount createdUserAccount = null;
if (m_UserAccountService is UserAccountService)
createdUserAccount
= ((UserAccountService)m_UserAccountService).CreateUser(
scopeID, principalID, firstName, lastName, password, email);
if (createdUserAccount == null)
return FailureResult();
result["result"] = createdUserAccount.ToKeyValuePairs();
return ResultToBytes(result);
}
private byte[] SuccessResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "result", "");
result.AppendChild(doc.CreateTextNode("Success"));
rootElement.AppendChild(result);
return DocToBytes(doc);
}
private byte[] FailureResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "result", "");
result.AppendChild(doc.CreateTextNode("Failure"));
rootElement.AppendChild(result);
return DocToBytes(doc);
}
private byte[] DocToBytes(XmlDocument doc)
{
MemoryStream ms = new MemoryStream();
XmlTextWriter xw = new XmlTextWriter(ms, null);
xw.Formatting = Formatting.Indented;
doc.WriteTo(xw);
xw.Flush();
return ms.ToArray();
}
private byte[] ResultToBytes(Dictionary<string, object> result)
{
string xmlString = ServerUtils.BuildXmlResponse(result);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace TestApp
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private ListViewEx.ListViewEx listViewEx1;
private System.Windows.Forms.DateTimePicker dateTimePicker1;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.CheckBox checkBoxDoubleClickActivation;
private System.Windows.Forms.TextBox textBoxComment;
private System.Windows.Forms.TextBox textBoxPassword;
private System.Windows.Forms.NumericUpDown numericUpDown1;
private System.Windows.Forms.ToolTip toolTip1;
private System.ComponentModel.IContainer components;
private Control[] Editors;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
listViewEx1.SubItemClicked += new ListViewEx.SubItemEventHandler(listViewEx1_SubItemClicked);
listViewEx1.SubItemEndEditing += new ListViewEx.SubItemEndEditingEventHandler(listViewEx1_SubItemEndEditing);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
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.dateTimePicker1 = new System.Windows.Forms.DateTimePicker();
this.textBoxComment = new System.Windows.Forms.TextBox();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.textBoxPassword = new System.Windows.Forms.TextBox();
this.numericUpDown1 = new System.Windows.Forms.NumericUpDown();
this.checkBoxDoubleClickActivation = new System.Windows.Forms.CheckBox();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.listViewEx1 = new ListViewEx.ListViewEx();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit();
this.SuspendLayout();
//
// dateTimePicker1
//
this.dateTimePicker1.Format = System.Windows.Forms.DateTimePickerFormat.Short;
this.dateTimePicker1.Location = new System.Drawing.Point(32, 56);
this.dateTimePicker1.Name = "dateTimePicker1";
this.dateTimePicker1.Size = new System.Drawing.Size(80, 20);
this.dateTimePicker1.TabIndex = 2;
this.dateTimePicker1.Visible = false;
//
// textBoxComment
//
this.textBoxComment.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.textBoxComment.Location = new System.Drawing.Point(32, 104);
this.textBoxComment.Multiline = true;
this.textBoxComment.Name = "textBoxComment";
this.textBoxComment.Size = new System.Drawing.Size(80, 16);
this.textBoxComment.TabIndex = 3;
this.textBoxComment.Text = "";
this.textBoxComment.Visible = false;
//
// comboBox1
//
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.IntegralHeight = false;
this.comboBox1.ItemHeight = 13;
this.comboBox1.Location = new System.Drawing.Point(32, 80);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(80, 21);
this.comboBox1.TabIndex = 1;
this.comboBox1.Visible = false;
//
// textBoxPassword
//
this.textBoxPassword.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.textBoxPassword.Location = new System.Drawing.Point(32, 128);
this.textBoxPassword.Name = "textBoxPassword";
this.textBoxPassword.PasswordChar = '*';
this.textBoxPassword.Size = new System.Drawing.Size(80, 20);
this.textBoxPassword.TabIndex = 4;
this.textBoxPassword.Text = "";
this.textBoxPassword.Visible = false;
//
// numericUpDown1
//
this.numericUpDown1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.numericUpDown1.Location = new System.Drawing.Point(32, 152);
this.numericUpDown1.Maximum = new System.Decimal(new int[] {
230,
0,
0,
0});
this.numericUpDown1.Minimum = new System.Decimal(new int[] {
120,
0,
0,
0});
this.numericUpDown1.Name = "numericUpDown1";
this.numericUpDown1.Size = new System.Drawing.Size(80, 20);
this.numericUpDown1.TabIndex = 5;
this.numericUpDown1.Value = new System.Decimal(new int[] {
120,
0,
0,
0});
this.numericUpDown1.Visible = false;
//
// checkBoxDoubleClickActivation
//
this.checkBoxDoubleClickActivation.Checked = true;
this.checkBoxDoubleClickActivation.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBoxDoubleClickActivation.Location = new System.Drawing.Point(8, 8);
this.checkBoxDoubleClickActivation.Name = "checkBoxDoubleClickActivation";
this.checkBoxDoubleClickActivation.Size = new System.Drawing.Size(176, 16);
this.checkBoxDoubleClickActivation.TabIndex = 6;
this.checkBoxDoubleClickActivation.Text = "DoubleClickActivation";
this.checkBoxDoubleClickActivation.CheckedChanged += new System.EventHandler(this.checkBoxDoubleClickActivation_CheckedChanged);
//
// listViewEx1
//
this.listViewEx1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listViewEx1.DoubleClickActivation = false;
this.listViewEx1.Location = new System.Drawing.Point(8, 32);
this.listViewEx1.Name = "listViewEx1";
this.listViewEx1.Size = new System.Drawing.Size(344, 168);
this.listViewEx1.TabIndex = 7;
this.listViewEx1.View = System.Windows.Forms.View.Details;
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(360, 205);
this.Controls.Add(this.checkBoxDoubleClickActivation);
this.Controls.Add(this.textBoxPassword);
this.Controls.Add(this.textBoxComment);
this.Controls.Add(this.numericUpDown1);
this.Controls.Add(this.comboBox1);
this.Controls.Add(this.dateTimePicker1);
this.Controls.Add(this.listViewEx1);
this.Name = "Form1";
this.Text = "ListViewEx Demo";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void Form1_Load(object sender, System.EventArgs e)
{
// Fill combo
comboBox1.Items.AddRange(new string[] {"Peter", "Paul", "Mary", "Jack", "Betty"});
// Add Columns
listViewEx1.Columns.Add("Birthday", 80, HorizontalAlignment.Left);
listViewEx1.Columns.Add("Name", 50, HorizontalAlignment.Left);
listViewEx1.Columns.Add("Note", 80, HorizontalAlignment.Left);
listViewEx1.Columns.Add("Password", 60, HorizontalAlignment.Left);
listViewEx1.Columns.Add("Height", 60, HorizontalAlignment.Left);
ListViewItem lvi;
// Create sample ListView data.
lvi = new ListViewItem("01.02.1964");
lvi.SubItems.Add("Peter");
lvi.SubItems.Add("");
lvi.SubItems.Add("****"); // This is what's displayed in the password column
lvi.Tag = "pwd1"; // and that's the real password
lvi.SubItems.Add("180");
this.listViewEx1.Items.Add(lvi);
lvi = new ListViewItem("12.04.1980");
lvi.SubItems.Add("Jack");
lvi.SubItems.Add("Hates sushi");
lvi.SubItems.Add("****");
lvi.Tag = "pwd2";
lvi.SubItems.Add("185");
this.listViewEx1.Items.Add(lvi);
lvi = new ListViewItem("02.06.1976");
lvi.SubItems.Add("Paul");
lvi.SubItems.Add("");
lvi.SubItems.Add("****");
lvi.Tag = "pwd3";
lvi.SubItems.Add("172");
this.listViewEx1.Items.Add(lvi);
lvi = new ListViewItem("09.01.2000");
lvi.SubItems.Add("Betty");
lvi.SubItems.Add("");
lvi.SubItems.Add("****");
lvi.Tag = "pwd4";
lvi.SubItems.Add("165");
this.listViewEx1.Items.Add(lvi);
Editors = new Control[] {
dateTimePicker1, // for column 0
comboBox1, // for column 1
textBoxComment, // for column 2
textBoxPassword, // for column 3
numericUpDown1 // for column 4
};
// Immediately accept the new value once the value of the control has changed
// (for example, the dateTimePicker and the comboBox)
dateTimePicker1.ValueChanged += new EventHandler(control_SelectedValueChanged);
comboBox1.SelectedIndexChanged += new EventHandler(control_SelectedValueChanged);
listViewEx1.DoubleClickActivation = true;
}
private void control_SelectedValueChanged(object sender, System.EventArgs e)
{
listViewEx1.EndEditing(true);
}
private void listViewEx1_SubItemClicked(object sender, ListViewEx.SubItemEventArgs e)
{
if (e.SubItem == 3) // Password field
{
// the current value (text) of the subitem is ****, so we have to provide
// the control with the actual text (that's been saved in the item's Tag property)
e.Item.SubItems[e.SubItem].Text = e.Item.Tag.ToString();
}
listViewEx1.StartEditing(Editors[e.SubItem], e.Item, e.SubItem);
}
private void listViewEx1_SubItemEndEditing(object sender, ListViewEx.SubItemEndEditingEventArgs e)
{
if (e.SubItem == 3) // Password field
{
if (e.Cancel)
{
e.DisplayText = new string(textBoxPassword.PasswordChar, e.Item.Tag.ToString().Length);
}
else
{
// in order to display a series of asterisks instead of the plain password text
// (textBox.Text _gives_ plain text, after all), we have to modify what'll get
// displayed and save the plain value somewhere else.
string plain = e.DisplayText;
e.DisplayText = new string(textBoxPassword.PasswordChar, plain.Length);
e.Item.Tag = plain;
}
}
}
private void checkBoxDoubleClickActivation_CheckedChanged(object sender, System.EventArgs e)
{
listViewEx1.DoubleClickActivation = checkBoxDoubleClickActivation.Checked;
}
private void listViewEx1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
// To show the real password (remember, the subitem's Text _is_ '*******'),
// set the tooltip to the ListViewItem's tag (that's where the password is stored)
ListViewItem item;
int idx = listViewEx1.GetSubItemAt(e.X, e.Y, out item);
if (item != null && idx == 3)
toolTip1.SetToolTip(listViewEx1, item.Tag.ToString());
else
toolTip1.SetToolTip(listViewEx1, null);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Security;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.World.Estate
{
public class EstateManagementModule : IEstateModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private delegate void LookupUUIDS(List<UUID> uuidLst);
private Scene m_scene;
private EstateTerrainXferHandler TerrainUploader;
public event ChangeDelegate OnRegionInfoChange;
public event ChangeDelegate OnEstateInfoChange;
public event MessageDelegate OnEstateMessage;
#region Packet Data Responders
private void sendDetailedEstateData(IClientAPI remote_client, UUID invoice)
{
uint sun = 0;
if (!m_scene.RegionInfo.EstateSettings.UseGlobalTime)
sun=(uint)(m_scene.RegionInfo.EstateSettings.SunPosition*1024.0) + 0x1800;
UUID estateOwner;
estateOwner = m_scene.RegionInfo.EstateSettings.EstateOwner;
if (m_scene.Permissions.IsGod(remote_client.AgentId))
estateOwner = remote_client.AgentId;
remote_client.SendDetailedEstateData(invoice,
m_scene.RegionInfo.EstateSettings.EstateName,
m_scene.RegionInfo.EstateSettings.EstateID,
m_scene.RegionInfo.EstateSettings.ParentEstateID,
GetEstateFlags(),
sun,
m_scene.RegionInfo.RegionSettings.Covenant,
m_scene.RegionInfo.EstateSettings.AbuseEmail,
estateOwner);
remote_client.SendEstateList(invoice,
(int)Constants.EstateAccessCodex.EstateManagers,
m_scene.RegionInfo.EstateSettings.EstateManagers,
m_scene.RegionInfo.EstateSettings.EstateID);
remote_client.SendEstateList(invoice,
(int)Constants.EstateAccessCodex.AccessOptions,
m_scene.RegionInfo.EstateSettings.EstateAccess,
m_scene.RegionInfo.EstateSettings.EstateID);
remote_client.SendEstateList(invoice,
(int)Constants.EstateAccessCodex.AllowedGroups,
m_scene.RegionInfo.EstateSettings.EstateGroups,
m_scene.RegionInfo.EstateSettings.EstateID);
remote_client.SendBannedUserList(invoice,
m_scene.RegionInfo.EstateSettings.EstateBans,
m_scene.RegionInfo.EstateSettings.EstateID);
}
private void estateSetRegionInfoHandler(bool blockTerraform, bool noFly, bool allowDamage, bool blockLandResell, int maxAgents, float objectBonusFactor,
int matureLevel, bool restrictPushObject, bool allowParcelChanges)
{
if (blockTerraform)
m_scene.RegionInfo.RegionSettings.BlockTerraform = true;
else
m_scene.RegionInfo.RegionSettings.BlockTerraform = false;
if (noFly)
m_scene.RegionInfo.RegionSettings.BlockFly = true;
else
m_scene.RegionInfo.RegionSettings.BlockFly = false;
if (allowDamage)
m_scene.RegionInfo.RegionSettings.AllowDamage = true;
else
m_scene.RegionInfo.RegionSettings.AllowDamage = false;
if (blockLandResell)
m_scene.RegionInfo.RegionSettings.AllowLandResell = false;
else
m_scene.RegionInfo.RegionSettings.AllowLandResell = true;
m_scene.RegionInfo.RegionSettings.AgentLimit = (byte) maxAgents;
m_scene.RegionInfo.RegionSettings.ObjectBonus = objectBonusFactor;
if (matureLevel <= 13)
m_scene.RegionInfo.RegionSettings.Maturity = 0;
else if (matureLevel <= 21)
m_scene.RegionInfo.RegionSettings.Maturity = 1;
else
m_scene.RegionInfo.RegionSettings.Maturity = 2;
if (restrictPushObject)
m_scene.RegionInfo.RegionSettings.RestrictPushing = true;
else
m_scene.RegionInfo.RegionSettings.RestrictPushing = false;
if (allowParcelChanges)
m_scene.RegionInfo.RegionSettings.AllowLandJoinDivide = true;
else
m_scene.RegionInfo.RegionSettings.AllowLandJoinDivide = false;
m_scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
sendRegionInfoPacketToAll();
}
public void setEstateTerrainBaseTexture(IClientAPI remoteClient, int corner, UUID texture)
{
if (texture == UUID.Zero)
return;
switch (corner)
{
case 0:
m_scene.RegionInfo.RegionSettings.TerrainTexture1 = texture;
break;
case 1:
m_scene.RegionInfo.RegionSettings.TerrainTexture2 = texture;
break;
case 2:
m_scene.RegionInfo.RegionSettings.TerrainTexture3 = texture;
break;
case 3:
m_scene.RegionInfo.RegionSettings.TerrainTexture4 = texture;
break;
}
m_scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
sendRegionInfoPacketToAll();
}
public void setEstateTerrainTextureHeights(IClientAPI client, int corner, float lowValue, float highValue)
{
switch (corner)
{
case 0:
m_scene.RegionInfo.RegionSettings.Elevation1SW = lowValue;
m_scene.RegionInfo.RegionSettings.Elevation2SW = highValue;
break;
case 1:
m_scene.RegionInfo.RegionSettings.Elevation1NW = lowValue;
m_scene.RegionInfo.RegionSettings.Elevation2NW = highValue;
break;
case 2:
m_scene.RegionInfo.RegionSettings.Elevation1SE = lowValue;
m_scene.RegionInfo.RegionSettings.Elevation2SE = highValue;
break;
case 3:
m_scene.RegionInfo.RegionSettings.Elevation1NE = lowValue;
m_scene.RegionInfo.RegionSettings.Elevation2NE = highValue;
break;
}
m_scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
sendRegionInfoPacketToAll();
}
private void handleCommitEstateTerrainTextureRequest(IClientAPI remoteClient)
{
sendRegionHandshakeToAll();
}
public void setRegionTerrainSettings(float WaterHeight,
float TerrainRaiseLimit, float TerrainLowerLimit,
bool UseEstateSun, bool UseFixedSun, float SunHour,
bool UseGlobal, bool EstateFixedSun, float EstateSunHour)
{
// Water Height
m_scene.RegionInfo.RegionSettings.WaterHeight = WaterHeight;
// Terraforming limits
m_scene.RegionInfo.RegionSettings.TerrainRaiseLimit = TerrainRaiseLimit;
m_scene.RegionInfo.RegionSettings.TerrainLowerLimit = TerrainLowerLimit;
// Time of day / fixed sun
m_scene.RegionInfo.RegionSettings.UseEstateSun = UseEstateSun;
m_scene.RegionInfo.RegionSettings.FixedSun = UseFixedSun;
m_scene.RegionInfo.RegionSettings.SunPosition = SunHour;
m_scene.TriggerEstateSunUpdate();
//m_log.Debug("[ESTATE]: UFS: " + UseFixedSun.ToString());
//m_log.Debug("[ESTATE]: SunHour: " + SunHour.ToString());
sendRegionInfoPacketToAll();
m_scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
}
private void handleEstateRestartSimRequest(IClientAPI remoteClient, int timeInSeconds)
{
m_scene.Restart(timeInSeconds);
}
private void handleChangeEstateCovenantRequest(IClientAPI remoteClient, UUID estateCovenantID)
{
m_scene.RegionInfo.RegionSettings.Covenant = estateCovenantID;
m_scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
}
private void handleEstateAccessDeltaRequest(IClientAPI remote_client, UUID invoice, int estateAccessType, UUID user)
{
// EstateAccessDelta handles Estate Managers, Sim Access, Sim Banlist, allowed Groups.. etc.
if (user == m_scene.RegionInfo.EstateSettings.EstateOwner)
return; // never process EO
if ((estateAccessType & 4) != 0) // User add
{
if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || m_scene.Permissions.BypassPermissions())
{
m_scene.RegionInfo.EstateSettings.AddEstateUser(user);
m_scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AccessOptions, m_scene.RegionInfo.EstateSettings.EstateAccess, m_scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & 8) != 0) // User remove
{
if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || m_scene.Permissions.BypassPermissions())
{
m_scene.RegionInfo.EstateSettings.RemoveEstateUser(user);
m_scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AccessOptions, m_scene.RegionInfo.EstateSettings.EstateAccess, m_scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & 16) != 0) // Group add
{
if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || m_scene.Permissions.BypassPermissions())
{
m_scene.RegionInfo.EstateSettings.AddEstateGroup(user);
m_scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedGroups, m_scene.RegionInfo.EstateSettings.EstateGroups, m_scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & 32) != 0) // Group remove
{
if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || m_scene.Permissions.BypassPermissions())
{
m_scene.RegionInfo.EstateSettings.RemoveEstateGroup(user);
m_scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedGroups, m_scene.RegionInfo.EstateSettings.EstateGroups, m_scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & 64) != 0) // Ban add
{
if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, false) || m_scene.Permissions.BypassPermissions())
{
EstateBan[] banlistcheck = m_scene.RegionInfo.EstateSettings.EstateBans;
bool alreadyInList = false;
for (int i = 0; i < banlistcheck.Length; i++)
{
if (user == banlistcheck[i].BannedUserID)
{
alreadyInList = true;
break;
}
}
if (!alreadyInList)
{
EstateBan item = new EstateBan();
item.BannedUserID = user;
item.EstateID = m_scene.RegionInfo.EstateSettings.EstateID;
item.BannedHostAddress = "0.0.0.0";
item.BannedHostIPMask = "0.0.0.0";
m_scene.RegionInfo.EstateSettings.AddBan(item);
m_scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
ScenePresence s = m_scene.GetScenePresence(user);
if (s != null)
{
if (!s.IsChildAgent)
{
m_scene.TeleportClientHome(user, s.ControllingClient);
}
}
}
else
{
remote_client.SendAlertMessage("User is already on the region ban list");
}
//m_scene.RegionInfo.regionBanlist.Add(Manager(user);
remote_client.SendBannedUserList(invoice, m_scene.RegionInfo.EstateSettings.EstateBans, m_scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & 128) != 0) // Ban remove
{
if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, false) || m_scene.Permissions.BypassPermissions())
{
EstateBan[] banlistcheck = m_scene.RegionInfo.EstateSettings.EstateBans;
bool alreadyInList = false;
EstateBan listitem = null;
for (int i = 0; i < banlistcheck.Length; i++)
{
if (user == banlistcheck[i].BannedUserID)
{
alreadyInList = true;
listitem = banlistcheck[i];
break;
}
}
if (alreadyInList && listitem != null)
{
m_scene.RegionInfo.EstateSettings.RemoveBan(listitem.BannedUserID);
m_scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
}
else
{
remote_client.SendAlertMessage("User is not on the region ban list");
}
//m_scene.RegionInfo.regionBanlist.Add(Manager(user);
remote_client.SendBannedUserList(invoice, m_scene.RegionInfo.EstateSettings.EstateBans, m_scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & 256) != 0) // Manager add
{
if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || m_scene.Permissions.BypassPermissions())
{
m_scene.RegionInfo.EstateSettings.AddEstateManager(user);
m_scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & 512) != 0) // Manager remove
{
if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || m_scene.Permissions.BypassPermissions())
{
m_scene.RegionInfo.EstateSettings.RemoveEstateManager(user);
m_scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
}
private void SendSimulatorBlueBoxMessage(
IClientAPI remote_client, UUID invoice, UUID senderID, UUID sessionID, string senderName, string message)
{
IDialogModule dm = m_scene.RequestModuleInterface<IDialogModule>();
if (dm != null)
dm.SendNotificationToUsersInRegion(senderID, senderName, message);
}
private void SendEstateBlueBoxMessage(
IClientAPI remote_client, UUID invoice, UUID senderID, UUID sessionID, string senderName, string message)
{
TriggerEstateMessage(senderID, senderName, message);
}
private void handleEstateDebugRegionRequest(IClientAPI remote_client, UUID invoice, UUID senderID, bool scripted, bool collisionEvents, bool physics)
{
if (physics)
m_scene.RegionInfo.RegionSettings.DisablePhysics = true;
else
m_scene.RegionInfo.RegionSettings.DisablePhysics = false;
if (scripted)
m_scene.RegionInfo.RegionSettings.DisableScripts = true;
else
m_scene.RegionInfo.RegionSettings.DisableScripts = false;
if (collisionEvents)
m_scene.RegionInfo.RegionSettings.DisableCollisions = true;
else
m_scene.RegionInfo.RegionSettings.DisableCollisions = false;
m_scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
m_scene.SetSceneCoreDebug(scripted, collisionEvents, physics);
}
private void handleEstateTeleportOneUserHomeRequest(IClientAPI remover_client, UUID invoice, UUID senderID, UUID prey)
{
if (!m_scene.Permissions.CanIssueEstateCommand(remover_client.AgentId, false))
return;
if (prey != UUID.Zero)
{
ScenePresence s = m_scene.GetScenePresence(prey);
if (s != null)
{
m_scene.TeleportClientHome(prey, s.ControllingClient);
}
}
}
private void handleEstateTeleportAllUsersHomeRequest(IClientAPI remover_client, UUID invoice, UUID senderID)
{
if (!m_scene.Permissions.CanIssueEstateCommand(remover_client.AgentId, false))
return;
m_scene.ForEachScenePresence(delegate(ScenePresence sp)
{
if (sp.UUID != senderID)
{
ScenePresence p = m_scene.GetScenePresence(sp.UUID);
// make sure they are still there, we could be working down a long list
// Also make sure they are actually in the region
if (p != null && !p.IsChildAgent)
{
m_scene.TeleportClientHome(p.UUID, p.ControllingClient);
}
}
});
}
private void AbortTerrainXferHandler(IClientAPI remoteClient, ulong XferID)
{
if (TerrainUploader != null)
{
lock (TerrainUploader)
{
if (XferID == TerrainUploader.XferID)
{
remoteClient.OnXferReceive -= TerrainUploader.XferReceive;
remoteClient.OnAbortXfer -= AbortTerrainXferHandler;
TerrainUploader.TerrainUploadDone -= HandleTerrainApplication;
TerrainUploader = null;
remoteClient.SendAlertMessage("Terrain Upload aborted by the client");
}
}
}
}
private void HandleTerrainApplication(string filename, byte[] terrainData, IClientAPI remoteClient)
{
lock (TerrainUploader)
{
remoteClient.OnXferReceive -= TerrainUploader.XferReceive;
remoteClient.OnAbortXfer -= AbortTerrainXferHandler;
TerrainUploader.TerrainUploadDone -= HandleTerrainApplication;
TerrainUploader = null;
}
remoteClient.SendAlertMessage("Terrain Upload Complete. Loading....");
IVoxelModule terr = m_scene.RequestModuleInterface<IVoxelModule>();
if (terr != null)
{
m_log.Warn("[CLIENT]: Got Request to Send Terrain in region " + m_scene.RegionInfo.RegionName);
try
{
string localfilename = "terrain.raw";
if (terrainData.Length == 851968)
{
localfilename = Path.Combine(Util.dataDir(),"terrain.raw"); // It's a .LLRAW
}
if (terrainData.Length == 196662) // 24-bit 256x256 Bitmap
localfilename = Path.Combine(Util.dataDir(), "terrain.bmp");
if (terrainData.Length == 256 * 256 * 4) // It's a .R32
localfilename = Path.Combine(Util.dataDir(), "terrain.r32");
if (terrainData.Length == 256 * 256 * 8) // It's a .R64
localfilename = Path.Combine(Util.dataDir(), "terrain.r64");
if (File.Exists(localfilename))
{
File.Delete(localfilename);
}
FileStream input = new FileStream(localfilename, FileMode.CreateNew);
input.Write(terrainData, 0, terrainData.Length);
input.Close();
FileInfo x = new FileInfo(localfilename);
terr.LoadFromFile(localfilename);
remoteClient.SendAlertMessage("Your terrain was loaded as a ." + x.Extension + " file. It may take a few moments to appear.");
}
catch (IOException e)
{
m_log.ErrorFormat("[TERRAIN]: Error Saving a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString());
remoteClient.SendAlertMessage("There was an IO Exception loading your terrain. Please check free space.");
return;
}
catch (SecurityException e)
{
m_log.ErrorFormat("[TERRAIN]: Error Saving a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString());
remoteClient.SendAlertMessage("There was a security Exception loading your terrain. Please check the security on the simulator drive");
return;
}
catch (UnauthorizedAccessException e)
{
m_log.ErrorFormat("[TERRAIN]: Error Saving a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString());
remoteClient.SendAlertMessage("There was a security Exception loading your terrain. Please check the security on the simulator drive");
return;
}
catch (Exception e)
{
m_log.ErrorFormat("[TERRAIN]: Error loading a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString());
remoteClient.SendAlertMessage("There was a general error loading your terrain. Please fix the terrain file and try again");
}
}
else
{
remoteClient.SendAlertMessage("Unable to apply terrain. Cannot get an instance of the terrain module");
}
}
private void handleUploadTerrain(IClientAPI remote_client, string clientFileName)
{
if (TerrainUploader == null)
{
TerrainUploader = new EstateTerrainXferHandler(remote_client, clientFileName);
lock (TerrainUploader)
{
remote_client.OnXferReceive += TerrainUploader.XferReceive;
remote_client.OnAbortXfer += AbortTerrainXferHandler;
TerrainUploader.TerrainUploadDone += HandleTerrainApplication;
}
TerrainUploader.RequestStartXfer(remote_client);
}
else
{
remote_client.SendAlertMessage("Another Terrain Upload is in progress. Please wait your turn!");
}
}
private void handleTerrainRequest(IClientAPI remote_client, string clientFileName)
{
// Save terrain here
IVoxelModule terr = m_scene.RequestModuleInterface<IVoxelModule>();
if (terr != null)
{
m_log.Warn("[CLIENT]: Got Request to Send Terrain in region " + m_scene.RegionInfo.RegionName);
if (File.Exists(Util.dataDir() + "/terrain.raw"))
{
File.Delete(Util.dataDir() + "/terrain.raw");
}
terr.SaveToFile(Util.dataDir() + "/terrain.raw");
FileStream input = new FileStream(Util.dataDir() + "/terrain.raw", FileMode.Open);
byte[] bdata = new byte[input.Length];
input.Read(bdata, 0, (int)input.Length);
remote_client.SendAlertMessage("Terrain file written, starting download...");
m_scene.XferManager.AddNewFile("terrain.raw", bdata);
// Tell client about it
m_log.Warn("[CLIENT]: Sending Terrain to " + remote_client.Name);
remote_client.SendInitiateDownload("terrain.raw", clientFileName);
}
}
private void HandleRegionInfoRequest(IClientAPI remote_client)
{
RegionInfoForEstateMenuArgs args = new RegionInfoForEstateMenuArgs();
args.billableFactor = m_scene.RegionInfo.EstateSettings.BillableFactor;
args.estateID = m_scene.RegionInfo.EstateSettings.EstateID;
args.maxAgents = (byte)m_scene.RegionInfo.RegionSettings.AgentLimit;
args.objectBonusFactor = (float)m_scene.RegionInfo.RegionSettings.ObjectBonus;
args.parentEstateID = m_scene.RegionInfo.EstateSettings.ParentEstateID;
args.pricePerMeter = m_scene.RegionInfo.EstateSettings.PricePerMeter;
args.redirectGridX = m_scene.RegionInfo.EstateSettings.RedirectGridX;
args.redirectGridY = m_scene.RegionInfo.EstateSettings.RedirectGridY;
args.regionFlags = GetRegionFlags();
args.simAccess = m_scene.RegionInfo.AccessLevel;
args.sunHour = (float)m_scene.RegionInfo.RegionSettings.SunPosition;
args.terrainLowerLimit = (float)m_scene.RegionInfo.RegionSettings.TerrainLowerLimit;
args.terrainRaiseLimit = (float)m_scene.RegionInfo.RegionSettings.TerrainRaiseLimit;
args.useEstateSun = m_scene.RegionInfo.RegionSettings.UseEstateSun;
args.waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight;
args.simName = m_scene.RegionInfo.RegionName;
args.regionType = m_scene.RegionInfo.RegionType;
remote_client.SendRegionInfoToEstateMenu(args);
}
private void HandleEstateCovenantRequest(IClientAPI remote_client)
{
remote_client.SendEstateCovenantInformation(m_scene.RegionInfo.RegionSettings.Covenant);
}
private void HandleLandStatRequest(int parcelID, uint reportType, uint requestFlags, string filter, IClientAPI remoteClient)
{
if (!m_scene.Permissions.CanIssueEstateCommand(remoteClient.AgentId, false))
return;
Dictionary<uint, float> SceneData = new Dictionary<uint,float>();
List<UUID> uuidNameLookupList = new List<UUID>();
if (reportType == 1)
{
SceneData = m_scene.PhysicsScene.GetTopColliders();
}
else if (reportType == 0)
{
SceneData = m_scene.SceneGraph.GetTopScripts();
}
List<LandStatReportItem> SceneReport = new List<LandStatReportItem>();
lock (SceneData)
{
foreach (uint obj in SceneData.Keys)
{
SceneObjectPart prt = m_scene.GetSceneObjectPart(obj);
if (prt != null)
{
if (prt.ParentGroup != null)
{
SceneObjectGroup sog = prt.ParentGroup;
if (sog != null)
{
LandStatReportItem lsri = new LandStatReportItem();
lsri.LocationX = sog.AbsolutePosition.X;
lsri.LocationY = sog.AbsolutePosition.Y;
lsri.LocationZ = sog.AbsolutePosition.Z;
lsri.Score = SceneData[obj];
lsri.TaskID = sog.UUID;
lsri.TaskLocalID = sog.LocalId;
lsri.TaskName = sog.GetPartName(obj);
lsri.OwnerName = "waiting";
lock (uuidNameLookupList)
uuidNameLookupList.Add(sog.OwnerID);
if (filter.Length != 0)
{
if ((lsri.OwnerName.Contains(filter) || lsri.TaskName.Contains(filter)))
{
}
else
{
continue;
}
}
SceneReport.Add(lsri);
}
}
}
}
}
remoteClient.SendLandStatReply(reportType, requestFlags, (uint)SceneReport.Count,SceneReport.ToArray());
if (uuidNameLookupList.Count > 0)
LookupUUID(uuidNameLookupList);
}
private static void LookupUUIDSCompleted(IAsyncResult iar)
{
LookupUUIDS icon = (LookupUUIDS)iar.AsyncState;
icon.EndInvoke(iar);
}
private void LookupUUID(List<UUID> uuidLst)
{
LookupUUIDS d = LookupUUIDsAsync;
d.BeginInvoke(uuidLst,
LookupUUIDSCompleted,
d);
}
private void LookupUUIDsAsync(List<UUID> uuidLst)
{
UUID[] uuidarr;
lock (uuidLst)
{
uuidarr = uuidLst.ToArray();
}
for (int i = 0; i < uuidarr.Length; i++)
{
// string lookupname = m_scene.CommsManager.UUIDNameRequestString(uuidarr[i]);
m_scene.GetUserName(uuidarr[i]);
// we drop it. It gets cached though... so we're ready for the next request.
}
}
#endregion
#region Outgoing Packets
public void sendRegionInfoPacketToAll()
{
m_scene.ForEachScenePresence(delegate(ScenePresence sp)
{
if (!sp.IsChildAgent)
HandleRegionInfoRequest(sp.ControllingClient);
});
}
public void sendRegionHandshake(IClientAPI remoteClient)
{
RegionHandshakeArgs args = new RegionHandshakeArgs();
args.isEstateManager = m_scene.RegionInfo.EstateSettings.IsEstateManager(remoteClient.AgentId);
if (m_scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero && m_scene.RegionInfo.EstateSettings.EstateOwner == remoteClient.AgentId)
args.isEstateManager = true;
args.billableFactor = m_scene.RegionInfo.EstateSettings.BillableFactor;
args.terrainStartHeight0 = (float)m_scene.RegionInfo.RegionSettings.Elevation1SW;
args.terrainHeightRange0 = (float)m_scene.RegionInfo.RegionSettings.Elevation2SW;
args.terrainStartHeight1 = (float)m_scene.RegionInfo.RegionSettings.Elevation1NW;
args.terrainHeightRange1 = (float)m_scene.RegionInfo.RegionSettings.Elevation2NW;
args.terrainStartHeight2 = (float)m_scene.RegionInfo.RegionSettings.Elevation1SE;
args.terrainHeightRange2 = (float)m_scene.RegionInfo.RegionSettings.Elevation2SE;
args.terrainStartHeight3 = (float)m_scene.RegionInfo.RegionSettings.Elevation1NE;
args.terrainHeightRange3 = (float)m_scene.RegionInfo.RegionSettings.Elevation2NE;
args.simAccess = m_scene.RegionInfo.AccessLevel;
args.waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight;
args.regionFlags = GetRegionFlags();
args.regionName = m_scene.RegionInfo.RegionName;
args.SimOwner = m_scene.RegionInfo.EstateSettings.EstateOwner;
args.terrainBase0 = UUID.Zero;
args.terrainBase1 = UUID.Zero;
args.terrainBase2 = UUID.Zero;
args.terrainBase3 = UUID.Zero;
args.terrainDetail0 = m_scene.RegionInfo.RegionSettings.TerrainTexture1;
args.terrainDetail1 = m_scene.RegionInfo.RegionSettings.TerrainTexture2;
args.terrainDetail2 = m_scene.RegionInfo.RegionSettings.TerrainTexture3;
args.terrainDetail3 = m_scene.RegionInfo.RegionSettings.TerrainTexture4;
remoteClient.SendRegionHandshake(m_scene.RegionInfo,args);
}
public void sendRegionHandshakeToAll()
{
m_scene.ForEachClient(sendRegionHandshake);
}
public void handleEstateChangeInfo(IClientAPI remoteClient, UUID invoice, UUID senderID, UInt32 parms1, UInt32 parms2)
{
if (parms2 == 0)
{
m_scene.RegionInfo.EstateSettings.UseGlobalTime = true;
m_scene.RegionInfo.EstateSettings.SunPosition = 0.0;
}
else
{
m_scene.RegionInfo.EstateSettings.UseGlobalTime = false;
m_scene.RegionInfo.EstateSettings.SunPosition = (parms2 - 0x1800)/1024.0;
}
if ((parms1 & 0x00000010) != 0)
m_scene.RegionInfo.EstateSettings.FixedSun = true;
else
m_scene.RegionInfo.EstateSettings.FixedSun = false;
if ((parms1 & 0x00008000) != 0)
m_scene.RegionInfo.EstateSettings.PublicAccess = true;
else
m_scene.RegionInfo.EstateSettings.PublicAccess = false;
if ((parms1 & 0x10000000) != 0)
m_scene.RegionInfo.EstateSettings.AllowVoice = true;
else
m_scene.RegionInfo.EstateSettings.AllowVoice = false;
if ((parms1 & 0x00100000) != 0)
m_scene.RegionInfo.EstateSettings.AllowDirectTeleport = true;
else
m_scene.RegionInfo.EstateSettings.AllowDirectTeleport = false;
if ((parms1 & 0x00800000) != 0)
m_scene.RegionInfo.EstateSettings.DenyAnonymous = true;
else
m_scene.RegionInfo.EstateSettings.DenyAnonymous = false;
if ((parms1 & 0x01000000) != 0)
m_scene.RegionInfo.EstateSettings.DenyIdentified = true;
else
m_scene.RegionInfo.EstateSettings.DenyIdentified = false;
if ((parms1 & 0x02000000) != 0)
m_scene.RegionInfo.EstateSettings.DenyTransacted = true;
else
m_scene.RegionInfo.EstateSettings.DenyTransacted = false;
if ((parms1 & 0x40000000) != 0)
m_scene.RegionInfo.EstateSettings.DenyMinors = true;
else
m_scene.RegionInfo.EstateSettings.DenyMinors = false;
m_scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
m_scene.TriggerEstateSunUpdate();
sendDetailedEstateData(remoteClient, invoice);
}
#endregion
#region IRegionModule Members
public void Initialise(Scene scene, IConfigSource source)
{
m_scene = scene;
m_scene.RegisterModuleInterface<IEstateModule>(this);
m_scene.EventManager.OnNewClient += EventManager_OnNewClient;
m_scene.EventManager.OnRequestChangeWaterHeight += changeWaterHeight;
m_scene.AddCommand(this, "set terrain texture",
"set terrain texture <number> <uuid> [<x>] [<y>]",
"Sets the terrain <number> to <uuid>, if <x> or <y> are specified, it will only " +
"set it on regions with a matching coordinate. Specify -1 in <x> or <y> to wildcard" +
" that coordinate.",
consoleSetTerrainTexture);
m_scene.AddCommand(this, "set terrain heights",
"set terrain heights <corner> <min> <max> [<x>] [<y>]",
"Sets the terrain texture heights on corner #<corner> to <min>/<max>, if <x> or <y> are specified, it will only " +
"set it on regions with a matching coordinate. Specify -1 in <x> or <y> to wildcard" +
" that coordinate. Corner # SW = 0, NW = 1, SE = 2, NE = 3.",
consoleSetTerrainHeights);
}
#region Console Commands
public void consoleSetTerrainTexture(string module, string[] args)
{
string num = args[3];
string uuid = args[4];
int x = (args.Length > 5 ? int.Parse(args[5]) : -1);
int y = (args.Length > 6 ? int.Parse(args[6]) : -1);
if (x == -1 || m_scene.RegionInfo.RegionLocX == x)
{
if (y == -1 || m_scene.RegionInfo.RegionLocY == y)
{
int corner = int.Parse(num);
UUID texture = UUID.Parse(uuid);
m_log.Debug("[ESTATEMODULE] Setting terrain textures for " + m_scene.RegionInfo.RegionName +
string.Format(" (C#{0} = {1})", corner, texture));
switch (corner)
{
case 0:
m_scene.RegionInfo.RegionSettings.TerrainTexture1 = texture;
break;
case 1:
m_scene.RegionInfo.RegionSettings.TerrainTexture2 = texture;
break;
case 2:
m_scene.RegionInfo.RegionSettings.TerrainTexture3 = texture;
break;
case 3:
m_scene.RegionInfo.RegionSettings.TerrainTexture4 = texture;
break;
}
m_scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
sendRegionInfoPacketToAll();
}
}
}
public void consoleSetTerrainHeights(string module, string[] args)
{
string num = args[3];
string min = args[4];
string max = args[5];
int x = (args.Length > 6 ? int.Parse(args[6]) : -1);
int y = (args.Length > 7 ? int.Parse(args[7]) : -1);
if (x == -1 || m_scene.RegionInfo.RegionLocX == x)
{
if (y == -1 || m_scene.RegionInfo.RegionLocY == y)
{
int corner = int.Parse(num);
float lowValue = float.Parse(min, Culture.NumberFormatInfo);
float highValue = float.Parse(max, Culture.NumberFormatInfo);
m_log.Debug("[ESTATEMODULE] Setting terrain heights " + m_scene.RegionInfo.RegionName +
string.Format(" (C{0}, {1}-{2}", corner, lowValue, highValue));
switch (corner)
{
case 0:
m_scene.RegionInfo.RegionSettings.Elevation1SW = lowValue;
m_scene.RegionInfo.RegionSettings.Elevation2SW = highValue;
break;
case 1:
m_scene.RegionInfo.RegionSettings.Elevation1NW = lowValue;
m_scene.RegionInfo.RegionSettings.Elevation2NW = highValue;
break;
case 2:
m_scene.RegionInfo.RegionSettings.Elevation1SE = lowValue;
m_scene.RegionInfo.RegionSettings.Elevation2SE = highValue;
break;
case 3:
m_scene.RegionInfo.RegionSettings.Elevation1NE = lowValue;
m_scene.RegionInfo.RegionSettings.Elevation2NE = highValue;
break;
}
m_scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
sendRegionHandshakeToAll();
}
}
}
#endregion
public void PostInitialise()
{
// Sets up the sun module based no the saved Estate and Region Settings
// DO NOT REMOVE or the sun will stop working
m_scene.TriggerEstateSunUpdate();
}
public void Close()
{
}
public string Name
{
get { return "EstateManagementModule"; }
}
public bool IsSharedModule
{
get { return false; }
}
#endregion
#region Other Functions
public void changeWaterHeight(float height)
{
setRegionTerrainSettings(height,
(float)m_scene.RegionInfo.RegionSettings.TerrainRaiseLimit,
(float)m_scene.RegionInfo.RegionSettings.TerrainLowerLimit,
m_scene.RegionInfo.RegionSettings.UseEstateSun,
m_scene.RegionInfo.RegionSettings.FixedSun,
(float)m_scene.RegionInfo.RegionSettings.SunPosition,
m_scene.RegionInfo.EstateSettings.UseGlobalTime,
m_scene.RegionInfo.EstateSettings.FixedSun,
(float)m_scene.RegionInfo.EstateSettings.SunPosition);
sendRegionInfoPacketToAll();
}
#endregion
private void EventManager_OnNewClient(IClientAPI client)
{
client.OnDetailedEstateDataRequest += sendDetailedEstateData;
client.OnSetEstateFlagsRequest += estateSetRegionInfoHandler;
// client.OnSetEstateTerrainBaseTexture += setEstateTerrainBaseTexture;
client.OnSetEstateTerrainDetailTexture += setEstateTerrainBaseTexture;
client.OnSetEstateTerrainTextureHeights += setEstateTerrainTextureHeights;
client.OnCommitEstateTerrainTextureRequest += handleCommitEstateTerrainTextureRequest;
client.OnSetRegionTerrainSettings += setRegionTerrainSettings;
client.OnEstateRestartSimRequest += handleEstateRestartSimRequest;
client.OnEstateChangeCovenantRequest += handleChangeEstateCovenantRequest;
client.OnEstateChangeInfo += handleEstateChangeInfo;
client.OnUpdateEstateAccessDeltaRequest += handleEstateAccessDeltaRequest;
client.OnSimulatorBlueBoxMessageRequest += SendSimulatorBlueBoxMessage;
client.OnEstateBlueBoxMessageRequest += SendEstateBlueBoxMessage;
client.OnEstateDebugRegionRequest += handleEstateDebugRegionRequest;
client.OnEstateTeleportOneUserHomeRequest += handleEstateTeleportOneUserHomeRequest;
client.OnEstateTeleportAllUsersHomeRequest += handleEstateTeleportAllUsersHomeRequest;
client.OnRequestTerrain += handleTerrainRequest;
client.OnUploadTerrain += handleUploadTerrain;
client.OnRegionInfoRequest += HandleRegionInfoRequest;
client.OnEstateCovenantRequest += HandleEstateCovenantRequest;
client.OnLandStatRequest += HandleLandStatRequest;
sendRegionHandshake(client);
}
public uint GetRegionFlags()
{
RegionFlags flags = RegionFlags.None;
// Fully implemented
//
if (m_scene.RegionInfo.RegionSettings.AllowDamage)
flags |= RegionFlags.AllowDamage;
if (m_scene.RegionInfo.RegionSettings.BlockTerraform)
flags |= RegionFlags.BlockTerraform;
if (!m_scene.RegionInfo.RegionSettings.AllowLandResell)
flags |= RegionFlags.BlockLandResell;
if (m_scene.RegionInfo.RegionSettings.DisableCollisions)
flags |= RegionFlags.SkipCollisions;
if (m_scene.RegionInfo.RegionSettings.DisableScripts)
flags |= RegionFlags.SkipScripts;
if (m_scene.RegionInfo.RegionSettings.DisablePhysics)
flags |= RegionFlags.SkipPhysics;
if (m_scene.RegionInfo.RegionSettings.BlockFly)
flags |= RegionFlags.NoFly;
if (m_scene.RegionInfo.RegionSettings.RestrictPushing)
flags |= RegionFlags.RestrictPushObject;
if (m_scene.RegionInfo.RegionSettings.AllowLandJoinDivide)
flags |= RegionFlags.AllowParcelChanges;
if (m_scene.RegionInfo.RegionSettings.BlockShowInSearch)
flags |= RegionFlags.BlockParcelSearch;
if (m_scene.RegionInfo.RegionSettings.FixedSun)
flags |= RegionFlags.SunFixed;
if (m_scene.RegionInfo.RegionSettings.Sandbox)
flags |= RegionFlags.Sandbox;
if (m_scene.RegionInfo.EstateSettings.AllowVoice)
flags |= RegionFlags.AllowVoice;
// Fudge these to always on, so the menu options activate
//
flags |= RegionFlags.AllowLandmark;
flags |= RegionFlags.AllowSetHome;
// TODO: SkipUpdateInterestList
// Omitted
//
// Omitted: NullLayer (what is that?)
// Omitted: SkipAgentAction (what does it do?)
return (uint)flags;
}
public uint GetEstateFlags()
{
RegionFlags flags = RegionFlags.None;
if (m_scene.RegionInfo.EstateSettings.FixedSun)
flags |= RegionFlags.SunFixed;
if (m_scene.RegionInfo.EstateSettings.PublicAccess)
flags |= (RegionFlags.PublicAllowed |
RegionFlags.ExternallyVisible);
if (m_scene.RegionInfo.EstateSettings.AllowVoice)
flags |= RegionFlags.AllowVoice;
if (m_scene.RegionInfo.EstateSettings.AllowDirectTeleport)
flags |= RegionFlags.AllowDirectTeleport;
if (m_scene.RegionInfo.EstateSettings.DenyAnonymous)
flags |= RegionFlags.DenyAnonymous;
if (m_scene.RegionInfo.EstateSettings.DenyIdentified)
flags |= RegionFlags.DenyIdentified;
if (m_scene.RegionInfo.EstateSettings.DenyTransacted)
flags |= RegionFlags.DenyTransacted;
if (m_scene.RegionInfo.EstateSettings.AbuseEmailToEstateOwner)
flags |= RegionFlags.AbuseEmailToEstateOwner;
if (m_scene.RegionInfo.EstateSettings.BlockDwell)
flags |= RegionFlags.BlockDwell;
if (m_scene.RegionInfo.EstateSettings.EstateSkipScripts)
flags |= RegionFlags.EstateSkipScripts;
if (m_scene.RegionInfo.EstateSettings.ResetHomeOnTeleport)
flags |= RegionFlags.ResetHomeOnTeleport;
if (m_scene.RegionInfo.EstateSettings.TaxFree)
flags |= RegionFlags.TaxFree;
if (m_scene.RegionInfo.EstateSettings.DenyMinors)
flags |= (RegionFlags)(1 << 30);
return (uint)flags;
}
public bool IsManager(UUID avatarID)
{
if (avatarID == m_scene.RegionInfo.EstateSettings.EstateOwner)
return true;
List<UUID> ems = new List<UUID>(m_scene.RegionInfo.EstateSettings.EstateManagers);
if (ems.Contains(avatarID))
return true;
return false;
}
protected void TriggerRegionInfoChange()
{
ChangeDelegate change = OnRegionInfoChange;
if (change != null)
change(m_scene.RegionInfo.RegionID);
}
protected void TriggerEstateInfoChange()
{
ChangeDelegate change = OnEstateInfoChange;
if (change != null)
change(m_scene.RegionInfo.RegionID);
}
protected void TriggerEstateMessage(UUID fromID, string fromName, string message)
{
MessageDelegate onmessage = OnEstateMessage;
if (onmessage != null)
onmessage(m_scene.RegionInfo.RegionID, fromID, fromName, message);
}
}
}
| |
using System;
using CslaSrd;
using CslaSrd.Properties;
namespace CslaSrd
{
/// <summary>
/// Provides an integer data type that understands the concept
/// of an empty value.
/// </summary>
/// <remarks>
/// See Chapter 5 for a full discussion of the need for a similar
/// data type and the design choices behind it. Basically, we are
/// using the same approach to handle integers instead of dates.
/// </remarks>
[Serializable()]
public struct SmartInt64 : IComparable, ISmartField
{
private Int64 _int;
private bool _initialized;
private bool _emptyIsMax;
private string _format;
#region Constructors
/// <summary>
/// Creates a new SmartInt64 object.
/// </summary>
/// <param name="emptyIsMin">Indicates whether an empty int is the min or max int value.</param>
public SmartInt64(bool emptyIsMin)
{
_emptyIsMax = !emptyIsMin;
_format = null;
_initialized = false;
// provide a dummy value to allow real initialization
_int = Int64.MinValue;
if (!_emptyIsMax)
Int = Int64.MinValue;
else
Int = Int64.MaxValue;
}
/// <summary>
/// Creates a new SmartInt64 object.
/// </summary>
/// <remarks>
/// The SmartInt64 created will use the min possible
/// int to represent an empty int.
/// </remarks>
/// <param name="value">The initial value of the object.</param>
public SmartInt64(Int64 value)
{
_emptyIsMax = false;
_format = null;
_initialized = false;
_int = Int64.MinValue;
Int = value;
}
/// <summary>
/// Creates a new SmartInt64 object.
/// </summary>
/// <param name="value">The initial value of the object.</param>
/// <param name="emptyIsMin">Indicates whether an empty int is the min or max int value.</param>
public SmartInt64(Int64 value, bool emptyIsMin)
{
_emptyIsMax = !emptyIsMin;
_format = null;
_initialized = false;
_int = Int64.MinValue;
Int = value;
}
/// <summary>
/// Creates a new SmartInt64 object.
/// </summary>
/// <remarks>
/// The SmartInt64 created will use the min possible
/// int to represent an empty int.
/// </remarks>
/// <param name="value">The initial value of the object (as text).</param>
public SmartInt64(string value)
{
_emptyIsMax = false;
_format = null;
_initialized = true;
_int = Int64.MinValue;
this.Text = value;
}
/// <summary>
/// Creates a new SmartInt64 object.
/// </summary>
/// <param name="value">The initial value of the object (as text).</param>
/// <param name="emptyIsMin">Indicates whether an empty int is the min or max int value.</param>
public SmartInt64(string value, bool emptyIsMin)
{
_emptyIsMax = !emptyIsMin;
_format = null;
_initialized = true;
_int = Int64.MinValue;
this.Text = value;
}
#endregion
#region Text Support
/// <summary>
/// Gets or sets the format string used to format a int
/// value when it is returned as text.
/// </summary>
/// <remarks>
/// The format string should follow the requirements for the
/// .NET <see cref="System.String.Format"/> statement.
/// </remarks>
/// <value>A format string.</value>
public string FormatString
{
get
{
if (_format == null)
_format = "d";
return _format;
}
set
{
_format = value;
}
}
/// <summary>
/// Gets or sets the int value.
/// </summary>
/// <remarks>
/// <para>
/// This property can be used to set the int value by passing a
/// text representation of the int. Any text int representation
/// that can be parsed by the .NET runtime is valid.
/// </para><para>
/// When the int value is retrieved via this property, the text
/// is formatted by using the format specified by the
/// <see cref="FormatString" /> property. The default is the
/// short int format (d).
/// </para>
/// </remarks>
public string Text
{
get { return IntToString(this.Int, FormatString, !_emptyIsMax); }
set { this.Int = StringToInt(value, !_emptyIsMax); }
}
#endregion
#region Int Support
/// <summary>
/// Gets a value indicating whether this object contains an empy value.
/// </summary>
/// <returns>True if the value is empty.</returns>
public bool HasNullValue()
{
return !_initialized;
}
/// <summary>
/// Gets or sets the int value.
/// </summary>
public Int64 Int
{
get
{
if (!_initialized)
{
_int = Int64.MinValue;
_initialized = true;
}
return _int;
}
set
{
_int = value;
_initialized = true;
}
}
#endregion
#region System.Object overrides
/// <summary>
/// Returns a text representation of the int value.
/// </summary>
public override string ToString()
{
return this.Text;
}
/// <summary>
/// Compares this object to another <see cref="SmartInt64"/>
/// for equality.
/// </summary>
public override bool Equals(object obj)
{
if (obj is SmartInt64)
{
SmartInt64 tmp = (SmartInt64)obj;
if (this.IsEmpty && tmp.IsEmpty)
return true;
else
return this.Int.Equals(tmp.Int);
}
else if (obj is Int64)
return this.Int.Equals((Int64)obj);
else if (obj is string)
return (this.CompareTo(obj.ToString()) == 0);
else
return false;
}
/// <summary>
/// Returns a hash code for this object.
/// </summary>
public override int GetHashCode()
{
return this.Int.GetHashCode();
}
#endregion
#region DBValue
/// <summary>
/// Gets a database-friendly version of the int value.
/// </summary>
/// <remarks>
/// <para>
/// If the SmartInt64 contains an empty int, this returns <see cref="DBNull"/>.
/// Otherwise the actual int value is returned as type Int.
/// </para><para>
/// This property is very useful when setting parameter values for
/// a Command object, since it automatically stores null values into
/// the database for empty int values.
/// </para><para>
/// When you also use the SafeDataReader and its GetSmartInt64 method,
/// you can easily read a null value from the database back into a
/// SmartInt64 object so it remains considered as an empty int value.
/// </para>
/// </remarks>
public object DBValue
{
get
{
if (this.IsEmpty)
return DBNull.Value;
else
return this.Int;
}
}
#endregion
#region Empty Ints
/// <summary>
/// Gets a value indicating whether this object contains an empty int.
/// </summary>
public bool IsEmpty
{
get
{
if (!_emptyIsMax)
return this.Int.Equals(Int64.MinValue);
else
return this.Int.Equals(Int64.MaxValue);
}
}
/// <summary>
/// Gets a value indicating whether an empty int is the
/// min or max possible int value.
/// </summary>
/// <remarks>
/// Whether an empty int is considered to be the smallest or largest possible
/// int is only important for comparison operations. This allows you to
/// compare an empty int with a real int and get a meaningful result.
/// </remarks>
public bool EmptyIsMin
{
get { return !_emptyIsMax; }
}
#endregion
#region Conversion Functions
/// <summary>
/// Converts a string value into a SmartInt64.
/// </summary>
/// <param name="value">String containing the int value.</param>
/// <returns>A new SmartInt64 containing the int value.</returns>
/// <remarks>
/// EmptyIsMin will default to <see langword="true"/>.
/// </remarks>
public static SmartInt64 Parse(string value)
{
return new SmartInt64(value);
}
/// <summary>
/// Converts a string value into a SmartInt64.
/// </summary>
/// <param name="value">String containing the int value.</param>
/// <param name="emptyIsMin">Indicates whether an empty int is the min or max int value.</param>
/// <returns>A new SmartInt64 containing the int value.</returns>
public static SmartInt64 Parse(string value, bool emptyIsMin)
{
return new SmartInt64(value, emptyIsMin);
}
/// <summary>
/// Converts a text int representation into a Int value.
/// </summary>
/// <remarks>
/// An empty string is assumed to represent an empty int. An empty int
/// is returned as the MinValue of the Int datatype.
/// </remarks>
/// <param name="value">The text representation of the int.</param>
/// <returns>A Int value.</returns>
public static Int64 StringToInt(string value)
{
return StringToInt(value, true);
}
/// <summary>
/// Converts a text int representation into a Int value.
/// </summary>
/// <remarks>
/// An empty string is assumed to represent an empty int. An empty int
/// is returned as the MinValue or MaxValue of the Int datatype depending
/// on the EmptyIsMin parameter.
/// </remarks>
/// <param name="value">The text representation of the int.</param>
/// <param name="emptyIsMin">Indicates whether an empty int is the min or max int value.</param>
/// <returns>A Int value.</returns>
public static Int64 StringToInt(string value, bool emptyIsMin)
{
Int64 tmp;
if (String.IsNullOrEmpty(value))
{
if (emptyIsMin)
return Int64.MinValue;
else
return Int64.MaxValue;
}
else if (Int64.TryParse(value, out tmp))
return tmp;
else
{
string lint = value.Trim().ToLower();
throw new ArgumentException(Resources.StringToInt64Exception);
}
}
/// <summary>
/// Converts a int value into a text representation.
/// </summary>
/// <remarks>
/// The int is considered empty if it matches the min value for
/// the Int datatype. If the int is empty, this
/// method returns an empty string. Otherwise it returns the int
/// value formatted based on the FormatString parameter.
/// </remarks>
/// <param name="value">The int value to convert.</param>
/// <param name="formatString">The format string used to format the int into text.</param>
/// <returns>Text representation of the int value.</returns>
public static string IntToString(Int64 value, string formatString)
{
return IntToString(value, formatString, true);
}
/// <summary>
/// Converts a int value into a text representation.
/// </summary>
/// <remarks>
/// Whether the int value is considered empty is determined by
/// the EmptyIsMin parameter value. If the int is empty, this
/// method returns an empty string. Otherwise it returns the int
/// value formatted based on the FormatString parameter.
/// </remarks>
/// <param name="value">The int value to convert.</param>
/// <param name="formatString">The format string used to format the int into text.</param>
/// <param name="emptyIsMin">Indicates whether an empty int is the min or max int value.</param>
/// <returns>Text representation of the int value.</returns>
public static string IntToString(
Int64 value, string formatString, bool emptyIsMin)
{
if (emptyIsMin && value == Int64.MinValue)
return string.Empty;
else if (!emptyIsMin && value == Int64.MaxValue)
return string.Empty;
else
return string.Format("{0:" + formatString + "}", value);
}
#endregion
#region Manipulation Functions
/// <summary>
/// Compares one SmartInt64 to another.
/// </summary>
/// <remarks>
/// This method works the same as the <see cref="int.CompareTo"/> method
/// on the Int inttype, with the exception that it
/// understands the concept of empty int values.
/// </remarks>
/// <param name="value">The int to which we are being compared.</param>
/// <returns>A value indicating if the comparison int is less than, equal to or greater than this int.</returns>
public int CompareTo(SmartInt64 value)
{
if (this.IsEmpty && value.IsEmpty)
return 0;
else
return _int.CompareTo(value.Int);
}
/// <summary>
/// Compares one SmartInt64 to another.
/// </summary>
/// <remarks>
/// This method works the same as the <see cref="int.CompareTo"/> method
/// on the Int inttype, with the exception that it
/// understands the concept of empty int values.
/// </remarks>
/// <param name="value">The int to which we are being compared.</param>
/// <returns>A value indicating if the comparison int is less than, equal to or greater than this int.</returns>
int IComparable.CompareTo(object value)
{
if (value is SmartInt64)
return CompareTo((SmartInt64)value);
else
throw new ArgumentException(Resources.ValueNotSmartInt64Exception);
}
/// <summary>
/// Compares a SmartInt64 to a text int value.
/// </summary>
/// <param name="value">The int to which we are being compared.</param>
/// <returns>A value indicating if the comparison int is less than, equal to or greater than this int.</returns>
public int CompareTo(string value)
{
return this.Int.CompareTo(StringToInt(value, !_emptyIsMax));
}
/// <summary>
/// Compares a SmartInt64 to a int value.
/// </summary>
/// <param name="value">The int to which we are being compared.</param>
/// <returns>A value indicating if the comparison int is less than, equal to or greater than this int.</returns>
public int CompareTo(Int64 value)
{
return this.Int.CompareTo(value);
}
/// <summary>
/// Adds an integer value onto the object.
/// </summary>
public Int64 Add(Int64 value)
{
if (IsEmpty)
return this.Int;
else
return (Int64)(this.Int + value);
}
/// <summary>
/// Subtracts an integer value from the object.
/// </summary>
public Int64 Subtract(Int64 value)
{
if (IsEmpty)
return this.Int;
else
return (Int64)(this.Int - value);
}
#endregion
#region Operators
/// <summary>
/// Compares two of this type of object for equality.
/// </summary>
/// <param name="obj1">The first object to compare</param>
/// <param name="obj2">The second object to compare</param>
/// <returns>Whether the object values are equal</returns>
public static bool operator ==(SmartInt64 obj1, SmartInt64 obj2)
{
return obj1.Equals(obj2);
}
/// <summary>
/// Checks two of this type of object for non-equality.
/// </summary>
/// <param name="obj1">The first object to compare</param>
/// <param name="obj2">The second object to compare</param>
/// <returns>Whether the two values are not equal</returns>
public static bool operator !=(SmartInt64 obj1, SmartInt64 obj2)
{
return !obj1.Equals(obj2);
}
/// <summary>
/// Compares an object of this type with an Int64 for equality.
/// </summary>
/// <param name="obj1">The object of this type to compare</param>
/// <param name="obj2">The Int64 to compare</param>
/// <returns>Whether the two values are equal</returns>
public static bool operator ==(SmartInt64 obj1, Int64 obj2)
{
return obj1.Equals(obj2);
}
/// <summary>
/// Compares an object of this type with an Int64 for non-equality.
/// </summary>
/// <param name="obj1">The object of this type to compare</param>
/// <param name="obj2">The Int64 to compare</param>
/// <returns>Whether the two values are not equal</returns>
public static bool operator !=(SmartInt64 obj1, Int64 obj2)
{
return !obj1.Equals(obj2);
}
/// <summary>
/// Compares an object of this type with an Int64 for equality.
/// </summary>
/// <param name="obj1">The object of this type to compare</param>
/// <param name="obj2">The Int64 to compare</param>
/// <returns>Whether the two values are equal</returns>
public static bool operator ==(SmartInt64 obj1, string obj2)
{
return obj1.Equals(obj2);
}
/// <summary>
/// Compares an object of this type with an string for non-equality.
/// </summary>
/// <param name="obj1">The object of this type to compare</param>
/// <param name="obj2">The string to compare</param>
/// <returns>Whether the two values are not equal</returns>
public static bool operator !=(SmartInt64 obj1, string obj2)
{
return !obj1.Equals(obj2);
}
/// <summary>
/// Adds an object of this type to an Int64.
/// </summary>
/// <param name="start">The object of this type to add</param>
/// <param name="span">The Int64 to add</param>
/// <returns>A SmartInt64 with the sum</returns>
public static SmartInt64 operator +(SmartInt64 start, Int64 span)
{
return new SmartInt64(start.Add(span), start.EmptyIsMin);
}
/// <summary>
/// Subtracts an Int64 from an object of this type.
/// </summary>
/// <param name="start">The object of this type to be subtracted from</param>
/// <param name="span">The Int64 to subtract</param>
/// <returns>The calculated result</returns>
public static SmartInt64 operator -(SmartInt64 start, Int64 span)
{
return new SmartInt64(start.Subtract(span), start.EmptyIsMin);
}
/// <summary>
/// Subtracts an object of this type from another.
/// </summary>
/// <param name="start">The object of this type to be subtracted from</param>
/// <param name="finish">The object of this type to subtract</param>
/// <returns>The calculated result</returns>
public static Int64 operator -(SmartInt64 start, SmartInt64 finish)
{
return start.Subtract(finish.Int);
}
/// <summary>
/// Determines whether the first object of this type is greater than the second.
/// </summary>
/// <param name="obj1">The first object of this type to compare</param>
/// <param name="obj2">The second object of this type to compare</param>
/// <returns>Whether the first value is greater than the second</returns>
public static bool operator >(SmartInt64 obj1, SmartInt64 obj2)
{
return obj1.CompareTo(obj2) > 0;
}
/// <summary>
/// Determines whether the first object of this type is less than the second.
/// </summary>
/// <param name="obj1">The first object of this type to compare</param>
/// <param name="obj2">The second object of this type to compare</param>
/// <returns>Whether the first value is less than the second</returns>
public static bool operator <(SmartInt64 obj1, SmartInt64 obj2)
{
return obj1.CompareTo(obj2) < 0;
}
/// <summary>
/// Determines whether the first object of this type is greater than an Int64.
/// </summary>
/// <param name="obj1">The object of this type to compare</param>
/// <param name="obj2">The Int64 to compare</param>
/// <returns>Whether the first value is greater than the second</returns>
public static bool operator >(SmartInt64 obj1, Int64 obj2)
{
return obj1.CompareTo(obj2) > 0;
}
/// <summary>
/// Determines whether the first object of this type is less than an Int64.
/// </summary>
/// <param name="obj1">The object of this type to compare</param>
/// <param name="obj2">The Int64 to compare</param>
/// <returns>Whether the first value is less than the second</returns>
public static bool operator <(SmartInt64 obj1, Int64 obj2)
{
return obj1.CompareTo(obj2) < 0;
}
/// <summary>
/// Determines whether the first object of this type is less than the value in a string.
/// </summary>
/// <param name="obj1">The object of this type to compare</param>
/// <param name="obj2">The string value to compare</param>
/// <returns>Whether the first value is greater than the second</returns>
public static bool operator >(SmartInt64 obj1, string obj2)
{
return obj1.CompareTo(obj2) > 0;
}
/// <summary>
/// Determines whether the first object of this type is less than the value in a string.
/// </summary>
/// <param name="obj1">The object of this type to compare</param>
/// <param name="obj2">The string value to compare</param>
/// <returns>Whether the first value is less than the second</returns>
public static bool operator <(SmartInt64 obj1, string obj2)
{
return obj1.CompareTo(obj2) < 0;
}
/// <summary>
/// Determines whether the first object of this type is greater than or equal to the second.
/// </summary>
/// <param name="obj1">The first object of this type to compare</param>
/// <param name="obj2">The second object of this type to compare</param>
/// <returns>Whether the first value is greater than or equal to the second</returns>
public static bool operator >=(SmartInt64 obj1, SmartInt64 obj2)
{
return obj1.CompareTo(obj2) >= 0;
}
/// <summary>
/// Determines whether the first object of this type is less than or equal to the second.
/// </summary>
/// <param name="obj1">The first object of this type to compare</param>
/// <param name="obj2">The second object of this type to compare</param>
/// <returns>Whether the first value is less than or equal to the second</returns>
public static bool operator <=(SmartInt64 obj1, SmartInt64 obj2)
{
return obj1.CompareTo(obj2) <= 0;
}
/// <summary>
/// Determines whether the first object of this type is greater than or equal to an Int64.
/// </summary>
/// <param name="obj1">The object of this type to compare</param>
/// <param name="obj2">The Int64 to compare</param>
/// <returns>Whether the first value is greater than or equal to the second</returns>
public static bool operator >=(SmartInt64 obj1, Int64 obj2)
{
return obj1.CompareTo(obj2) >= 0;
}
/// <summary>
/// Determines whether the first object of this type is less than or equal to an Int64.
/// </summary>
/// <param name="obj1">The object of this type to compare</param>
/// <param name="obj2">The Int64 to compare</param>
/// <returns>Whether the first value is less than or equal to the second</returns>
public static bool operator <=(SmartInt64 obj1, Int64 obj2)
{
return obj1.CompareTo(obj2) <= 0;
}
/// <summary>
/// Determines whether the first object of this type is greater than or equal to the value of a string.
/// </summary>
/// <param name="obj1">The object of this type to compare</param>
/// <param name="obj2">The string value to compare</param>
/// <returns>Whether the first value is greater than or equal to the second</returns>
public static bool operator >=(SmartInt64 obj1, string obj2)
{
return obj1.CompareTo(obj2) >= 0;
}
/// <summary>
/// Determines whether the first object of this type is less than or equal to the value of a string.
/// </summary>
/// <param name="obj1">The object of this type to compare</param>
/// <param name="obj2">The string value to compare</param>
/// <returns>Whether the first value is less than or equal to the second</returns>
public static bool operator <=(SmartInt64 obj1, string obj2)
{
return obj1.CompareTo(obj2) <= 0;
}
#endregion
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
namespace System.Management.Automation
{
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Management.Automation.Runspaces;
using System.Collections;
/// <summary>
/// Auxiliary class to the execution of commands as needed by
/// CommandCompletion
/// </summary>
internal class CompletionExecutionHelper
{
#region Constructors
// Creates a new CompletionExecutionHelper with the PowerShell instance that will be used to execute the tab expansion commands
// Used by the ISE
internal CompletionExecutionHelper(PowerShell powershell)
{
if (powershell == null)
{
throw PSTraceSource.NewArgumentNullException("powershell");
}
this.CurrentPowerShell = powershell;
}
#endregion Constructors
#region Fields and Properties
// Gets and sets a flag set to false at the beginning of each tab completion and
// set to true if a pipeline is stopped to indicate all commands should return empty matches
internal bool CancelTabCompletion { get; set; }
// Gets and sets the PowerShell instance used to run command completion commands
// Used by the ISE
internal PowerShell CurrentPowerShell { get; set; }
// Returns true if this instance is currently executing a command
internal bool IsRunning
{
get { return CurrentPowerShell.InvocationStateInfo.State == PSInvocationState.Running; }
}
// Returns true if the command executed by this instance was stopped
internal bool IsStopped
{
get { return CurrentPowerShell.InvocationStateInfo.State == PSInvocationState.Stopped; }
}
#endregion Fields and Properties
#region Command Execution
internal Collection<PSObject> ExecuteCommand(string command)
{
Exception unused;
return this.ExecuteCommand(command, true, out unused, null);
}
internal bool ExecuteCommandAndGetResultAsBool()
{
Exception exceptionThrown;
Collection<PSObject> streamResults = ExecuteCurrentPowerShell(out exceptionThrown);
if (exceptionThrown != null || streamResults == null || streamResults.Count == 0)
{
return false;
}
// we got back one or more objects.
return (streamResults.Count > 1) || (LanguagePrimitives.IsTrue(streamResults[0]));
}
internal string ExecuteCommandAndGetResultAsString()
{
Exception exceptionThrown;
Collection<PSObject> streamResults = ExecuteCurrentPowerShell(out exceptionThrown);
if (exceptionThrown != null || streamResults == null || streamResults.Count == 0)
{
return null;
}
// 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.
return SafeToString(streamResults[0]);
}
internal Collection<PSObject> ExecuteCommand(string command, bool isScript, out Exception exceptionThrown, Hashtable args)
{
Diagnostics.Assert(command != null, "caller to verify command is not null");
exceptionThrown = null;
// This flag indicates a previous call to this method had its pipeline cancelled
if (this.CancelTabCompletion)
{
return new Collection<PSObject>();
}
CurrentPowerShell.AddCommand(command);
Command cmd = new Command(command, isScript);
if (args != null)
{
foreach (DictionaryEntry arg in args)
{
cmd.Parameters.Add((string)(arg.Key), arg.Value);
}
}
Collection<PSObject> results = null;
try
{
// blocks until all results are retrieved.
//results = this.ExecuteCommand(cmd);
// If this pipeline has been stopped lets set a flag to cancel all future tab completion calls
// untill the next completion
if (this.IsStopped)
{
results = new Collection<PSObject>();
this.CancelTabCompletion = true;
}
}
catch (Exception e)
{
CommandProcessorBase.CheckForSevereException(e);
exceptionThrown = e;
}
return results;
}
internal Collection<PSObject> ExecuteCurrentPowerShell(out Exception exceptionThrown, IEnumerable input = null)
{
exceptionThrown = null;
// This flag indicates a previous call to this method had its pipeline cancelled
if (this.CancelTabCompletion)
{
return new Collection<PSObject>();
}
Collection<PSObject> results = null;
try
{
results = CurrentPowerShell.Invoke(input);
// If this pipeline has been stopped lets set a flag to cancel all future tab completion calls
// untill the next completion
if (this.IsStopped)
{
results = new Collection<PSObject>();
this.CancelTabCompletion = true;
}
}
catch (Exception e)
{
CommandProcessorBase.CheckForSevereException(e);
exceptionThrown = e;
}
finally
{
CurrentPowerShell.Commands.Clear();
}
return results;
}
#endregion Command Execution
#region Helpers
/// <summary>
/// Converts an object to a string safely...
/// </summary>
/// <param name="obj">The object to convert</param>
/// <returns>The result of the conversion...</returns>
internal static string SafeToString(object obj)
{
if (obj == null)
{
return string.Empty;
}
try
{
PSObject pso = obj as PSObject;
string result;
if (pso != null)
{
object baseObject = pso.BaseObject;
if (baseObject != null && !(baseObject is PSCustomObject))
result = baseObject.ToString();
else
result = pso.ToString();
}
else
{
result = obj.ToString();
}
return result;
}
catch (Exception e)
{
// We swallow all exceptions from command completion because we don't want the shell to crash
CommandProcessorBase.CheckForSevereException(e);
return string.Empty;
}
}
/// <summary>
/// Converts an object to a string adn, if the string is not empty, adds it to the list
/// </summary>
/// <param name="list">The list to update</param>
/// <param name="obj">The object to convert to a string...</param>
internal static void SafeAddToStringList(List<string> list, object obj)
{
if (list == null)
return;
string result = SafeToString(obj);
if (!string.IsNullOrEmpty(result))
list.Add(result);
}
#endregion Helpers
}
}
| |
// 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.ObjectModel;
using System.Diagnostics;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.ComponentInterfaces;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Microsoft.VisualStudio.Debugger.Metadata;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
/// <summary>
/// Type member expansion.
/// </summary>
/// <remarks>
/// Includes accesses to static members with instance receivers and
/// accesses to instance members with dynamic receivers.
/// </remarks>
internal sealed class MemberExpansion : Expansion
{
internal static Expansion CreateExpansion(
DkmInspectionContext inspectionContext,
TypeAndCustomInfo declaredTypeAndInfo,
DkmClrValue value,
ExpansionFlags flags,
Predicate<MemberInfo> predicate,
ResultProvider resultProvider)
{
// For members of type DynamicProperty (part of Dynamic View expansion), we want
// to expand the underlying value (not the members of the DynamicProperty type).
var type = value.Type;
var isDynamicProperty = type.GetLmrType().IsDynamicProperty();
if (isDynamicProperty)
{
Debug.Assert(!value.IsNull);
value = value.GetFieldValue("value", inspectionContext);
}
var runtimeType = type.GetLmrType();
// Primitives, enums, function pointers, and null values with a declared type that is an interface have no visible members.
Debug.Assert(!runtimeType.IsInterface || value.IsNull);
if (resultProvider.IsPrimitiveType(runtimeType) || runtimeType.IsEnum || runtimeType.IsInterface || runtimeType.IsFunctionPointer())
{
return null;
}
// As in the old C# EE, DynamicProperty members are only expandable if they have a Dynamic View expansion.
var dynamicViewExpansion = DynamicViewExpansion.CreateExpansion(inspectionContext, value, resultProvider);
if (isDynamicProperty && (dynamicViewExpansion == null))
{
return null;
}
var dynamicFlagsMap = DynamicFlagsMap.Create(declaredTypeAndInfo);
var expansions = ArrayBuilder<Expansion>.GetInstance();
// From the members, collect the fields and properties,
// separated into static and instance members.
var staticMembers = ArrayBuilder<MemberAndDeclarationInfo>.GetInstance();
var instanceMembers = ArrayBuilder<MemberAndDeclarationInfo>.GetInstance();
var appDomain = value.Type.AppDomain;
// Expand members. (Ideally, this should be done lazily.)
var allMembers = ArrayBuilder<MemberAndDeclarationInfo>.GetInstance();
var includeInherited = (flags & ExpansionFlags.IncludeBaseMembers) == ExpansionFlags.IncludeBaseMembers;
var hideNonPublic = (inspectionContext.EvaluationFlags & DkmEvaluationFlags.HideNonPublicMembers) == DkmEvaluationFlags.HideNonPublicMembers;
runtimeType.AppendTypeMembers(allMembers, predicate, declaredTypeAndInfo.Type, appDomain, includeInherited, hideNonPublic);
foreach (var member in allMembers)
{
var name = member.Name;
if (name.IsCompilerGenerated())
{
continue;
}
if (member.IsStatic)
{
staticMembers.Add(member);
}
else if (!value.IsNull)
{
instanceMembers.Add(member);
}
}
allMembers.Free();
// Public and non-public instance members.
Expansion publicInstanceExpansion;
Expansion nonPublicInstanceExpansion;
GetPublicAndNonPublicMembers(
instanceMembers,
dynamicFlagsMap,
out publicInstanceExpansion,
out nonPublicInstanceExpansion);
// Public and non-public static members.
Expansion publicStaticExpansion;
Expansion nonPublicStaticExpansion;
GetPublicAndNonPublicMembers(
staticMembers,
dynamicFlagsMap,
out publicStaticExpansion,
out nonPublicStaticExpansion);
if (publicInstanceExpansion != null)
{
expansions.Add(publicInstanceExpansion);
}
if ((publicStaticExpansion != null) || (nonPublicStaticExpansion != null))
{
var staticExpansions = ArrayBuilder<Expansion>.GetInstance();
if (publicStaticExpansion != null)
{
staticExpansions.Add(publicStaticExpansion);
}
if (nonPublicStaticExpansion != null)
{
staticExpansions.Add(nonPublicStaticExpansion);
}
Debug.Assert(staticExpansions.Count > 0);
var staticMembersExpansion = new StaticMembersExpansion(
type,
AggregateExpansion.CreateExpansion(staticExpansions));
staticExpansions.Free();
expansions.Add(staticMembersExpansion);
}
if (value.NativeComPointer != 0)
{
expansions.Add(NativeViewExpansion.Instance);
}
if (nonPublicInstanceExpansion != null)
{
expansions.Add(nonPublicInstanceExpansion);
}
// Include Results View if necessary.
if ((flags & ExpansionFlags.IncludeResultsView) != 0)
{
var resultsViewExpansion = ResultsViewExpansion.CreateExpansion(inspectionContext, value, resultProvider);
if (resultsViewExpansion != null)
{
expansions.Add(resultsViewExpansion);
}
}
if (dynamicViewExpansion != null)
{
expansions.Add(dynamicViewExpansion);
}
var result = AggregateExpansion.CreateExpansion(expansions);
expansions.Free();
return result;
}
private static void GetPublicAndNonPublicMembers(
ArrayBuilder<MemberAndDeclarationInfo> allMembers,
DynamicFlagsMap dynamicFlagsMap,
out Expansion publicExpansion,
out Expansion nonPublicExpansion)
{
var publicExpansions = ArrayBuilder<Expansion>.GetInstance();
var publicMembers = ArrayBuilder<MemberAndDeclarationInfo>.GetInstance();
var nonPublicMembers = ArrayBuilder<MemberAndDeclarationInfo>.GetInstance();
foreach (var member in allMembers)
{
if (member.BrowsableState.HasValue)
{
switch (member.BrowsableState.Value)
{
case DkmClrDebuggerBrowsableAttributeState.RootHidden:
if (publicMembers.Count > 0)
{
publicExpansions.Add(new MemberExpansion(publicMembers.ToArray(), dynamicFlagsMap));
publicMembers.Clear();
}
publicExpansions.Add(new RootHiddenExpansion(member, dynamicFlagsMap));
continue;
case DkmClrDebuggerBrowsableAttributeState.Never:
continue;
}
}
if (member.HideNonPublic && !member.IsPublic)
{
nonPublicMembers.Add(member);
}
else
{
publicMembers.Add(member);
}
}
if (publicMembers.Count > 0)
{
publicExpansions.Add(new MemberExpansion(publicMembers.ToArray(), dynamicFlagsMap));
}
publicMembers.Free();
publicExpansion = AggregateExpansion.CreateExpansion(publicExpansions);
publicExpansions.Free();
nonPublicExpansion = (nonPublicMembers.Count > 0) ?
new NonPublicMembersExpansion(
members: new MemberExpansion(nonPublicMembers.ToArray(), dynamicFlagsMap)) :
null;
nonPublicMembers.Free();
}
private readonly MemberAndDeclarationInfo[] _members;
private readonly DynamicFlagsMap _dynamicFlagsMap;
private MemberExpansion(MemberAndDeclarationInfo[] members, DynamicFlagsMap dynamicFlagsMap)
{
Debug.Assert(members != null);
Debug.Assert(members.Length > 0);
Debug.Assert(dynamicFlagsMap != null);
_members = members;
_dynamicFlagsMap = dynamicFlagsMap;
}
internal override void GetRows(
ResultProvider resultProvider,
ArrayBuilder<EvalResult> rows,
DkmInspectionContext inspectionContext,
EvalResultDataItem parent,
DkmClrValue value,
int startIndex,
int count,
bool visitAll,
ref int index)
{
int startIndex2;
int count2;
GetIntersection(startIndex, count, index, _members.Length, out startIndex2, out count2);
int offset = startIndex2 - index;
for (int i = 0; i < count2; i++)
{
rows.Add(GetMemberRow(resultProvider, inspectionContext, value, _members[i + offset], parent, _dynamicFlagsMap));
}
index += _members.Length;
}
private static EvalResult GetMemberRow(
ResultProvider resultProvider,
DkmInspectionContext inspectionContext,
DkmClrValue value,
MemberAndDeclarationInfo member,
EvalResultDataItem parent,
DynamicFlagsMap dynamicFlagsMap)
{
var memberValue = value.GetMemberValue(member, inspectionContext);
return CreateMemberDataItem(
resultProvider,
inspectionContext,
member,
memberValue,
parent,
dynamicFlagsMap,
ExpansionFlags.All);
}
/// <summary>
/// An explicit user request to bypass "Just My Code" and display
/// the inaccessible members of an instance of an imported type.
/// </summary>
private sealed class NonPublicMembersExpansion : Expansion
{
private readonly Expansion _members;
internal NonPublicMembersExpansion(Expansion members)
{
_members = members;
}
internal override void GetRows(
ResultProvider resultProvider,
ArrayBuilder<EvalResult> rows,
DkmInspectionContext inspectionContext,
EvalResultDataItem parent,
DkmClrValue value,
int startIndex,
int count,
bool visitAll,
ref int index)
{
if (InRange(startIndex, count, index))
{
rows.Add(GetRow(
inspectionContext,
value,
_members,
parent));
}
index++;
}
private static readonly ReadOnlyCollection<string> s_hiddenFormatSpecifiers = new ReadOnlyCollection<string>(new[] { "hidden" });
private static EvalResult GetRow(
DkmInspectionContext inspectionContext,
DkmClrValue value,
Expansion expansion,
EvalResultDataItem parent)
{
return new EvalResult(
ExpansionKind.NonPublicMembers,
name: Resources.NonPublicMembers,
typeDeclaringMemberAndInfo: default(TypeAndCustomInfo),
declaredTypeAndInfo: default(TypeAndCustomInfo),
useDebuggerDisplay: false,
value: value,
displayValue: null,
expansion: expansion,
childShouldParenthesize: parent.ChildShouldParenthesize,
fullName: parent.FullNameWithoutFormatSpecifiers,
childFullNamePrefixOpt: parent.ChildFullNamePrefix,
formatSpecifiers: s_hiddenFormatSpecifiers,
category: DkmEvaluationResultCategory.Data,
flags: DkmEvaluationResultFlags.ReadOnly,
editableValue: null,
inspectionContext: inspectionContext);
}
}
/// <summary>
/// A transition from an instance of a type to the type itself (for inspecting static members).
/// </summary>
private sealed class StaticMembersExpansion : Expansion
{
private readonly DkmClrType _type;
private readonly Expansion _members;
internal StaticMembersExpansion(DkmClrType type, Expansion members)
{
_type = type;
_members = members;
}
internal override void GetRows(
ResultProvider resultProvider,
ArrayBuilder<EvalResult> rows,
DkmInspectionContext inspectionContext,
EvalResultDataItem parent,
DkmClrValue value,
int startIndex,
int count,
bool visitAll,
ref int index)
{
if (InRange(startIndex, count, index))
{
rows.Add(GetRow(
resultProvider,
inspectionContext,
new TypeAndCustomInfo(_type),
value,
_members));
}
index++;
}
private static EvalResult GetRow(
ResultProvider resultProvider,
DkmInspectionContext inspectionContext,
TypeAndCustomInfo declaredTypeAndInfo,
DkmClrValue value,
Expansion expansion)
{
var fullName = resultProvider.FullNameProvider.GetClrTypeName(inspectionContext, declaredTypeAndInfo.ClrType, declaredTypeAndInfo.Info);
return new EvalResult(
ExpansionKind.StaticMembers,
name: resultProvider.StaticMembersString,
typeDeclaringMemberAndInfo: default(TypeAndCustomInfo),
declaredTypeAndInfo: declaredTypeAndInfo,
useDebuggerDisplay: false,
value: value,
displayValue: null,
expansion: expansion,
childShouldParenthesize: false,
fullName: fullName,
childFullNamePrefixOpt: fullName,
formatSpecifiers: Formatter.NoFormatSpecifiers,
category: DkmEvaluationResultCategory.Class,
flags: DkmEvaluationResultFlags.ReadOnly,
editableValue: null,
inspectionContext: inspectionContext);
}
}
internal static EvalResult CreateMemberDataItem(
ResultProvider resultProvider,
DkmInspectionContext inspectionContext,
MemberAndDeclarationInfo member,
DkmClrValue memberValue,
EvalResultDataItem parent,
DynamicFlagsMap dynamicFlagsMap,
ExpansionFlags flags)
{
var fullNameProvider = resultProvider.FullNameProvider;
var declaredType = member.Type;
var declaredTypeInfo = dynamicFlagsMap.SubstituteDynamicFlags(member.OriginalDefinitionType, DynamicFlagsCustomTypeInfo.Create(member.TypeInfo)).GetCustomTypeInfo();
string memberName;
// Considering, we're not handling the case of a member inherited from a generic base type.
var typeDeclaringMember = member.GetExplicitlyImplementedInterface(out memberName) ?? member.DeclaringType;
var typeDeclaringMemberInfo = typeDeclaringMember.IsInterface
? dynamicFlagsMap.SubstituteDynamicFlags(typeDeclaringMember.GetInterfaceListEntry(member.DeclaringType), originalDynamicFlags: default(DynamicFlagsCustomTypeInfo)).GetCustomTypeInfo()
: null;
var memberNameForFullName = fullNameProvider.GetClrValidIdentifier(inspectionContext, memberName);
var appDomain = memberValue.Type.AppDomain;
string fullName;
if (memberNameForFullName == null)
{
fullName = null;
}
else
{
memberName = memberNameForFullName;
fullName = MakeFullName(
fullNameProvider,
inspectionContext,
memberNameForFullName,
new TypeAndCustomInfo(DkmClrType.Create(appDomain, typeDeclaringMember), typeDeclaringMemberInfo), // Note: Won't include DynamicAttribute.
member.RequiresExplicitCast,
member.IsStatic,
parent);
}
return resultProvider.CreateDataItem(
inspectionContext,
memberName,
typeDeclaringMemberAndInfo: (member.IncludeTypeInMemberName || typeDeclaringMember.IsInterface) ? new TypeAndCustomInfo(DkmClrType.Create(appDomain, typeDeclaringMember), typeDeclaringMemberInfo) : default(TypeAndCustomInfo), // Note: Won't include DynamicAttribute.
declaredTypeAndInfo: new TypeAndCustomInfo(DkmClrType.Create(appDomain, declaredType), declaredTypeInfo),
value: memberValue,
useDebuggerDisplay: parent != null,
expansionFlags: flags,
childShouldParenthesize: false,
fullName: fullName,
formatSpecifiers: Formatter.NoFormatSpecifiers,
category: DkmEvaluationResultCategory.Other,
flags: memberValue.EvalFlags,
evalFlags: DkmEvaluationFlags.None);
}
private static string MakeFullName(
IDkmClrFullNameProvider fullNameProvider,
DkmInspectionContext inspectionContext,
string name,
TypeAndCustomInfo typeDeclaringMemberAndInfo,
bool memberAccessRequiresExplicitCast,
bool memberIsStatic,
EvalResultDataItem parent)
{
// If the parent is an exception thrown during evaluation,
// there is no valid fullname expression for the child.
if (parent.Value.EvalFlags.Includes(DkmEvaluationResultFlags.ExceptionThrown))
{
return null;
}
var parentFullName = parent.ChildFullNamePrefix;
if (parentFullName == null)
{
return null;
}
if (parent.ChildShouldParenthesize)
{
parentFullName = $"({parentFullName})";
}
var typeDeclaringMember = typeDeclaringMemberAndInfo.Type;
if (typeDeclaringMember.IsInterface)
{
memberAccessRequiresExplicitCast = !typeDeclaringMember.Equals(parent.DeclaredTypeAndInfo.Type);
}
return fullNameProvider.GetClrMemberName(
inspectionContext,
parentFullName,
typeDeclaringMemberAndInfo.ClrType,
typeDeclaringMemberAndInfo.Info,
name,
memberAccessRequiresExplicitCast,
memberIsStatic);
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using Dbg = System.Management.Automation;
using System.Collections;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Provider;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// This provider is the data accessor for shell variables. It uses
/// the HashtableProvider as the base class to get a hashtable as
/// a data store.
/// </summary>
[CmdletProvider(VariableProvider.ProviderName, ProviderCapabilities.ShouldProcess)]
[OutputType(typeof(PSVariable), ProviderCmdlet = ProviderCmdlet.SetItem)]
[OutputType(typeof(PSVariable), ProviderCmdlet = ProviderCmdlet.RenameItem)]
[OutputType(typeof(PSVariable), ProviderCmdlet = ProviderCmdlet.CopyItem)]
[OutputType(typeof(PSVariable), ProviderCmdlet = ProviderCmdlet.GetItem)]
[OutputType(typeof(PSVariable), ProviderCmdlet = ProviderCmdlet.NewItem)]
public sealed class VariableProvider : SessionStateProviderBase
{
/// <summary>
/// Gets the name of the provider
/// </summary>
public const string ProviderName = "Variable";
#region Constructor
/// <summary>
/// The constructor for the provider that exposes variables to the user
/// as drives.
/// </summary>
public VariableProvider()
{
} // constructor
#endregion Constructor
#region DriveCmdletProvider overrides
/// <summary>
/// Initializes the variables drive
/// </summary>
///
/// <returns>
/// An array of a single PSDriveInfo object representing the variables drive.
/// </returns>
///
protected override Collection<PSDriveInfo> InitializeDefaultDrives()
{
string description = SessionStateStrings.VariableDriveDescription;
PSDriveInfo variableDrive =
new PSDriveInfo(
DriveNames.VariableDrive,
ProviderInfo,
String.Empty,
description,
null);
Collection<PSDriveInfo> drives = new Collection<PSDriveInfo>();
drives.Add(variableDrive);
return drives;
} // InitializeDefaultDrives
#endregion DriveCmdletProvider overrides
#region protected members
/// <summary>
/// Gets a variable from session state
/// </summary>
///
/// <param name="name">
/// The name of the variable to retrieve.
/// </param>
///
/// <returns>
/// A PSVariable that represents the variable.
/// </returns>
///
internal override object GetSessionStateItem(string name)
{
Dbg.Diagnostics.Assert(
!String.IsNullOrEmpty(name),
"The caller should verify this parameter");
return (PSVariable)SessionState.Internal.GetVariable(name, Context.Origin);
} // GetSessionStateItem
/// <summary>
/// Sets the variable of the specified name to the specified value
/// </summary>
///
/// <param name="name">
/// The name of the variable to set.
/// </param>
///
/// <param name="value">
/// The new value for the variable.
/// </param>
///
/// <param name="writeItem">
/// If true, the item that was set should be written to WriteItemObject.
/// </param>
///
internal override void SetSessionStateItem(string name, object value, bool writeItem)
{
Dbg.Diagnostics.Assert(
!String.IsNullOrEmpty(name),
"The caller should verify this parameter");
PSVariable variable = null;
if (value != null)
{
variable = value as PSVariable;
if (variable == null)
{
variable = new PSVariable(name, value);
}
else
{
// ensure the name matches
if (!String.Equals(name, variable.Name, StringComparison.OrdinalIgnoreCase))
{
PSVariable newVar = new PSVariable(name, variable.Value, variable.Options, variable.Attributes);
newVar.Description = variable.Description;
variable = newVar;
}
}
}
else
{
variable = new PSVariable(name, null);
}
PSVariable item = SessionState.Internal.SetVariable(variable, Force, Context.Origin) as PSVariable;
if (writeItem && item != null)
{
WriteItemObject(item, item.Name, false);
}
} // SetSessionStateItem
/// <summary>
/// Removes the specified variable from session state.
/// </summary>
///
/// <param name="name">
/// The name of the variable to remove from session state.
/// </param>
///
internal override void RemoveSessionStateItem(string name)
{
Dbg.Diagnostics.Assert(
!String.IsNullOrEmpty(name),
"The caller should verify this parameter");
SessionState.Internal.RemoveVariable(name, Force);
} // RemoveSessionStateItem
/// <summary>
/// Gets a flattened view of the variables in session state
/// </summary>
///
/// <returns>
/// An IDictionary representing the flattened view of the variables in
/// session state.
/// </returns>
///
internal override IDictionary GetSessionStateTable()
{
return (IDictionary)SessionState.Internal.GetVariableTable();
} // GetSessionStateTable
/// <summary>
/// Gets the value of the item that is returned from GetItem by
/// extracting the PSVariable value.
/// </summary>
///
/// <param name="item">
/// The item to extract the value from.
/// </param>
///
/// <returns>
/// The value of the specified item.
/// </returns>
///
internal override object GetValueOfItem(object item)
{
Dbg.Diagnostics.Assert(
item != null,
"Caller should verify the item parameter");
// Call the base class to unwrap the DictionaryEntry
// if necessary
object value = base.GetValueOfItem(item);
PSVariable var = item as PSVariable;
if (var != null)
{
value = var.Value;
}
return value;
} // GetValueOfItem
/// <summary>
/// Determines if the item can be renamed. Derived classes that need
/// to perform a check should override this method.
/// </summary>
///
/// <param name="item">
/// The item to verify if it can be renamed.
/// </param>
///
/// <returns>
/// true if the item can be renamed or false otherwise.
/// </returns>
///
internal override bool CanRenameItem(object item)
{
bool result = false;
PSVariable variable = item as PSVariable;
if (variable != null)
{
if ((variable.Options & ScopedItemOptions.Constant) != 0 ||
((variable.Options & ScopedItemOptions.ReadOnly) != 0 && !Force))
{
SessionStateUnauthorizedAccessException e =
new SessionStateUnauthorizedAccessException(
variable.Name,
SessionStateCategory.Variable,
"CannotRenameVariable",
SessionStateStrings.CannotRenameVariable);
throw e;
}
result = true;
}
return result;
}
#endregion protected members
} // VariableProvider
}
| |
using System;
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
[ExecuteInEditMode]
[CustomEditor(typeof(Suimono.Core.fx_EffectObject))]
public class suimono_objectfx_editor : Editor {
public override void OnInspectorGUI() {
//string renName = "";
//int setRename = 0;
//int localPresetIndex = -1;
//bool showErrors = false;
//bool showPresets = false;
//bool showSplash = false;
//bool showWaves = false;
//bool showGeneral = false;
//bool showSurface = false;
//bool showUnderwater = false;
//bool showEffects = false;
//bool showColor = false;
//bool showReflect = false;
//bool showFoam = false;
Texture logoTex;
Texture divTex;
Texture divRevTex;
//Texture divVertTex;
//Texture divHorizTex;
//Texture bgPreset;
//Texture bgPresetSt;
//Texture bgPresetNd;
Color colorEnabled = new Color(1.0f,1.0f,1.0f,1.0f);
Color colorDisabled = new Color(1.0f,1.0f,1.0f,0.25f);
//Color colorEnabled = new Color(1.0f,1.0f,1.0f,1.0f);
//Color colorDisabled = new Color(1.0f,1.0f,1.0f,0.35f);
//Color highlightColor2 = new Color(0.7f,1f,0.2f,0.6f);
//Color highlightColor = new Color(1f,0.5f,0f,0.9f);
float emMin = 1.0f;
float emMax = 3.0f;
float aMin = 0.9f;
float aMax = 1.0f;
float apMin = 0.9f;
float apMax = 1.1f;
float szMin = 0.5f;
float szMax = 1.5f;
Suimono.Core.fx_EffectObject script = (Suimono.Core.fx_EffectObject) target;
Undo.RecordObject(target, "Changed Area Of Effect");
//load textures
logoTex = Resources.Load("textures/gui_tex_suimonologo") as Texture;
divTex = Resources.Load("textures/gui_tex_suimonodiv") as Texture;
divRevTex = Resources.Load("textures/gui_tex_suimonodivrev") as Texture;
//divVertTex = Resources.Load("textures/gui_tex_suimono_divvert") as Texture;
//divHorizTex = Resources.Load("textures/gui_tex_suimono_divhorz") as Texture;
//bgPreset = Resources.Load("textures/gui_bgpreset") as Texture;
//bgPresetSt = Resources.Load("textures/gui_bgpresetSt") as Texture;
//bgPresetNd = Resources.Load("textures/gui_bgpresetNd") as Texture;
#if UNITY_PRO_LICENSE
divTex = Resources.Load("textures/gui_tex_suimonodiv") as Texture;
logoTex = Resources.Load("textures/gui_tex_suimonologofx") as Texture;
//bgPreset = Resources.Load("textures/gui_bgpreset") as Texture;
//bgPresetSt = Resources.Load("textures/gui_bgpresetSt") as Texture;
//bgPresetNd = Resources.Load("textures/gui_bgpresetNd") as Texture;
//highlightColor = new Color(1f,0.5f,0f,0.9f);
#else
divTex = Resources.Load("textures/gui_tex_suimonodiv_i") as Texture;
logoTex = Resources.Load("textures/gui_tex_suimonologofx_i") as Texture;
//bgPreset = Resources.Load("textures/gui_bgpreset_i") as Texture;
//bgPresetSt = Resources.Load("textures/gui_bgpresetSt_i") as Texture;
//bgPresetNd = Resources.Load("textures/gui_bgpresetNd_i") as Texture;
//highlightColor = new Color(0.0f,0.81f,0.9f,0.6f);
#endif
//SUIMONO LOGO
GUIContent buttonText = new GUIContent("");
GUIStyle buttonStyle = GUIStyle.none;
Rect rt = GUILayoutUtility.GetRect(buttonText, buttonStyle);
int margin = 15;
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin,rt.y,387,36),logoTex);
GUILayout.Space(25.0f);
//SET TYPE
rt = GUILayoutUtility.GetRect(buttonText, buttonStyle);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin,rt.y,387,24),divTex);
//EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin,rt.y+30,387,24),divRevTex);
//if (GUI.Button(new Rect(rt.x+margin,rt.y+12,192,24),"Particle Effect")) script.typeIndex = 0;
//if (GUI.Button(new Rect(rt.x+margin+194,rt.y+12,192,24),"Audio Effect")) script.typeIndex = 1;
if (GUI.Button(new Rect(rt.x + margin, rt.y + 12, 128, 24), "Particle Effect")) script.typeIndex = 0;
if (GUI.Button(new Rect(rt.x + margin + 130, rt.y + 12, 128, 24), "Audio Effect")) script.typeIndex = 1;
if (GUI.Button(new Rect(rt.x + margin + 130 * 2, rt.y + 12, 128, 24), "Event Trigger")) script.typeIndex = 2;
GUILayout.Space(30.0f);
//SET ACTION TYPE
rt = GUILayoutUtility.GetRect(buttonText, buttonStyle);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin,rt.y,387,24),divTex);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+12, 180, 18),"Action Type");
script.actionIndex = EditorGUI.Popup(new Rect(rt.x+margin+110, rt.y+12, 260, 18),"",script.actionIndex, script.actionOptions.ToArray());
if (script.actionIndex == 0 || script.actionIndex == 2){
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+32, 90, 18),"Reset Time");
script.actionReset = EditorGUI.FloatField(new Rect(rt.x+margin+110, rt.y+32, 40, 18),"",script.actionReset);
if (script.actionIndex == 2){
EditorGUI.LabelField(new Rect(rt.x+margin+225, rt.y+32, 100, 18),"Repeat Number");
script.actionNum = EditorGUI.IntField(new Rect(rt.x+margin+325, rt.y+32, 40, 18),"",script.actionNum);
}
GUILayout.Space(20.0f);
}
GUILayout.Space(20.0f);
//SET EFFECT PARTICLE UI
if (script.typeIndex == 0){
rt = GUILayoutUtility.GetRect(buttonText, buttonStyle);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin,rt.y,387,24),divTex);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin,rt.y+139,387,24),divRevTex);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+15, 90, 18),"Particle Effect");
script.systemIndex = EditorGUI.Popup(new Rect(rt.x+margin+110, rt.y+15, 260, 18),"",script.systemIndex, script.sysNames.ToArray());
//script.systemIndex = EditorGUI.Popup(new Rect(rt.x+margin+110, rt.y+15, 260, 18),"",script.systemIndex, script.sysNames);
emMin = script.emitNum.x;
emMax = script.emitNum.y;
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+45, 130, 18),"Emit Number");
EditorGUI.MinMaxSlider(new Rect(rt.x+margin+115, rt.y+45, 200, 18), ref emMin, ref emMax, 0.0f, 20.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+340, rt.y+45, 50, 18),Mathf.Floor(emMin)+" "+Mathf.Floor(emMax));
szMin = script.effectSize.x;
szMax = script.effectSize.y;
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+65, 130, 18),"Particle Size");
EditorGUI.MinMaxSlider(new Rect(rt.x+margin+115, rt.y+65, 200, 18), ref szMin, ref szMax,0.0f,4.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+340, rt.y+65, 50, 18),szMin.ToString("F1")+" "+szMax.ToString("F1"));
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+95, 130, 18),"Emission Speed");
script.emitSpeed = EditorGUI.FloatField(new Rect(rt.x+margin+115, rt.y+95, 60, 18),"",script.emitSpeed);
EditorGUI.LabelField(new Rect(rt.x+margin+210, rt.y+95, 130, 18),"Directional Speed");
script.directionMultiplier = EditorGUI.FloatField(new Rect(rt.x+margin+320, rt.y+95, 40, 18),"",script.directionMultiplier);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+115, 130, 18),"Emit At Surface");
script.emitAtWaterLevel = EditorGUI.Toggle(new Rect(rt.x+margin+115, rt.y+114, 40, 18),"",script.emitAtWaterLevel);
EditorGUI.LabelField(new Rect(rt.x+margin+210, rt.y+115, 130, 18),"Distance Range");
script.effectDistance = EditorGUI.FloatField(new Rect(rt.x+margin+320, rt.y+114, 40, 18),"",script.effectDistance);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+135, 130, 18),"Clamp Rotation");
script.clampRot = EditorGUI.Toggle(new Rect(rt.x+margin+115, rt.y+134, 40, 18),"",script.clampRot);
EditorGUI.LabelField(new Rect(rt.x+margin+155, rt.y+135, 130, 18),"Tint Color");
script.tintCol = EditorGUI.ColorField(new Rect(rt.x+margin+225, rt.y+134, 140, 18),"",script.tintCol);
script.emitNum.x = Mathf.Floor(emMin);
script.emitNum.y = Mathf.Floor(emMax);
script.effectSize.x = szMin;
script.effectSize.y = szMax;
GUILayout.Space(150.0f);
}
//SET EFFECT AUDIO UI
if (script.typeIndex == 1){
rt = GUILayoutUtility.GetRect(buttonText, buttonStyle);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin,rt.y,387,24),divTex);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin,rt.y+139,387,24),divRevTex);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+15, 130, 18),"Select Audio Sample");
script.audioObj = EditorGUI.ObjectField(new Rect(rt.x+margin+150, rt.y+15, 220, 18), script.audioObj, typeof(AudioClip), true) as AudioClip;
aMin = script.audioVol.x;
aMax = script.audioVol.y;
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+45, 130, 18),"Audio Volume Range");
EditorGUI.MinMaxSlider(new Rect(rt.x+margin+150, rt.y+45, 230, 18), ref aMin, ref aMax,0.0f,1.0f);
apMin = script.audioPit.x;
apMax = script.audioPit.y;
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+65, 130, 18),"Audio Pitch Range");
EditorGUI.MinMaxSlider(new Rect(rt.x+margin+150, rt.y+65, 230, 18),ref apMin,ref apMax,0.0f,2.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+90, 150, 18),"Audio Repeat Speed");
script.audioSpeed = EditorGUI.FloatField(new Rect(rt.x+margin+145, rt.y+90, 60, 18),"",script.audioSpeed);
script.audioVol.x = aMin;
script.audioVol.y = aMax;
script.audioPit.x = apMin;
script.audioPit.y = apMax;
GUILayout.Space(150.0f);
}
//SET EVENT UI
if (script.typeIndex == 2){
rt = GUILayoutUtility.GetRect(buttonText, buttonStyle);
EditorGUI.DrawPreviewTexture(new Rect(rt.x + margin, rt.y, 387, 24), divTex);
EditorGUI.DrawPreviewTexture(new Rect(rt.x + margin, rt.y + 139, 387, 24), divRevTex);
GUI.contentColor = colorDisabled;
GUI.backgroundColor = colorDisabled;
EditorGUI.LabelField(new Rect(rt.x + margin + 10, rt.y + 10, 387, 18), "*Event will be triggered REGARDLESS of action type*");
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
EditorGUI.LabelField(new Rect(rt.x + margin + 30, rt.y + 30, 130, 18), "Enable Event Broadcasting");
script.enableEvents = EditorGUI.Toggle(new Rect(rt.x + margin + 10, rt.y + 30, 40, 18), "", script.enableEvents);
if (!script.enableEvents){
GUI.contentColor = colorDisabled;
GUI.backgroundColor = colorDisabled;
}
EditorGUI.LabelField(new Rect(rt.x + margin + 10, rt.y + 60, 130, 18), "Interval(sec)");
script.eventInterval = EditorGUI.FloatField(new Rect(rt.x + margin + 115, rt.y + 60, 30, 18), "", script.eventInterval);
EditorGUI.LabelField(new Rect(rt.x + margin + 10, rt.y + 80, 130, 18), "At Surface");
script.eventAtSurface = EditorGUI.Toggle(new Rect(rt.x + margin + 115, rt.y + 80, 40, 18), "", script.eventAtSurface);
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
GUILayout.Space(150.0f);
}
//SET RULES
rt = GUILayoutUtility.GetRect(buttonText, buttonStyle);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin,rt.y,387,24),divTex);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin,rt.y+89f+(script.effectRule.Length*20.0f),387f,24f),divRevTex);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+15, 387, 18),"SET ACTIVATION RULES");
if (script.effectRule.Length <= 0){
EditorGUI.LabelField(new Rect(rt.x+margin+50, rt.y+35, 387, 18),"THERE ARE CURRENTLY NO RULES TO VIEW...");
} else {
for (int rL = 0; rL < script.effectRule.Length; rL++){
if (rL < script.effectRule.Length){
if (GUI.Button(new Rect(rt.x+margin+10f,rt.y+45f+(rL * 20.0f),18f,16f),"-")){
script.DeleteRule(rL);
}
if (rL >= script.effectRule.Length) break;
EditorGUI.LabelField(new Rect(rt.x+margin+35f, rt.y+45f+(rL * 20.0f), 70f, 18f),"RULE "+(rL+1));
//-----------------
if (script.ruleIndex[rL] > 3 && script.ruleIndex[rL] < 8){
script.ruleIndex[rL] = EditorGUI.Popup(new Rect(rt.x+margin+90f, rt.y+45f+(rL * 20.0f), 246f, 18f),"",script.ruleIndex[rL], script.ruleOptions.ToArray());
script.effectData[rL] = EditorGUI.FloatField(new Rect(rt.x+margin+340f, rt.y+44f+(rL * 20.0f), 30f, 18f),"",script.effectData[rL]);
} else {
script.ruleIndex[rL] = EditorGUI.Popup(new Rect(rt.x+margin+90f, rt.y+45f+(rL * 20.0f), 280f, 18f),"",script.ruleIndex[rL], script.ruleOptions.ToArray());
}
//-----------------
GUILayout.Space(20.0f);
}
}
}
if (GUI.Button(new Rect(rt.x+margin+90f,rt.y+60f+(script.effectRule.Length*20.0f),200f,18f),"+ ADD NEW RULE")) script.AddRule();
GUILayout.Space(100.0f);
EditorUtility.SetDirty (script);
}
}
| |
// ****************************************************************
// Copyright 2002-2003, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org/?p=license&r=2.4
// ****************************************************************
using System;
using System.IO;
using System.Xml;
using System.Text.RegularExpressions;
namespace NUnit.Util
{
/// <summary>
/// The ProjectType enumerator indicates the language of the project.
/// </summary>
public enum VSProjectType
{
CSharp,
JSharp,
VisualBasic,
CPlusPlus
}
/// <summary>
/// This class allows loading information about
/// configurations and assemblies in a Visual
/// Studio project file and inspecting them.
/// Only the most common project types are
/// supported and an exception is thrown if
/// an attempt is made to load an invalid
/// file or one of an unknown type.
/// </summary>
public class VSProject
{
#region Static and Instance Variables
/// <summary>
/// VS Project extentions
/// </summary>
private static readonly string[] validExtensions = { ".csproj", ".vbproj", ".vjsproj", ".vcproj" };
/// <summary>
/// VS Solution extension
/// </summary>
private static readonly string solutionExtension = ".sln";
/// <summary>
/// Path to the file storing this project
/// </summary>
private string projectPath;
/// <summary>
/// Collection of configs for the project
/// </summary>
private VSProjectConfigCollection configs;
/// <summary>
/// The current project type
/// </summary>
private VSProjectType projectType;
/// <summary>
/// Indicates whether the project is managed code. This is
/// always true for C#, J# and VB projects but may vary in
/// the case of C++ projects.
/// </summary>
private bool isManaged;
#endregion
#region Constructor
public VSProject( string projectPath )
{
this.projectPath = Path.GetFullPath( projectPath );
configs = new VSProjectConfigCollection();
Load();
}
#endregion
#region Properties
/// <summary>
/// The name of the project.
/// </summary>
public string Name
{
get { return Path.GetFileNameWithoutExtension( projectPath ); }
}
/// <summary>
/// The path to the project
/// </summary>
public string ProjectPath
{
get { return projectPath; }
}
/// <summary>
/// Our collection of configurations
/// </summary>
public VSProjectConfigCollection Configs
{
get { return configs; }
}
/// <summary>
/// The current project type
/// </summary>
public VSProjectType ProjectType
{
get { return projectType; }
}
/// <summary>
/// Indicates whether the project is managed code. This is
/// always true for C#, J# and VB projects but may vary in
/// the case of C++ projects.
/// </summary>
public bool IsManaged
{
get { return isManaged; }
}
#endregion
#region Static Methods
public static bool IsProjectFile( string path )
{
if ( path.IndexOfAny( Path.InvalidPathChars ) >= 0 )
return false;
if ( path.ToLower().IndexOf( "http:" ) >= 0 )
return false;
string extension = Path.GetExtension( path );
foreach( string validExtension in validExtensions )
if ( extension == validExtension )
return true;
return false;
}
public static bool IsSolutionFile( string path )
{
return Path.GetExtension( path ) == solutionExtension;
}
#endregion
#region Instance Methods
private void Load()
{
if ( !IsProjectFile( projectPath ) )
ThrowInvalidFileType( projectPath );
string projectDirectory = Path.GetFullPath( Path.GetDirectoryName( projectPath ) );
StreamReader rdr = new StreamReader( projectPath, System.Text.Encoding.UTF8 );
string[] extensions = {"", ".exe", ".dll", ".lib", "" };
try
{
XmlDocument doc = new XmlDocument();
doc.Load( rdr );
string extension = Path.GetExtension( projectPath );
string assemblyName = null;
switch ( extension )
{
case ".vcproj":
this.projectType = VSProjectType.CPlusPlus;
XmlNode topNode = doc.SelectSingleNode( "/VisualStudioProject" );
XmlNode keyWordAttr = topNode.Attributes["Keyword"];
this.isManaged = keyWordAttr != null && keyWordAttr.Value == "ManagedCProj";
// TODO: This is all very hacked up... replace it.
foreach ( XmlNode configNode in doc.SelectNodes( "/VisualStudioProject/Configurations/Configuration" ) )
{
string name = RequiredAttributeValue( configNode, "Name" );
int config_type = System.Convert.ToInt32(RequiredAttributeValue(configNode, "ConfigurationType" ) );
string dirName = name;
int bar = dirName.IndexOf( '|' );
if ( bar >= 0 )
dirName = dirName.Substring( 0, bar );
string outputPath = RequiredAttributeValue( configNode, "OutputDirectory" );
outputPath = outputPath.Replace( "$(SolutionDir)", Path.GetFullPath( Path.GetDirectoryName( projectPath ) ) + Path.DirectorySeparatorChar );
outputPath = outputPath.Replace( "$(ConfigurationName)", dirName );
string outputDirectory = Path.Combine( projectDirectory, outputPath );
XmlNode toolNode = configNode.SelectSingleNode( "Tool[@Name='VCLinkerTool']" );
if ( toolNode != null )
{
assemblyName = SafeAttributeValue( toolNode, "OutputFile" );
if ( assemblyName != null )
assemblyName = Path.GetFileName( assemblyName );
else
assemblyName = Path.GetFileNameWithoutExtension(projectPath) + extensions[config_type];
}
else
{
toolNode = configNode.SelectSingleNode( "Tool[@Name='VCNMakeTool']" );
if ( toolNode != null )
assemblyName = Path.GetFileName( RequiredAttributeValue( toolNode, "Output" ) );
}
assemblyName = assemblyName.Replace( "$(OutDir)", outputPath );
assemblyName = assemblyName.Replace( "$(ProjectName)", this.Name );
VSProjectConfig config = new VSProjectConfig ( name );
if ( assemblyName != null )
config.Assemblies.Add( Path.Combine( outputDirectory, assemblyName ) );
this.configs.Add( config );
}
break;
case ".csproj":
this.projectType = VSProjectType.CSharp;
this.isManaged = true;
LoadProject( projectDirectory, doc );
break;
case ".vbproj":
this.projectType = VSProjectType.VisualBasic;
this.isManaged = true;
LoadProject( projectDirectory, doc );
break;
case ".vjsproj":
this.projectType = VSProjectType.JSharp;
this.isManaged = true;
LoadProject( projectDirectory, doc );
break;
default:
break;
}
}
catch( FileNotFoundException )
{
throw;
}
catch( Exception e )
{
ThrowInvalidFormat( projectPath, e );
}
finally
{
rdr.Close();
}
}
private bool LoadProject(string projectDirectory, XmlDocument doc)
{
bool loaded = LoadVS2003Project(projectDirectory, doc);
if (loaded) return true;
loaded = LoadMSBuildProject(projectDirectory, doc);
if (loaded) return true;
return false;
}
private bool LoadVS2003Project(string projectDirectory, XmlDocument doc)
{
XmlNode settingsNode = doc.SelectSingleNode("/VisualStudioProject/*/Build/Settings");
if (settingsNode == null)
return false;
string assemblyName = RequiredAttributeValue( settingsNode, "AssemblyName" );
string outputType = RequiredAttributeValue( settingsNode, "OutputType" );
if (outputType == "Exe" || outputType == "WinExe")
assemblyName = assemblyName + ".exe";
else
assemblyName = assemblyName + ".dll";
XmlNodeList nodes = settingsNode.SelectNodes("Config");
if (nodes != null)
foreach (XmlNode configNode in nodes)
{
string name = RequiredAttributeValue( configNode, "Name" );
string outputPath = RequiredAttributeValue( configNode, "OutputPath" );
string outputDirectory = Path.Combine(projectDirectory, outputPath);
string assemblyPath = Path.Combine(outputDirectory, assemblyName);
VSProjectConfig config = new VSProjectConfig(name);
config.Assemblies.Add(assemblyPath);
configs.Add(config);
}
return true;
}
private bool LoadMSBuildProject(string projectDirectory, XmlDocument doc)
{
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.NameTable);
namespaceManager.AddNamespace("msbuild", "http://schemas.microsoft.com/developer/msbuild/2003");
XmlNodeList nodes = doc.SelectNodes("/msbuild:Project/msbuild:PropertyGroup", namespaceManager);
if (nodes == null) return false;
XmlElement assemblyNameElement = (XmlElement)doc.SelectSingleNode("/msbuild:Project/msbuild:PropertyGroup/msbuild:AssemblyName", namespaceManager);
string assemblyName = assemblyNameElement.InnerText;
XmlElement outputTypeElement = (XmlElement)doc.SelectSingleNode("/msbuild:Project/msbuild:PropertyGroup/msbuild:OutputType", namespaceManager);
string outputType = outputTypeElement.InnerText;
if (outputType == "Exe" || outputType == "WinExe")
assemblyName = assemblyName + ".exe";
else
assemblyName = assemblyName + ".dll";
foreach (XmlElement configNode in nodes)
{
XmlAttribute conditionAttribute = configNode.Attributes["Condition"];
if (conditionAttribute == null) continue;
string condition = conditionAttribute.Value;
string configurationPrefix = " '$(Configuration)|$(Platform)' == '";
string configurationPostfix = "|AnyCPU' ";
if (!condition.StartsWith(configurationPrefix) || !condition.EndsWith(configurationPostfix))
continue;
string configurationName = condition.Substring(configurationPrefix.Length, condition.Length - configurationPrefix.Length - configurationPostfix.Length);
XmlElement outputPathElement = (XmlElement)configNode.SelectSingleNode("msbuild:OutputPath", namespaceManager);
string outputPath = outputPathElement.InnerText;
string outputDirectory = Path.Combine(projectDirectory, outputPath);
string assemblyPath = Path.Combine(outputDirectory, assemblyName);
VSProjectConfig config = new VSProjectConfig(configurationName);
config.Assemblies.Add(assemblyPath);
configs.Add(config);
}
return true;
}
private void ThrowInvalidFileType(string projectPath)
{
throw new ArgumentException(
string.Format( "Invalid project file type: {0}",
Path.GetFileName( projectPath ) ) );
}
private void ThrowInvalidFormat( string projectPath, Exception e )
{
throw new ArgumentException(
string.Format( "Invalid project file format: {0}",
Path.GetFileName( projectPath ) ), e );
}
private string SafeAttributeValue( XmlNode node, string attrName )
{
XmlNode attrNode = node.Attributes[attrName];
return attrNode == null ? null : attrNode.Value;
}
private string RequiredAttributeValue( XmlNode node, string name )
{
string result = SafeAttributeValue( node, name );
if ( result != null )
return result;
throw new ApplicationException( "Missing required attribute " + name );
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using FluentAssertions;
using JsonApiDotNetCore.Serialization.Objects;
using JsonApiDotNetCoreTests.IntegrationTests.Microservices.Messages;
using Microsoft.Extensions.DependencyInjection;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreTests.IntegrationTests.Microservices.FireAndForgetDelivery
{
public sealed partial class FireForgetTests
{
[Fact]
public async Task Create_group_sends_messages()
{
// Arrange
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
var messageBroker = _testContext.Factory.Services.GetRequiredService<MessageBroker>();
string newGroupName = _fakers.DomainGroup.Generate().Name;
var requestBody = new
{
data = new
{
type = "domainGroups",
attributes = new
{
name = newGroupName
}
}
};
const string route = "/domainGroups";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Created);
responseDocument.Data.SingleValue.Should().NotBeNull();
responseDocument.Data.SingleValue.Attributes["name"].Should().Be(newGroupName);
hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[]
{
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnPrepareWriteAsync),
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWritingAsync),
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWriteSucceededAsync)
}, options => options.WithStrictOrdering());
messageBroker.SentMessages.Should().HaveCount(1);
Guid newGroupId = Guid.Parse(responseDocument.Data.SingleValue.Id);
var content = messageBroker.SentMessages[0].GetContentAs<GroupCreatedContent>();
content.GroupId.Should().Be(newGroupId);
content.GroupName.Should().Be(newGroupName);
}
[Fact]
public async Task Create_group_with_users_sends_messages()
{
// Arrange
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
var messageBroker = _testContext.Factory.Services.GetRequiredService<MessageBroker>();
DomainUser existingUserWithoutGroup = _fakers.DomainUser.Generate();
DomainUser existingUserWithOtherGroup = _fakers.DomainUser.Generate();
existingUserWithOtherGroup.Group = _fakers.DomainGroup.Generate();
string newGroupName = _fakers.DomainGroup.Generate().Name;
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Users.AddRange(existingUserWithoutGroup, existingUserWithOtherGroup);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "domainGroups",
attributes = new
{
name = newGroupName
},
relationships = new
{
users = new
{
data = new[]
{
new
{
type = "domainUsers",
id = existingUserWithoutGroup.StringId
},
new
{
type = "domainUsers",
id = existingUserWithOtherGroup.StringId
}
}
}
}
}
};
const string route = "/domainGroups";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Created);
responseDocument.Data.SingleValue.Should().NotBeNull();
responseDocument.Data.SingleValue.Attributes["name"].Should().Be(newGroupName);
hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[]
{
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnPrepareWriteAsync),
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSetToManyRelationshipAsync),
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWritingAsync),
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWriteSucceededAsync)
}, options => options.WithStrictOrdering());
messageBroker.SentMessages.Should().HaveCount(3);
Guid newGroupId = Guid.Parse(responseDocument.Data.SingleValue.Id);
var content1 = messageBroker.SentMessages[0].GetContentAs<GroupCreatedContent>();
content1.GroupId.Should().Be(newGroupId);
content1.GroupName.Should().Be(newGroupName);
var content2 = messageBroker.SentMessages[1].GetContentAs<UserAddedToGroupContent>();
content2.UserId.Should().Be(existingUserWithoutGroup.Id);
content2.GroupId.Should().Be(newGroupId);
var content3 = messageBroker.SentMessages[2].GetContentAs<UserMovedToGroupContent>();
content3.UserId.Should().Be(existingUserWithOtherGroup.Id);
content3.BeforeGroupId.Should().Be(existingUserWithOtherGroup.Group.Id);
content3.AfterGroupId.Should().Be(newGroupId);
}
[Fact]
public async Task Update_group_sends_messages()
{
// Arrange
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
var messageBroker = _testContext.Factory.Services.GetRequiredService<MessageBroker>();
DomainGroup existingGroup = _fakers.DomainGroup.Generate();
string newGroupName = _fakers.DomainGroup.Generate().Name;
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Groups.Add(existingGroup);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "domainGroups",
id = existingGroup.StringId,
attributes = new
{
name = newGroupName
}
}
};
string route = $"/domainGroups/{existingGroup.StringId}";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[]
{
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnPrepareWriteAsync),
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWritingAsync),
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWriteSucceededAsync)
}, options => options.WithStrictOrdering());
messageBroker.SentMessages.Should().HaveCount(1);
var content = messageBroker.SentMessages[0].GetContentAs<GroupRenamedContent>();
content.GroupId.Should().Be(existingGroup.StringId);
content.BeforeGroupName.Should().Be(existingGroup.Name);
content.AfterGroupName.Should().Be(newGroupName);
}
[Fact]
public async Task Update_group_with_users_sends_messages()
{
// Arrange
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
var messageBroker = _testContext.Factory.Services.GetRequiredService<MessageBroker>();
DomainGroup existingGroup = _fakers.DomainGroup.Generate();
DomainUser existingUserWithoutGroup = _fakers.DomainUser.Generate();
DomainUser existingUserWithSameGroup1 = _fakers.DomainUser.Generate();
existingUserWithSameGroup1.Group = existingGroup;
DomainUser existingUserWithSameGroup2 = _fakers.DomainUser.Generate();
existingUserWithSameGroup2.Group = existingGroup;
DomainUser existingUserWithOtherGroup = _fakers.DomainUser.Generate();
existingUserWithOtherGroup.Group = _fakers.DomainGroup.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Users.AddRange(existingUserWithoutGroup, existingUserWithSameGroup1, existingUserWithSameGroup2, existingUserWithOtherGroup);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "domainGroups",
id = existingGroup.StringId,
relationships = new
{
users = new
{
data = new[]
{
new
{
type = "domainUsers",
id = existingUserWithoutGroup.StringId
},
new
{
type = "domainUsers",
id = existingUserWithSameGroup1.StringId
},
new
{
type = "domainUsers",
id = existingUserWithOtherGroup.StringId
}
}
}
}
}
};
string route = $"/domainGroups/{existingGroup.StringId}";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[]
{
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnPrepareWriteAsync),
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSetToManyRelationshipAsync),
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWritingAsync),
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWriteSucceededAsync)
}, options => options.WithStrictOrdering());
messageBroker.SentMessages.Should().HaveCount(3);
var content1 = messageBroker.SentMessages[0].GetContentAs<UserAddedToGroupContent>();
content1.UserId.Should().Be(existingUserWithoutGroup.Id);
content1.GroupId.Should().Be(existingGroup.Id);
var content2 = messageBroker.SentMessages[1].GetContentAs<UserMovedToGroupContent>();
content2.UserId.Should().Be(existingUserWithOtherGroup.Id);
content2.BeforeGroupId.Should().Be(existingUserWithOtherGroup.Group.Id);
content2.AfterGroupId.Should().Be(existingGroup.Id);
var content3 = messageBroker.SentMessages[2].GetContentAs<UserRemovedFromGroupContent>();
content3.UserId.Should().Be(existingUserWithSameGroup2.Id);
content3.GroupId.Should().Be(existingGroup.Id);
}
[Fact]
public async Task Delete_group_sends_messages()
{
// Arrange
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
var messageBroker = _testContext.Factory.Services.GetRequiredService<MessageBroker>();
DomainGroup existingGroup = _fakers.DomainGroup.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Groups.Add(existingGroup);
await dbContext.SaveChangesAsync();
});
string route = $"/domainGroups/{existingGroup.StringId}";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[]
{
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWritingAsync),
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWriteSucceededAsync)
}, options => options.WithStrictOrdering());
messageBroker.SentMessages.Should().HaveCount(1);
var content = messageBroker.SentMessages[0].GetContentAs<GroupDeletedContent>();
content.GroupId.Should().Be(existingGroup.StringId);
}
[Fact]
public async Task Delete_group_with_users_sends_messages()
{
// Arrange
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
var messageBroker = _testContext.Factory.Services.GetRequiredService<MessageBroker>();
DomainGroup existingGroup = _fakers.DomainGroup.Generate();
existingGroup.Users = _fakers.DomainUser.Generate(1).ToHashSet();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Groups.Add(existingGroup);
await dbContext.SaveChangesAsync();
});
string route = $"/domainGroups/{existingGroup.StringId}";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[]
{
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWritingAsync),
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWriteSucceededAsync)
}, options => options.WithStrictOrdering());
messageBroker.SentMessages.Should().HaveCount(2);
var content1 = messageBroker.SentMessages[0].GetContentAs<UserRemovedFromGroupContent>();
content1.UserId.Should().Be(existingGroup.Users.ElementAt(0).Id);
content1.GroupId.Should().Be(existingGroup.StringId);
var content2 = messageBroker.SentMessages[1].GetContentAs<GroupDeletedContent>();
content2.GroupId.Should().Be(existingGroup.StringId);
}
[Fact]
public async Task Replace_users_in_group_sends_messages()
{
// Arrange
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
var messageBroker = _testContext.Factory.Services.GetRequiredService<MessageBroker>();
DomainGroup existingGroup = _fakers.DomainGroup.Generate();
DomainUser existingUserWithoutGroup = _fakers.DomainUser.Generate();
DomainUser existingUserWithSameGroup1 = _fakers.DomainUser.Generate();
existingUserWithSameGroup1.Group = existingGroup;
DomainUser existingUserWithSameGroup2 = _fakers.DomainUser.Generate();
existingUserWithSameGroup2.Group = existingGroup;
DomainUser existingUserWithOtherGroup = _fakers.DomainUser.Generate();
existingUserWithOtherGroup.Group = _fakers.DomainGroup.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Users.AddRange(existingUserWithoutGroup, existingUserWithSameGroup1, existingUserWithSameGroup2, existingUserWithOtherGroup);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new[]
{
new
{
type = "domainUsers",
id = existingUserWithoutGroup.StringId
},
new
{
type = "domainUsers",
id = existingUserWithSameGroup1.StringId
},
new
{
type = "domainUsers",
id = existingUserWithOtherGroup.StringId
}
}
};
string route = $"/domainGroups/{existingGroup.StringId}/relationships/users";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[]
{
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnPrepareWriteAsync),
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSetToManyRelationshipAsync),
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWritingAsync),
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWriteSucceededAsync)
}, options => options.WithStrictOrdering());
messageBroker.SentMessages.Should().HaveCount(3);
var content1 = messageBroker.SentMessages[0].GetContentAs<UserAddedToGroupContent>();
content1.UserId.Should().Be(existingUserWithoutGroup.Id);
content1.GroupId.Should().Be(existingGroup.Id);
var content2 = messageBroker.SentMessages[1].GetContentAs<UserMovedToGroupContent>();
content2.UserId.Should().Be(existingUserWithOtherGroup.Id);
content2.BeforeGroupId.Should().Be(existingUserWithOtherGroup.Group.Id);
content2.AfterGroupId.Should().Be(existingGroup.Id);
var content3 = messageBroker.SentMessages[2].GetContentAs<UserRemovedFromGroupContent>();
content3.UserId.Should().Be(existingUserWithSameGroup2.Id);
content3.GroupId.Should().Be(existingGroup.Id);
}
[Fact]
public async Task Add_users_to_group_sends_messages()
{
// Arrange
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
var messageBroker = _testContext.Factory.Services.GetRequiredService<MessageBroker>();
DomainGroup existingGroup = _fakers.DomainGroup.Generate();
DomainUser existingUserWithoutGroup = _fakers.DomainUser.Generate();
DomainUser existingUserWithSameGroup = _fakers.DomainUser.Generate();
existingUserWithSameGroup.Group = existingGroup;
DomainUser existingUserWithOtherGroup = _fakers.DomainUser.Generate();
existingUserWithOtherGroup.Group = _fakers.DomainGroup.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Users.AddRange(existingUserWithoutGroup, existingUserWithSameGroup, existingUserWithOtherGroup);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new[]
{
new
{
type = "domainUsers",
id = existingUserWithoutGroup.StringId
},
new
{
type = "domainUsers",
id = existingUserWithOtherGroup.StringId
}
}
};
string route = $"/domainGroups/{existingGroup.StringId}/relationships/users";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[]
{
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnAddToRelationshipAsync),
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWritingAsync),
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWriteSucceededAsync)
}, options => options.WithStrictOrdering());
messageBroker.SentMessages.Should().HaveCount(2);
var content1 = messageBroker.SentMessages[0].GetContentAs<UserAddedToGroupContent>();
content1.UserId.Should().Be(existingUserWithoutGroup.Id);
content1.GroupId.Should().Be(existingGroup.Id);
var content2 = messageBroker.SentMessages[1].GetContentAs<UserMovedToGroupContent>();
content2.UserId.Should().Be(existingUserWithOtherGroup.Id);
content2.BeforeGroupId.Should().Be(existingUserWithOtherGroup.Group.Id);
content2.AfterGroupId.Should().Be(existingGroup.Id);
}
[Fact]
public async Task Remove_users_from_group_sends_messages()
{
// Arrange
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
var messageBroker = _testContext.Factory.Services.GetRequiredService<MessageBroker>();
DomainGroup existingGroup = _fakers.DomainGroup.Generate();
DomainUser existingUserWithSameGroup1 = _fakers.DomainUser.Generate();
existingUserWithSameGroup1.Group = existingGroup;
DomainUser existingUserWithSameGroup2 = _fakers.DomainUser.Generate();
existingUserWithSameGroup2.Group = existingGroup;
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Users.AddRange(existingUserWithSameGroup1, existingUserWithSameGroup2);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new[]
{
new
{
type = "domainUsers",
id = existingUserWithSameGroup2.StringId
}
}
};
string route = $"/domainGroups/{existingGroup.StringId}/relationships/users";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[]
{
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnRemoveFromRelationshipAsync),
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWritingAsync),
(typeof(DomainGroup), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWriteSucceededAsync)
}, options => options.WithStrictOrdering());
messageBroker.SentMessages.Should().HaveCount(1);
var content = messageBroker.SentMessages[0].GetContentAs<UserRemovedFromGroupContent>();
content.UserId.Should().Be(existingUserWithSameGroup2.Id);
content.GroupId.Should().Be(existingGroup.Id);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
namespace System.Reflection.Emit
{
using System;
using System.Collections.Generic;
using CultureInfo = System.Globalization.CultureInfo;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class DynamicMethod : MethodInfo
{
private RuntimeType[] m_parameterTypes;
internal IRuntimeMethodInfo m_methodHandle;
private RuntimeType m_returnType;
private DynamicILGenerator m_ilGenerator;
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
private DynamicILInfo m_DynamicILInfo;
private bool m_fInitLocals;
private RuntimeModule m_module;
internal bool m_skipVisibility;
internal RuntimeType m_typeOwner; // can be null
// We want the creator of the DynamicMethod to control who has access to the
// DynamicMethod (just like we do for delegates). However, a user can get to
// the corresponding RTDynamicMethod using Exception.TargetSite, StackFrame.GetMethod, etc.
// If we allowed use of RTDynamicMethod, the creator of the DynamicMethod would
// not be able to bound access to the DynamicMethod. Hence, we need to ensure that
// we do not allow direct use of RTDynamicMethod.
private RTDynamicMethod m_dynMethod;
// needed to keep the object alive during jitting
// assigned by the DynamicResolver ctor
internal DynamicResolver m_resolver;
// Always false unless we are in an immersive (non dev mode) process.
#if FEATURE_APPX
private bool m_profileAPICheck;
private RuntimeAssembly m_creatorAssembly;
#endif
internal bool m_restrictedSkipVisibility;
// The context when the method was created. We use this to do the RestrictedMemberAccess checks.
// These checks are done when the method is compiled. This can happen at an arbitrary time,
// when CreateDelegate or Invoke is called, or when another DynamicMethod executes OpCodes.Call.
// We capture the creation context so that we can do the checks against the same context,
// irrespective of when the method gets compiled. Note that the DynamicMethod does not know when
// it is ready for use since there is not API which indictates that IL generation has completed.
#if FEATURE_COMPRESSEDSTACK
internal CompressedStack m_creationContext;
#endif // FEATURE_COMPRESSEDSTACK
private static volatile InternalModuleBuilder s_anonymouslyHostedDynamicMethodsModule;
private static readonly object s_anonymouslyHostedDynamicMethodsModuleLock = new object();
//
// class initialization (ctor and init)
//
private DynamicMethod() { }
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
Type returnType,
Type[] parameterTypes)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Init(name,
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
returnType,
parameterTypes,
null, // owner
null, // m
false, // skipVisibility
true,
ref stackMark); // transparentMethod
}
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
Type returnType,
Type[] parameterTypes,
bool restrictedSkipVisibility)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Init(name,
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
returnType,
parameterTypes,
null, // owner
null, // m
restrictedSkipVisibility,
true,
ref stackMark); // transparentMethod
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
Type returnType,
Type[] parameterTypes,
Module m) {
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
PerformSecurityCheck(m, ref stackMark, false);
Init(name,
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
returnType,
parameterTypes,
null, // owner
m, // m
false, // skipVisibility
false,
ref stackMark); // transparentMethod
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
Type returnType,
Type[] parameterTypes,
Module m,
bool skipVisibility) {
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
PerformSecurityCheck(m, ref stackMark, skipVisibility);
Init(name,
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
returnType,
parameterTypes,
null, // owner
m, // m
skipVisibility,
false,
ref stackMark); // transparentMethod
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
MethodAttributes attributes,
CallingConventions callingConvention,
Type returnType,
Type[] parameterTypes,
Module m,
bool skipVisibility) {
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
PerformSecurityCheck(m, ref stackMark, skipVisibility);
Init(name,
attributes,
callingConvention,
returnType,
parameterTypes,
null, // owner
m, // m
skipVisibility,
false,
ref stackMark); // transparentMethod
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
Type returnType,
Type[] parameterTypes,
Type owner) {
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
PerformSecurityCheck(owner, ref stackMark, false);
Init(name,
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
returnType,
parameterTypes,
owner, // owner
null, // m
false, // skipVisibility
false,
ref stackMark); // transparentMethod
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
Type returnType,
Type[] parameterTypes,
Type owner,
bool skipVisibility) {
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
PerformSecurityCheck(owner, ref stackMark, skipVisibility);
Init(name,
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
returnType,
parameterTypes,
owner, // owner
null, // m
skipVisibility,
false,
ref stackMark); // transparentMethod
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
MethodAttributes attributes,
CallingConventions callingConvention,
Type returnType,
Type[] parameterTypes,
Type owner,
bool skipVisibility) {
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
PerformSecurityCheck(owner, ref stackMark, skipVisibility);
Init(name,
attributes,
callingConvention,
returnType,
parameterTypes,
owner, // owner
null, // m
skipVisibility,
false,
ref stackMark); // transparentMethod
}
// helpers for intialization
static private void CheckConsistency(MethodAttributes attributes, CallingConventions callingConvention) {
// only static public for method attributes
if ((attributes & ~MethodAttributes.MemberAccessMask) != MethodAttributes.Static)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicMethodFlags"));
if ((attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicMethodFlags"));
Contract.EndContractBlock();
// only standard or varargs supported
if (callingConvention != CallingConventions.Standard && callingConvention != CallingConventions.VarArgs)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicMethodFlags"));
// vararg is not supported at the moment
if (callingConvention == CallingConventions.VarArgs)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicMethodFlags"));
}
// We create a transparent assembly to host DynamicMethods. Since the assembly does not have any
// non-public fields (or any fields at all), it is a safe anonymous assembly to host DynamicMethods
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
private static RuntimeModule GetDynamicMethodsModule()
{
if (s_anonymouslyHostedDynamicMethodsModule != null)
return s_anonymouslyHostedDynamicMethodsModule;
lock (s_anonymouslyHostedDynamicMethodsModuleLock)
{
if (s_anonymouslyHostedDynamicMethodsModule != null)
return s_anonymouslyHostedDynamicMethodsModule;
ConstructorInfo transparencyCtor = typeof(SecurityTransparentAttribute).GetConstructor(Type.EmptyTypes);
CustomAttributeBuilder transparencyAttribute = new CustomAttributeBuilder(transparencyCtor, EmptyArray<Object>.Value);
List<CustomAttributeBuilder> assemblyAttributes = new List<CustomAttributeBuilder>();
assemblyAttributes.Add(transparencyAttribute);
#if !FEATURE_CORECLR
// On the desktop, we need to use the security rule set level 1 for anonymously hosted
// dynamic methods. In level 2, transparency rules are strictly enforced, which leads to
// errors when a fully trusted application causes a dynamic method to be generated that tries
// to call a method with a LinkDemand or a SecurityCritical method. To retain compatibility
// with the v2.0 and v3.x frameworks, these calls should be allowed.
//
// If this rule set was not explicitly called out, then the anonymously hosted dynamic methods
// assembly would inherit the rule set from the creating assembly - which would cause it to
// be level 2 because mscorlib.dll is using the level 2 rules.
ConstructorInfo securityRulesCtor = typeof(SecurityRulesAttribute).GetConstructor(new Type[] { typeof(SecurityRuleSet) });
CustomAttributeBuilder securityRulesAttribute =
new CustomAttributeBuilder(securityRulesCtor, new object[] { SecurityRuleSet.Level1 });
assemblyAttributes.Add(securityRulesAttribute);
#endif // !FEATURE_CORECLR
AssemblyName assemblyName = new AssemblyName("Anonymously Hosted DynamicMethods Assembly");
StackCrawlMark stackMark = StackCrawlMark.LookForMe;
AssemblyBuilder assembly = AssemblyBuilder.InternalDefineDynamicAssembly(
assemblyName,
AssemblyBuilderAccess.Run,
null, null, null, null, null,
ref stackMark,
assemblyAttributes,
SecurityContextSource.CurrentAssembly);
AppDomain.PublishAnonymouslyHostedDynamicMethodsAssembly(assembly.GetNativeHandle());
// this always gets the internal module.
s_anonymouslyHostedDynamicMethodsModule = (InternalModuleBuilder)assembly.ManifestModule;
}
return s_anonymouslyHostedDynamicMethodsModule;
}
[System.Security.SecurityCritical] // auto-generated
private unsafe void Init(String name,
MethodAttributes attributes,
CallingConventions callingConvention,
Type returnType,
Type[] signature,
Type owner,
Module m,
bool skipVisibility,
bool transparentMethod,
ref StackCrawlMark stackMark)
{
DynamicMethod.CheckConsistency(attributes, callingConvention);
// check and store the signature
if (signature != null) {
m_parameterTypes = new RuntimeType[signature.Length];
for (int i = 0; i < signature.Length; i++) {
if (signature[i] == null)
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidTypeInSignature"));
m_parameterTypes[i] = signature[i].UnderlyingSystemType as RuntimeType;
if ( m_parameterTypes[i] == null || !(m_parameterTypes[i] is RuntimeType) || m_parameterTypes[i] == (RuntimeType)typeof(void) )
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidTypeInSignature"));
}
}
else {
m_parameterTypes = Array.Empty<RuntimeType>();
}
// check and store the return value
m_returnType = (returnType == null) ? (RuntimeType)typeof(void) : returnType.UnderlyingSystemType as RuntimeType;
if ( (m_returnType == null) || !(m_returnType is RuntimeType) || m_returnType.IsByRef )
throw new NotSupportedException(Environment.GetResourceString("Arg_InvalidTypeInRetType"));
if (transparentMethod)
{
Contract.Assert(owner == null && m == null, "owner and m cannot be set for transparent methods");
m_module = GetDynamicMethodsModule();
if (skipVisibility)
{
m_restrictedSkipVisibility = true;
}
#if FEATURE_COMPRESSEDSTACK
m_creationContext = CompressedStack.Capture();
#endif // FEATURE_COMPRESSEDSTACK
}
else
{
Contract.Assert(m != null || owner != null, "PerformSecurityCheck should ensure that either m or owner is set");
Contract.Assert(m == null || !m.Equals(s_anonymouslyHostedDynamicMethodsModule), "The user cannot explicitly use this assembly");
Contract.Assert(m == null || owner == null, "m and owner cannot both be set");
if (m != null)
m_module = m.ModuleHandle.GetRuntimeModule(); // this returns the underlying module for all RuntimeModule and ModuleBuilder objects.
else
{
RuntimeType rtOwner = null;
if (owner != null)
rtOwner = owner.UnderlyingSystemType as RuntimeType;
if (rtOwner != null)
{
if (rtOwner.HasElementType || rtOwner.ContainsGenericParameters
|| rtOwner.IsGenericParameter || rtOwner.IsInterface)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeForDynamicMethod"));
m_typeOwner = rtOwner;
m_module = rtOwner.GetRuntimeModule();
}
}
m_skipVisibility = skipVisibility;
}
// initialize remaining fields
m_ilGenerator = null;
m_fInitLocals = true;
m_methodHandle = null;
if (name == null)
throw new ArgumentNullException("name");
#if FEATURE_APPX
if (AppDomain.ProfileAPICheck)
{
if (m_creatorAssembly == null)
m_creatorAssembly = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
if (m_creatorAssembly != null && !m_creatorAssembly.IsFrameworkAssembly())
m_profileAPICheck = true;
}
#endif // FEATURE_APPX
m_dynMethod = new RTDynamicMethod(this, name, attributes, callingConvention);
}
[System.Security.SecurityCritical] // auto-generated
private void PerformSecurityCheck(Module m, ref StackCrawlMark stackMark, bool skipVisibility)
{
if (m == null)
throw new ArgumentNullException("m");
Contract.EndContractBlock();
RuntimeModule rtModule;
ModuleBuilder mb = m as ModuleBuilder;
if (mb != null)
rtModule = mb.InternalModule;
else
rtModule = m as RuntimeModule;
if (rtModule == null)
{
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeModule"), "m");
}
// The user cannot explicitly use this assembly
if (rtModule == s_anonymouslyHostedDynamicMethodsModule)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue"), "m");
// ask for member access if skip visibility
if (skipVisibility)
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
#if !FEATURE_CORECLR
// ask for control evidence if outside of the caller assembly
RuntimeType callingType = RuntimeMethodHandle.GetCallerType(ref stackMark);
m_creatorAssembly = callingType.GetRuntimeAssembly();
if (m.Assembly != m_creatorAssembly)
{
// Demand the permissions of the assembly where the DynamicMethod will live
CodeAccessSecurityEngine.ReflectionTargetDemandHelper(PermissionType.SecurityControlEvidence,
m.Assembly.PermissionSet);
}
#else //FEATURE_CORECLR
#pragma warning disable 618
new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
#pragma warning restore 618
#endif //FEATURE_CORECLR
}
[System.Security.SecurityCritical] // auto-generated
private void PerformSecurityCheck(Type owner, ref StackCrawlMark stackMark, bool skipVisibility)
{
if (owner == null)
throw new ArgumentNullException("owner");
RuntimeType rtOwner = owner as RuntimeType;
if (rtOwner == null)
rtOwner = owner.UnderlyingSystemType as RuntimeType;
if (rtOwner == null)
throw new ArgumentNullException("owner", Environment.GetResourceString("Argument_MustBeRuntimeType"));
// get the type the call is coming from
RuntimeType callingType = RuntimeMethodHandle.GetCallerType(ref stackMark);
// ask for member access if skip visibility
if (skipVisibility)
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
else
{
// if the call is not coming from the same class ask for member access
if (callingType != rtOwner)
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
}
#if !FEATURE_CORECLR
m_creatorAssembly = callingType.GetRuntimeAssembly();
// ask for control evidence if outside of the caller module
if (rtOwner.Assembly != m_creatorAssembly)
{
// Demand the permissions of the assembly where the DynamicMethod will live
CodeAccessSecurityEngine.ReflectionTargetDemandHelper(PermissionType.SecurityControlEvidence,
owner.Assembly.PermissionSet);
}
#else //FEATURE_CORECLR
#pragma warning disable 618
new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
#pragma warning restore 618
#endif //FEATURE_CORECLR
}
//
// Delegate and method creation
//
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public sealed override Delegate CreateDelegate(Type delegateType) {
if (m_restrictedSkipVisibility)
{
// Compile the method since accessibility checks are done as part of compilation.
GetMethodDescriptor();
System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(m_methodHandle);
}
MulticastDelegate d = (MulticastDelegate)Delegate.CreateDelegateNoSecurityCheck(delegateType, null, GetMethodDescriptor());
// stash this MethodInfo by brute force.
d.StoreDynamicMethod(GetMethodInfo());
return d;
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public sealed override Delegate CreateDelegate(Type delegateType, Object target) {
if (m_restrictedSkipVisibility)
{
// Compile the method since accessibility checks are done as part of compilation
GetMethodDescriptor();
System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(m_methodHandle);
}
MulticastDelegate d = (MulticastDelegate)Delegate.CreateDelegateNoSecurityCheck(delegateType, target, GetMethodDescriptor());
// stash this MethodInfo by brute force.
d.StoreDynamicMethod(GetMethodInfo());
return d;
}
#if FEATURE_APPX
internal bool ProfileAPICheck
{
get
{
return m_profileAPICheck;
}
[FriendAccessAllowed]
set
{
m_profileAPICheck = value;
}
}
#endif
// This is guaranteed to return a valid handle
[System.Security.SecurityCritical] // auto-generated
internal unsafe RuntimeMethodHandle GetMethodDescriptor() {
if (m_methodHandle == null) {
lock (this) {
if (m_methodHandle == null) {
if (m_DynamicILInfo != null)
m_DynamicILInfo.GetCallableMethod(m_module, this);
else {
if (m_ilGenerator == null || m_ilGenerator.ILOffset == 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadEmptyMethodBody", Name));
m_ilGenerator.GetCallableMethod(m_module, this);
}
}
}
}
return new RuntimeMethodHandle(m_methodHandle);
}
//
// MethodInfo api. They mostly forward to RTDynamicMethod
//
public override String ToString() { return m_dynMethod.ToString(); }
public override String Name { get { return m_dynMethod.Name; } }
public override Type DeclaringType { get { return m_dynMethod.DeclaringType; } }
public override Type ReflectedType { get { return m_dynMethod.ReflectedType; } }
public override Module Module { get { return m_dynMethod.Module; } }
// we cannot return a MethodHandle because we cannot track it via GC so this method is off limits
public override RuntimeMethodHandle MethodHandle { get { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod")); } }
public override MethodAttributes Attributes { get { return m_dynMethod.Attributes; } }
public override CallingConventions CallingConvention { get { return m_dynMethod.CallingConvention; } }
public override MethodInfo GetBaseDefinition() { return this; }
[Pure]
public override ParameterInfo[] GetParameters() { return m_dynMethod.GetParameters(); }
public override MethodImplAttributes GetMethodImplementationFlags() { return m_dynMethod.GetMethodImplementationFlags(); }
//
// Security transparency accessors
//
// Since the dynamic method may not be JITed yet, we don't always have the runtime method handle
// which is needed to determine the official runtime transparency status of the dynamic method. We
// fall back to saying that the dynamic method matches the transparency of its containing module
// until we get a JITed version, since dynamic methods cannot have attributes of their own.
//
public override bool IsSecurityCritical
{
[SecuritySafeCritical]
get
{
if (m_methodHandle != null)
{
return RuntimeMethodHandle.IsSecurityCritical(m_methodHandle);
}
else if (m_typeOwner != null)
{
RuntimeAssembly assembly = m_typeOwner.Assembly as RuntimeAssembly;
Contract.Assert(assembly != null);
return assembly.IsAllSecurityCritical();
}
else
{
RuntimeAssembly assembly = m_module.Assembly as RuntimeAssembly;
Contract.Assert(assembly != null);
return assembly.IsAllSecurityCritical();
}
}
}
public override bool IsSecuritySafeCritical
{
[SecuritySafeCritical]
get
{
if (m_methodHandle != null)
{
return RuntimeMethodHandle.IsSecuritySafeCritical(m_methodHandle);
}
else if (m_typeOwner != null)
{
RuntimeAssembly assembly = m_typeOwner.Assembly as RuntimeAssembly;
Contract.Assert(assembly != null);
return assembly.IsAllPublicAreaSecuritySafeCritical();
}
else
{
RuntimeAssembly assembly = m_module.Assembly as RuntimeAssembly;
Contract.Assert(assembly != null);
return assembly.IsAllSecuritySafeCritical();
}
}
}
public override bool IsSecurityTransparent
{
[SecuritySafeCritical]
get
{
if (m_methodHandle != null)
{
return RuntimeMethodHandle.IsSecurityTransparent(m_methodHandle);
}
else if (m_typeOwner != null)
{
RuntimeAssembly assembly = m_typeOwner.Assembly as RuntimeAssembly;
Contract.Assert(assembly != null);
return !assembly.IsAllSecurityCritical();
}
else
{
RuntimeAssembly assembly = m_module.Assembly as RuntimeAssembly;
Contract.Assert(assembly != null);
return !assembly.IsAllSecurityCritical();
}
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) {
if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_CallToVarArg"));
Contract.EndContractBlock();
//
// We do not demand any permission here because the caller already has access
// to the current DynamicMethod object, and it could just as easily emit another
// Transparent DynamicMethod to call the current DynamicMethod.
//
RuntimeMethodHandle method = GetMethodDescriptor();
// ignore obj since it's a static method
// create a signature object
Signature sig = new Signature(
this.m_methodHandle, m_parameterTypes, m_returnType, CallingConvention);
// verify arguments
int formalCount = sig.Arguments.Length;
int actualCount = (parameters != null) ? parameters.Length : 0;
if (formalCount != actualCount)
throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt"));
// if we are here we passed all the previous checks. Time to look at the arguments
Object retValue = null;
if (actualCount > 0)
{
Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig);
retValue = RuntimeMethodHandle.InvokeMethod(null, arguments, sig, false);
// copy out. This should be made only if ByRef are present.
for (int index = 0; index < arguments.Length; index++)
parameters[index] = arguments[index];
}
else
{
retValue = RuntimeMethodHandle.InvokeMethod(null, null, sig, false);
}
GC.KeepAlive(this);
return retValue;
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return m_dynMethod.GetCustomAttributes(attributeType, inherit);
}
public override Object[] GetCustomAttributes(bool inherit) { return m_dynMethod.GetCustomAttributes(inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_dynMethod.IsDefined(attributeType, inherit); }
public override Type ReturnType { get { return m_dynMethod.ReturnType; } }
public override ParameterInfo ReturnParameter { get { return m_dynMethod.ReturnParameter; } }
public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { return m_dynMethod.ReturnTypeCustomAttributes; } }
//
// DynamicMethod specific methods
//
public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, String parameterName) {
if (position < 0 || position > m_parameterTypes.Length)
throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_ParamSequence"));
position--; // it's 1 based. 0 is the return value
if (position >= 0) {
ParameterInfo[] parameters = m_dynMethod.LoadParameters();
parameters[position].SetName(parameterName);
parameters[position].SetAttributes(attributes);
}
return null;
}
[System.Security.SecuritySafeCritical] // auto-generated
public DynamicILInfo GetDynamicILInfo()
{
#pragma warning disable 618
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
#pragma warning restore 618
if (m_DynamicILInfo != null)
return m_DynamicILInfo;
return GetDynamicILInfo(new DynamicScope());
}
[System.Security.SecurityCritical] // auto-generated
internal DynamicILInfo GetDynamicILInfo(DynamicScope scope)
{
if (m_DynamicILInfo == null)
{
byte[] methodSignature = SignatureHelper.GetMethodSigHelper(
null, CallingConvention, ReturnType, null, null, m_parameterTypes, null, null).GetSignature(true);
m_DynamicILInfo = new DynamicILInfo(scope, this, methodSignature);
}
return m_DynamicILInfo;
}
public ILGenerator GetILGenerator() {
return GetILGenerator(64);
}
[System.Security.SecuritySafeCritical] // auto-generated
public ILGenerator GetILGenerator(int streamSize)
{
if (m_ilGenerator == null)
{
byte[] methodSignature = SignatureHelper.GetMethodSigHelper(
null, CallingConvention, ReturnType, null, null, m_parameterTypes, null, null).GetSignature(true);
m_ilGenerator = new DynamicILGenerator(this, methodSignature, streamSize);
}
return m_ilGenerator;
}
public bool InitLocals {
get {return m_fInitLocals;}
set {m_fInitLocals = value;}
}
//
// Internal API
//
internal MethodInfo GetMethodInfo() {
return m_dynMethod;
}
//////////////////////////////////////////////////////////////////////////////////////////////
// RTDynamicMethod
//
// this is actually the real runtime instance of a method info that gets used for invocation
// We need this so we never leak the DynamicMethod out via an exception.
// This way the DynamicMethod creator is the only one responsible for DynamicMethod access,
// and can control exactly who gets access to it.
//
internal class RTDynamicMethod : MethodInfo {
internal DynamicMethod m_owner;
ParameterInfo[] m_parameters;
String m_name;
MethodAttributes m_attributes;
CallingConventions m_callingConvention;
//
// ctors
//
private RTDynamicMethod() {}
internal RTDynamicMethod(DynamicMethod owner, String name, MethodAttributes attributes, CallingConventions callingConvention) {
m_owner = owner;
m_name = name;
m_attributes = attributes;
m_callingConvention = callingConvention;
}
//
// MethodInfo api
//
public override String ToString() {
return ReturnType.FormatTypeName() + " " + FormatNameAndSig();
}
public override String Name {
get { return m_name; }
}
public override Type DeclaringType {
get { return null; }
}
public override Type ReflectedType {
get { return null; }
}
public override Module Module {
get { return m_owner.m_module; }
}
public override RuntimeMethodHandle MethodHandle {
get { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod")); }
}
public override MethodAttributes Attributes {
get { return m_attributes; }
}
public override CallingConventions CallingConvention {
get { return m_callingConvention; }
}
public override MethodInfo GetBaseDefinition() {
return this;
}
[Pure]
public override ParameterInfo[] GetParameters() {
ParameterInfo[] privateParameters = LoadParameters();
ParameterInfo[] parameters = new ParameterInfo[privateParameters.Length];
Array.Copy(privateParameters, parameters, privateParameters.Length);
return parameters;
}
public override MethodImplAttributes GetMethodImplementationFlags() {
return MethodImplAttributes.IL | MethodImplAttributes.NoInlining;
}
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) {
// We want the creator of the DynamicMethod to control who has access to the
// DynamicMethod (just like we do for delegates). However, a user can get to
// the corresponding RTDynamicMethod using Exception.TargetSite, StackFrame.GetMethod, etc.
// If we allowed use of RTDynamicMethod, the creator of the DynamicMethod would
// not be able to bound access to the DynamicMethod. Hence, we do not allow
// direct use of RTDynamicMethod.
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "this");
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) {
if (attributeType == null)
throw new ArgumentNullException("attributeType");
Contract.EndContractBlock();
if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute)))
return new Object[] { new MethodImplAttribute(GetMethodImplementationFlags()) };
else
return EmptyArray<Object>.Value;
}
public override Object[] GetCustomAttributes(bool inherit) {
// support for MethodImplAttribute PCA
return new Object[] { new MethodImplAttribute(GetMethodImplementationFlags()) };
}
public override bool IsDefined(Type attributeType, bool inherit) {
if (attributeType == null)
throw new ArgumentNullException("attributeType");
Contract.EndContractBlock();
if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute)))
return true;
else
return false;
}
public override bool IsSecurityCritical
{
get { return m_owner.IsSecurityCritical; }
}
public override bool IsSecuritySafeCritical
{
get { return m_owner.IsSecuritySafeCritical; }
}
public override bool IsSecurityTransparent
{
get { return m_owner.IsSecurityTransparent; }
}
public override Type ReturnType
{
get
{
return m_owner.m_returnType;
}
}
public override ParameterInfo ReturnParameter {
get { return null; }
}
public override ICustomAttributeProvider ReturnTypeCustomAttributes {
get { return GetEmptyCAHolder(); }
}
//
// private implementation
//
internal ParameterInfo[] LoadParameters() {
if (m_parameters == null) {
Type[] parameterTypes = m_owner.m_parameterTypes;
ParameterInfo[] parameters = new ParameterInfo[parameterTypes.Length];
for (int i = 0; i < parameterTypes.Length; i++)
parameters[i] = new RuntimeParameterInfo(this, null, parameterTypes[i], i);
if (m_parameters == null)
// should we interlockexchange?
m_parameters = parameters;
}
return m_parameters;
}
// private implementation of CA for the return type
private ICustomAttributeProvider GetEmptyCAHolder() {
return new EmptyCAHolder();
}
///////////////////////////////////////////////////
// EmptyCAHolder
private class EmptyCAHolder : ICustomAttributeProvider {
internal EmptyCAHolder() {}
Object[] ICustomAttributeProvider.GetCustomAttributes(Type attributeType, bool inherit) {
return EmptyArray<Object>.Value;
}
Object[] ICustomAttributeProvider.GetCustomAttributes(bool inherit) {
return EmptyArray<Object>.Value;
}
bool ICustomAttributeProvider.IsDefined (Type attributeType, bool inherit) {
return false;
}
}
}
}
}
| |
// 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 OrInt64()
{
var test = new SimpleBinaryOpTest__OrInt64();
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();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// 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 class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
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__OrInt64
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int64[] inArray1, Int64[] inArray2, Int64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int64> _fld1;
public Vector128<Int64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__OrInt64 testClass)
{
var result = Sse2.Or(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__OrInt64 testClass)
{
fixed (Vector128<Int64>* pFld1 = &_fld1)
fixed (Vector128<Int64>* pFld2 = &_fld2)
{
var result = Sse2.Or(
Sse2.LoadVector128((Int64*)(pFld1)),
Sse2.LoadVector128((Int64*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static Int64[] _data1 = new Int64[Op1ElementCount];
private static Int64[] _data2 = new Int64[Op2ElementCount];
private static Vector128<Int64> _clsVar1;
private static Vector128<Int64> _clsVar2;
private Vector128<Int64> _fld1;
private Vector128<Int64> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__OrInt64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
}
public SimpleBinaryOpTest__OrInt64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
_dataTable = new DataTable(_data1, _data2, new Int64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.Or(
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.Or(
Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.Or(
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.Or(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int64>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int64>* pClsVar2 = &_clsVar2)
{
var result = Sse2.Or(
Sse2.LoadVector128((Int64*)(pClsVar1)),
Sse2.LoadVector128((Int64*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr);
var result = Sse2.Or(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr));
var result = Sse2.Or(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr));
var result = Sse2.Or(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__OrInt64();
var result = Sse2.Or(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__OrInt64();
fixed (Vector128<Int64>* pFld1 = &test._fld1)
fixed (Vector128<Int64>* pFld2 = &test._fld2)
{
var result = Sse2.Or(
Sse2.LoadVector128((Int64*)(pFld1)),
Sse2.LoadVector128((Int64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.Or(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int64>* pFld1 = &_fld1)
fixed (Vector128<Int64>* pFld2 = &_fld2)
{
var result = Sse2.Or(
Sse2.LoadVector128((Int64*)(pFld1)),
Sse2.LoadVector128((Int64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.Or(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.Or(
Sse2.LoadVector128((Int64*)(&test._fld1)),
Sse2.LoadVector128((Int64*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int64> op1, Vector128<Int64> op2, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((long)(left[0] | right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((long)(left[i] | right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Or)}<Int64>(Vector128<Int64>, Vector128<Int64>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Cci.Immutable;
using Microsoft.Cci.MetadataReader.ObjectModelImplementation;
using Microsoft.Cci.MetadataReader.PEFileFlags;
using Microsoft.Cci.UtilityDataStructures;
using System.Diagnostics.Contracts;
namespace Microsoft.Cci.MetadataReader.ObjectModelImplementation {
internal abstract class ExpressionBase : IMetadataExpression {
internal abstract ITypeReference/*?*/ ModuleTypeReference { get; }
#region IExpression Members
public IEnumerable<ILocation> Locations {
get { return Enumerable<ILocation>.Empty; }
}
public ITypeReference Type {
get { return this.ModuleTypeReference; }
}
/// <summary>
/// Calls the visitor.Visit(T) method where T is the most derived object model node interface type implemented by the concrete type
/// of the object implementing IDoubleDispatcher. The dispatch method does not invoke Dispatch on any child objects. If child traversal
/// is desired, the implementations of the Visit methods should do the subsequent dispatching.
/// </summary>
public abstract void Dispatch(IMetadataVisitor visitor);
#endregion
}
internal sealed class ConstantExpression : ExpressionBase, IMetadataConstant {
readonly ITypeReference TypeReference;
internal object/*?*/ value;
internal ConstantExpression(
ITypeReference typeReference,
object/*?*/ value
) {
this.TypeReference = typeReference;
this.value = value;
}
internal override ITypeReference/*?*/ ModuleTypeReference {
get { return this.TypeReference; }
}
public override void Dispatch(IMetadataVisitor visitor) {
visitor.Visit(this);
}
#region ICompileTimeConstant Members
public object/*?*/ Value {
get { return this.value; }
}
#endregion
}
internal sealed class ArrayExpression : ExpressionBase, IMetadataCreateArray {
internal readonly IArrayTypeReference VectorType;
internal readonly EnumerableArrayWrapper<ExpressionBase, IMetadataExpression> Elements;
internal ArrayExpression(
IArrayTypeReference vectorType,
EnumerableArrayWrapper<ExpressionBase, IMetadataExpression> elements
) {
this.VectorType = vectorType;
this.Elements = elements;
}
internal override ITypeReference/*?*/ ModuleTypeReference {
get { return this.VectorType; }
}
public override void Dispatch(IMetadataVisitor visitor) {
visitor.Visit(this);
}
#region IArrayCreate Members
public ITypeReference ElementType {
get {
ITypeReference/*?*/ moduleTypeRef = this.VectorType.ElementType;
if (moduleTypeRef == null)
return Dummy.TypeReference;
return moduleTypeRef;
}
}
public IEnumerable<IMetadataExpression> Initializers {
get { return this.Elements; }
}
public IEnumerable<int> LowerBounds {
get { return IteratorHelper.GetSingletonEnumerable<int>(0); }
}
public uint Rank {
get { return 1; }
}
public IEnumerable<ulong> Sizes {
get { return IteratorHelper.GetSingletonEnumerable<ulong>((ulong)this.Elements.RawArray.Length); }
}
#endregion
}
internal sealed class TypeOfExpression : ExpressionBase, IMetadataTypeOf {
readonly PEFileToObjectModel PEFileToObjectModel;
readonly ITypeReference/*?*/ TypeExpression;
internal TypeOfExpression(
PEFileToObjectModel peFileToObjectModel,
ITypeReference/*?*/ typeExpression
) {
this.PEFileToObjectModel = peFileToObjectModel;
this.TypeExpression = typeExpression;
}
internal override ITypeReference/*?*/ ModuleTypeReference {
get { return this.PEFileToObjectModel.PlatformType.SystemType; }
}
public override void Dispatch(IMetadataVisitor visitor) {
visitor.Visit(this);
}
#region ITypeOf Members
public ITypeReference TypeToGet {
get {
if (this.TypeExpression == null) return Dummy.TypeReference;
return this.TypeExpression;
}
}
#endregion
}
internal sealed class FieldOrPropertyNamedArgumentExpression : ExpressionBase, IMetadataNamedArgument {
const int IsFieldFlag = 0x01;
const int IsResolvedFlag = 0x02;
readonly IName Name;
readonly ITypeReference ContainingType;
int Flags;
readonly ITypeReference fieldOrPropTypeReference;
object/*?*/ resolvedFieldOrProperty;
internal readonly ExpressionBase ExpressionValue;
internal FieldOrPropertyNamedArgumentExpression(
IName name,
ITypeReference containingType,
bool isField,
ITypeReference fieldOrPropTypeReference,
ExpressionBase expressionValue
) {
this.Name = name;
this.ContainingType = containingType;
if (isField)
this.Flags |= FieldOrPropertyNamedArgumentExpression.IsFieldFlag;
this.fieldOrPropTypeReference = fieldOrPropTypeReference;
this.ExpressionValue = expressionValue;
}
public bool IsField {
get {
return (this.Flags & FieldOrPropertyNamedArgumentExpression.IsFieldFlag) == FieldOrPropertyNamedArgumentExpression.IsFieldFlag;
}
}
internal override ITypeReference/*?*/ ModuleTypeReference {
get { return this.fieldOrPropTypeReference; }
}
public override void Dispatch(IMetadataVisitor visitor) {
visitor.Visit(this);
}
#region INamedArgument Members
public IName ArgumentName {
get { return this.Name; }
}
public IMetadataExpression ArgumentValue {
get { return this.ExpressionValue; }
}
public object/*?*/ ResolvedDefinition {
get {
if ((this.Flags & FieldOrPropertyNamedArgumentExpression.IsResolvedFlag) == 0) {
this.Flags |= FieldOrPropertyNamedArgumentExpression.IsResolvedFlag;
ITypeDefinition/*?*/ typeDef = this.ContainingType.ResolvedType;
if (this.IsField) {
foreach (ITypeDefinitionMember tdm in typeDef.GetMembersNamed(this.Name, false)) {
IFieldDefinition/*?*/ fd = tdm as IFieldDefinition;
if (fd == null)
continue;
ITypeReference/*?*/ fmtr = fd.Type as ITypeReference;
if (fmtr == null)
continue;
if (fmtr.InternedKey == this.fieldOrPropTypeReference.InternedKey) {
this.resolvedFieldOrProperty = fd;
break;
}
}
} else {
foreach (ITypeDefinitionMember tdm in typeDef.GetMembersNamed(this.Name, false)) {
IPropertyDefinition/*?*/ pd = tdm as IPropertyDefinition;
if (pd == null)
continue;
ITypeReference/*?*/ pmtr = pd.Type as ITypeReference;
if (pmtr == null)
continue;
if (pmtr.InternedKey == this.fieldOrPropTypeReference.InternedKey) {
this.resolvedFieldOrProperty = pd;
break;
}
}
}
}
return this.resolvedFieldOrProperty;
}
}
#endregion
}
internal sealed class CustomAttribute : MetadataObject, ICustomAttribute {
internal readonly IMethodReference Constructor;
internal readonly IMetadataExpression[]/*?*/ Arguments;
internal IMetadataNamedArgument[]/*?*/ NamedArguments;
internal readonly uint AttributeRowId;
internal CustomAttribute(PEFileToObjectModel peFileToObjectModel, uint attributeRowId, IMethodReference constructor,
IMetadataExpression[]/*?*/ arguments, IMetadataNamedArgument[]/*?*/ namedArguments)
: base(peFileToObjectModel) {
this.AttributeRowId = attributeRowId;
this.Constructor = constructor;
this.Arguments = arguments;
this.NamedArguments = namedArguments;
}
public override void Dispatch(IMetadataVisitor visitor) {
visitor.Visit(this);
}
public override void DispatchAsReference(IMetadataVisitor visitor) {
throw new InvalidOperationException();
}
internal override uint TokenValue {
get { return TokenTypeIds.CustomAttribute | this.AttributeRowId; }
}
#region ICustomAttribute Members
IEnumerable<IMetadataExpression> ICustomAttribute.Arguments {
get { return IteratorHelper.GetReadonly(this.Arguments)??Enumerable<IMetadataExpression>.Empty; }
}
IMethodReference ICustomAttribute.Constructor {
get { return this.Constructor; }
}
IEnumerable<IMetadataNamedArgument> ICustomAttribute.NamedArguments {
get { return IteratorHelper. GetReadonly(this.NamedArguments)??Enumerable<IMetadataNamedArgument>.Empty; }
}
ushort ICustomAttribute.NumberOfNamedArguments {
get {
if (this.NamedArguments == null) return 0;
return (ushort)this.NamedArguments.Length;
}
}
public ITypeReference Type {
get {
ITypeReference/*?*/ moduleTypeRef = this.Constructor.ContainingType;
if (moduleTypeRef == null)
return Dummy.TypeReference;
return moduleTypeRef;
}
}
#endregion
}
internal sealed class SecurityCustomAttribute : ICustomAttribute {
internal readonly SecurityAttribute ContainingSecurityAttribute;
internal readonly IMethodReference ConstructorReference;
internal readonly IMetadataNamedArgument[]/*?*/ NamedArguments;
internal SecurityCustomAttribute(SecurityAttribute containingSecurityAttribute, IMethodReference constructorReference, IMetadataNamedArgument[]/*?*/ namedArguments) {
this.ContainingSecurityAttribute = containingSecurityAttribute;
this.ConstructorReference = constructorReference;
this.NamedArguments = namedArguments;
}
#region ICustomAttribute Members
IEnumerable<IMetadataExpression> ICustomAttribute.Arguments {
get { return Enumerable<IMetadataExpression>.Empty; }
}
public IMethodReference Constructor {
get { return this.ConstructorReference; }
}
IEnumerable<IMetadataNamedArgument> ICustomAttribute.NamedArguments {
get { return IteratorHelper.GetReadonly(this.NamedArguments)??Enumerable<IMetadataNamedArgument>.Empty; }
}
ushort ICustomAttribute.NumberOfNamedArguments {
get {
if (this.NamedArguments == null) return 0;
return (ushort)this.NamedArguments.Length;
}
}
public ITypeReference Type {
get { return this.ConstructorReference.ContainingType; }
}
#endregion
}
internal sealed class SecurityAttribute : MetadataObject, ISecurityAttribute {
internal readonly SecurityAction Action;
internal readonly uint DeclSecurityRowId;
internal SecurityAttribute(
PEFileToObjectModel peFileToObjectModel,
uint declSecurityRowId,
SecurityAction action
)
: base(peFileToObjectModel) {
this.DeclSecurityRowId = declSecurityRowId;
this.Action = action;
}
public override void Dispatch(IMetadataVisitor visitor) {
visitor.Visit(this);
}
public override void DispatchAsReference(IMetadataVisitor visitor) {
throw new InvalidOperationException();
}
internal override uint TokenValue {
get { return TokenTypeIds.Permission | this.DeclSecurityRowId; }
}
protected override IEnumerable<ICustomAttribute> GetAttributes() {
return this.PEFileToObjectModel.GetSecurityAttributeData(this);
}
#region ISecurityAttribute Members
SecurityAction ISecurityAttribute.Action {
get { return this.Action; }
}
#endregion
}
internal sealed class NamespaceName {
internal readonly IName FullyQualifiedName;
internal readonly NamespaceName/*?*/ ParentNamespaceName;
internal readonly IName Name;
internal NamespaceName(INameTable nameTable, NamespaceName/*?*/ parentNamespaceName, IName name) {
this.ParentNamespaceName = parentNamespaceName;
this.Name = name;
if (parentNamespaceName == null)
this.FullyQualifiedName = name;
else
this.FullyQualifiedName = nameTable.GetNameFor(parentNamespaceName.FullyQualifiedName.Value + "." + name);
}
internal IUnitNamespace/*?*/ Resolve(IModule module) {
Contract.Requires(module != null);
IUnitNamespace containingNamespace;
if (this.ParentNamespaceName == null)
containingNamespace = module.UnitNamespaceRoot;
else
containingNamespace = this.ParentNamespaceName.Resolve(module);
if (containingNamespace == null) return null;
foreach (var member in containingNamespace.GetMembersNamed(this.Name, false)) {
var ns = member as IUnitNamespace;
if (ns != null) return ns;
}
return null;
}
public override string ToString() {
return this.FullyQualifiedName.Value;
}
}
internal abstract class TypeName {
/// <param name="peFileToObjectModel">
/// Supplies the "owning file" associated with the current type name resolution operation.
/// Every top-level resolution operation conceptually happens in the context of a single
/// "owning" file. This file is recorded as the owner of all type reference objects
/// generated during resolution. The owning file is stable throughout resolution and is
/// therefore forwarded without modification whenever an outer resolution operation invokes
/// an inner resolution operation (e.g., when generic instantiation resolution invokes
/// resolution of a specific type argument).
///
/// The owning file is generally set to whichever file physically contains the serialized
/// text block that was parsed in order to generate the current TypeName instance.
/// </param>
/// <param name="module">
/// Supplies a reference to the module that should be used if the GetAsTypeReference
/// implementation needs to know which module is "targeted" by the reference being loaded.
/// For example, the value of this parameter dictates the module context used during the
/// TypeDef table lookup that occurs when a NamespaceTypeName is resolved to an
/// ITypeDefinition.
///
/// Once specified by the top-level caller, this argument can change at the following points
/// in the GetAsTypeReference call tree:
/// o AssemblyQualifiedTypeName::GetAsTypeReference steers the "module" argument to reflect
/// the fact that the targeted module has been overridden by whatever explicit assembly
/// qualifier that was found in the serialized type name.
/// o GenericTypeName::GetAsTypeReference steers the "module" argument to ensure that it
/// matches the "peFileToObjectModel" argument. This has the effect of "escaping" from any
/// explicit assembly qualifier that applied to the current generic type, ensuring that type
/// arguments are resolved against the stable root context that applies to the entire
/// outermost serialized type name production that is being parsed.
/// o If a generated type reference is redirected by the host, NamespaceTypeName::GetAsNominalType
/// steers the "module" argument to ensure that it targets whichever module is targeted by
/// the redirected type reference.
/// </param>
internal abstract ITypeReference/*?*/ GetAsTypeReference(
PEFileToObjectModel peFileToObjectModel,
IMetadataReaderModuleReference module
);
}
internal abstract class NominalTypeName : TypeName {
internal abstract uint GenericParameterCount { get; }
internal abstract INamedTypeReference/*?*/ GetAsNomimalType(
PEFileToObjectModel peFileToObjectModel,
IMetadataReaderModuleReference module
);
internal override ITypeReference GetAsTypeReference(
PEFileToObjectModel peFileToObjectModel, IMetadataReaderModuleReference module
) {
return this.GetAsNomimalType(peFileToObjectModel, module);
}
internal INamedTypeReference GetAsNamedTypeReference(
PEFileToObjectModel peFileToObjectModel, IMetadataReaderModuleReference module
) {
return this.GetAsNomimalType(peFileToObjectModel, module);
}
internal abstract INamedTypeDefinition/*?*/ ResolveNominalTypeName(IMetadataReaderModuleReference module);
internal abstract IName UnmangledTypeName { get; }
}
internal sealed class NamespaceTypeName : NominalTypeName {
readonly ushort genericParameterCount;
internal readonly NamespaceName/*?*/ NamespaceName;
internal readonly IName Name;
internal readonly IName unmanagledTypeName;
internal NamespaceTypeName(INameTable nameTable, NamespaceName/*?*/ namespaceName, IName name) {
this.NamespaceName = namespaceName;
this.Name = name;
string nameStr = null;
TypeCache.SplitMangledTypeName(name.Value, out nameStr, out this.genericParameterCount);
if (this.genericParameterCount > 0)
this.unmanagledTypeName = nameTable.GetNameFor(nameStr);
else
this.unmanagledTypeName = name;
}
internal override uint GenericParameterCount {
get { return this.genericParameterCount; }
}
internal override INamedTypeReference/*?*/ GetAsNomimalType(
PEFileToObjectModel peFileToObjectModel,
IMetadataReaderModuleReference module
) {
var typeRef = new NamespaceTypeNameTypeReference(module, this, peFileToObjectModel);
var redirectedTypeRef = peFileToObjectModel.ModuleReader.metadataReaderHost.Redirect(peFileToObjectModel.Module, typeRef) as INamespaceTypeReference;
if (redirectedTypeRef != typeRef && redirectedTypeRef != null) {
return redirectedTypeRef;
}
return typeRef;
}
private static NamespaceName/*?*/ GetNamespaceName(INameTable nameTable, INestedUnitNamespaceReference/*?*/ nestedUnitNamespaceReference) {
if (nestedUnitNamespaceReference == null) return null;
var parentNamespaceName = GetNamespaceName(nameTable, nestedUnitNamespaceReference.ContainingUnitNamespace as INestedUnitNamespaceReference);
return new NamespaceName(nameTable, parentNamespaceName, nestedUnitNamespaceReference.Name);
}
internal override IName UnmangledTypeName {
get {
return this.unmanagledTypeName;
}
}
internal override INamedTypeDefinition/*?*/ ResolveNominalTypeName(IMetadataReaderModuleReference module) {
var readerModule = module.ResolvedModule as Module;
if (readerModule != null) {
var peFileToObjectModel = readerModule.PEFileToObjectModel;
if (this.NamespaceName == null)
return peFileToObjectModel.ResolveNamespaceTypeDefinition(
peFileToObjectModel.NameTable.EmptyName,
this.Name
);
else
return peFileToObjectModel.ResolveNamespaceTypeDefinition(
this.NamespaceName.FullyQualifiedName,
this.Name
);
}
IUnitNamespace containingNamespace;
if (this.NamespaceName == null)
containingNamespace = module.ResolvedModule.UnitNamespaceRoot;
else
containingNamespace = this.NamespaceName.Resolve(module.ResolvedModule);
if (containingNamespace == null) return null;
foreach (var member in containingNamespace.GetMembersNamed(this.UnmangledTypeName, false)) {
var t = member as INamedTypeDefinition;
if (t != null && t.GenericParameterCount == this.GenericParameterCount) return t;
}
var assembly = module as IAssembly;
if (assembly == null) return null;
foreach (var alias in assembly.ExportedTypes) {
var nsAlias = alias as INamespaceAliasForType;
if (nsAlias == null || nsAlias.Name != this.UnmangledTypeName) continue;
var aliasedType = nsAlias.AliasedType.ResolvedType;
if (aliasedType.GenericParameterCount == this.GenericParameterCount) return aliasedType;
}
return null;
}
internal bool MangleName {
get { return this.Name.UniqueKey != this.unmanagledTypeName.UniqueKey; }
}
}
internal sealed class NestedTypeName : NominalTypeName {
readonly ushort genericParameterCount;
internal readonly NominalTypeName ContainingTypeName;
internal readonly IName Name;
internal readonly IName unmangledTypeName;
internal NestedTypeName(INameTable nameTable, NominalTypeName containingTypeName, IName mangledName) {
this.ContainingTypeName = containingTypeName;
this.Name = mangledName;
string nameStr = null;
TypeCache.SplitMangledTypeName(mangledName.Value, out nameStr, out this.genericParameterCount);
this.unmangledTypeName = nameTable.GetNameFor(nameStr);
}
internal override uint GenericParameterCount {
get { return this.genericParameterCount; }
}
internal override INamedTypeReference/*?*/ GetAsNomimalType(
PEFileToObjectModel peFileToObjectModel,
IMetadataReaderModuleReference module
) {
return new NestedTypeNameTypeReference(module, this, peFileToObjectModel);
}
internal override IName UnmangledTypeName {
get {
return this.unmangledTypeName;
}
}
internal override INamedTypeDefinition/*?*/ ResolveNominalTypeName(IMetadataReaderModuleReference module) {
var containingType = this.ContainingTypeName.ResolveNominalTypeName(module);
if (containingType == null) return null;
return TypeHelper.GetNestedType(containingType, this.UnmangledTypeName, (int)this.GenericParameterCount);
}
internal bool MangleName {
get { return this.Name.UniqueKey != this.unmangledTypeName.UniqueKey; }
}
}
internal sealed class GenericTypeName : TypeName {
internal readonly NominalTypeName GenericTemplate;
internal readonly List<TypeName> GenericArguments;
internal GenericTypeName(NominalTypeName genericTemplate, List<TypeName> genericArguments) {
this.GenericTemplate = genericTemplate;
this.GenericArguments = genericArguments;
}
internal override ITypeReference/*?*/ GetAsTypeReference(PEFileToObjectModel peFileToObjectModel, IMetadataReaderModuleReference module) {
var nominalType = this.GenericTemplate.GetAsNomimalType(peFileToObjectModel, module);
if (nominalType == null) return null;
int argumentUsed;
return this.GetSpecializedTypeReference(peFileToObjectModel, nominalType, out argumentUsed, mostNested: true);
}
private ITypeReference GetSpecializedTypeReference(PEFileToObjectModel peFileToObjectModel, INamedTypeReference nominalType, out int argumentUsed, bool mostNested) {
argumentUsed = 0;
int len = this.GenericArguments.Count;
var nestedType = nominalType as INestedTypeReference;
if (nestedType != null) {
var containingType = (INamedTypeReference)nestedType.ContainingType; // store to a local to prevent re-evaluation
var parentTemplate = this.GetSpecializedTypeReference(peFileToObjectModel, containingType, out argumentUsed, mostNested: false);
if (parentTemplate != containingType)
nominalType = new SpecializedNestedTypeReference(nestedType, parentTemplate, peFileToObjectModel.InternFactory);
}
var argsToUse = mostNested ? len-argumentUsed : nominalType.GenericParameterCount;
if (argsToUse == 0) return nominalType;
var genericArgumentsReferences = new ITypeReference[argsToUse];
for (int i = 0; i < argsToUse; ++i)
genericArgumentsReferences[i] = this.GenericArguments[i+argumentUsed].GetAsTypeReference(peFileToObjectModel, peFileToObjectModel.Module)??Dummy.TypeReference;
argumentUsed += argsToUse;
return GenericTypeInstanceReference.GetOrMake(nominalType, IteratorHelper.GetReadonly(genericArgumentsReferences), peFileToObjectModel.InternFactory);
}
}
internal sealed class ArrayTypeName : TypeName {
readonly TypeName ElementType;
readonly uint Rank; // 0 is SZArray
internal ArrayTypeName(TypeName elementType, uint rank) {
this.ElementType = elementType;
this.Rank = rank;
}
internal override ITypeReference/*?*/ GetAsTypeReference(PEFileToObjectModel peFileToObjectModel, IMetadataReaderModuleReference module) {
ITypeReference/*?*/ elementType = this.ElementType.GetAsTypeReference(peFileToObjectModel, module);
if (elementType == null) return null;
if (this.Rank == 0)
return Vector.GetVector(elementType, peFileToObjectModel.InternFactory);
else
return Matrix.GetMatrix(elementType, this.Rank, peFileToObjectModel.InternFactory);
}
}
internal sealed class PointerTypeName : TypeName {
internal readonly TypeName TargetType;
internal PointerTypeName(
TypeName targetType
) {
this.TargetType = targetType;
}
internal override ITypeReference/*?*/ GetAsTypeReference(
PEFileToObjectModel peFileToObjectModel,
IMetadataReaderModuleReference module
) {
var targetType = this.TargetType.GetAsTypeReference(peFileToObjectModel, module);
if (targetType == null) return null;
return PointerType.GetPointerType(targetType, peFileToObjectModel.InternFactory);
}
}
internal sealed class ManagedPointerTypeName : TypeName {
internal readonly TypeName TargetType;
internal ManagedPointerTypeName(
TypeName targetType
) {
this.TargetType = targetType;
}
internal override ITypeReference GetAsTypeReference(
PEFileToObjectModel peFileToObjectModel,
IMetadataReaderModuleReference module
) {
ITypeReference/*?*/ targetType = this.TargetType.GetAsTypeReference(peFileToObjectModel, module);
if (targetType == null) return null;
return ManagedPointerType.GetManagedPointerType(targetType, peFileToObjectModel.InternFactory);
}
}
internal sealed class AssemblyQualifiedTypeName : TypeName {
private TypeName TypeName;
private readonly AssemblyIdentity AssemblyIdentity;
private readonly bool Retargetable;
internal AssemblyQualifiedTypeName(TypeName typeName, AssemblyIdentity assemblyIdentity, bool retargetable) {
this.TypeName = typeName;
this.AssemblyIdentity = assemblyIdentity;
this.Retargetable = retargetable;
}
internal override ITypeReference/*?*/ GetAsTypeReference(PEFileToObjectModel peFileToObjectModel, IMetadataReaderModuleReference module) {
foreach (var aref in peFileToObjectModel.GetAssemblyReferences()) {
var assemRef = aref as AssemblyReference;
if (assemRef == null) continue;
if (assemRef.AssemblyIdentity.Equals(this.AssemblyIdentity))
return this.TypeName.GetAsTypeReference(peFileToObjectModel, assemRef);
}
if (module.ContainingAssembly.AssemblyIdentity.Equals(this.AssemblyIdentity))
return this.TypeName.GetAsTypeReference(peFileToObjectModel, module);
AssemblyFlags flags = (AssemblyFlags)0;
if (this.Retargetable) flags |= AssemblyFlags.Retargetable;
if (this.AssemblyIdentity.ContainsForeignTypes) flags |= AssemblyFlags.ContainsForeignTypes;
return this.TypeName.GetAsTypeReference(peFileToObjectModel, new AssemblyReference(peFileToObjectModel, 0, this.AssemblyIdentity, flags));
}
}
internal enum TypeNameTokenKind {
EOS,
Identifier,
Dot,
Plus,
OpenBracket,
CloseBracket,
Astrix,
Comma,
Ampersand,
Equals,
PublicKeyToken,
}
internal struct ScannerState {
internal readonly int CurrentIndex;
internal readonly TypeNameTokenKind CurrentTypeNameTokenKind;
internal readonly IName CurrentIdentifierInfo;
internal ScannerState(
int currentIndex,
TypeNameTokenKind currentTypeNameTokenKind,
IName currentIdentifierInfo
) {
this.CurrentIndex = currentIndex;
this.CurrentTypeNameTokenKind = currentTypeNameTokenKind;
this.CurrentIdentifierInfo = currentIdentifierInfo;
}
}
internal sealed class TypeNameParser {
readonly INameTable NameTable;
readonly string TypeName;
readonly int Length;
readonly IName Version;
readonly IName Retargetable;
readonly IName PublicKeyToken;
readonly IName Culture;
readonly IName neutral;
readonly IName ContentType;
readonly IName WindowsRuntime;
int CurrentIndex;
TypeNameTokenKind CurrentTypeNameTokenKind;
IName CurrentIdentifierInfo;
ScannerState ScannerSnapshot() {
return new ScannerState(
this.CurrentIndex,
this.CurrentTypeNameTokenKind,
this.CurrentIdentifierInfo
);
}
void RestoreScanner(
ScannerState scannerState
) {
this.CurrentIndex = scannerState.CurrentIndex;
this.CurrentTypeNameTokenKind = scannerState.CurrentTypeNameTokenKind;
this.CurrentIdentifierInfo = scannerState.CurrentIdentifierInfo;
}
void SkipSpaces() {
int currPtr = this.CurrentIndex;
string name = this.TypeName;
while (currPtr < this.Length && char.IsWhiteSpace(name[currPtr])) {
currPtr++;
}
this.CurrentIndex = currPtr;
}
static bool IsEndofIdentifier(
char c,
bool honorPunctuation,
bool assemblyName
) {
if (c == '[' || c == ']' || c == '*' || c == ',' || c == '&' || c == ' ' || char.IsWhiteSpace(c)) {
return true;
}
if (c == '+') {
return honorPunctuation;
}
if (assemblyName) {
if (c == '=')
return true;
} else {
if (c == '.') {
// '.' characters are embedded in type names synthesized for classes created for async methods.
// The method name appears in the class name, which makes ".ctor" (and maybe "..ctor"?) possible
// to find within class names. The method name is nested within '<' and '>' characters.
return honorPunctuation;
}
}
return false;
}
Version/*?*/ ScanVersion() {
this.SkipSpaces();
int currPtr = this.CurrentIndex;
string name = this.TypeName;
if (currPtr >= this.Length)
return null;
// TODO: build a Version number parser.
int endMark = name.IndexOf(',', currPtr);
if (endMark == -1) {
endMark = this.Length;
}
string versString = name.Substring(currPtr, endMark - currPtr);
Version/*?*/ vers = null;
try {
vers = new Version(versString);
} catch (FormatException) {
// Error
} catch (OverflowException) {
// Error
} catch (ArgumentOutOfRangeException) {
// Error
} catch (ArgumentException) {
// Error
}
this.CurrentIndex = endMark;
return vers;
}
bool ScanYesNo(out bool value) {
this.SkipSpaces();
int currPtr = this.CurrentIndex;
string name = this.TypeName;
if (currPtr + 3 <= this.Length && string.Compare(name, currPtr, "yes", 0, 3, StringComparison.OrdinalIgnoreCase) == 0) {
this.CurrentIndex += 3;
value = true;
return true;
}
if (currPtr + 2 <= this.Length && string.Compare(name, currPtr, "no", 0, 2, StringComparison.OrdinalIgnoreCase) == 0) {
this.CurrentIndex += 2;
value = false;
return true;
}
value = false;
return false;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
byte[] ScanPublicKeyToken() {
this.SkipSpaces();
int currPtr = this.CurrentIndex;
string name = this.TypeName;
if (currPtr + 4 <= this.Length && string.Compare(name, currPtr, "null", 0, 4, StringComparison.OrdinalIgnoreCase) == 0) {
this.CurrentIndex += 4;
return TypeCache.EmptyByteArray;
}
if (currPtr + 16 > this.Length) {
return TypeCache.EmptyByteArray;
}
string val = name.Substring(currPtr, 16);
this.CurrentIndex += 16;
ulong result = 0;
try {
result = ulong.Parse(val, System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.InvariantCulture);
} catch {
return TypeCache.EmptyByteArray;
}
byte[] pkToken = new byte[8];
for (int i = 7; i >= 0; --i) {
pkToken[i] = (byte)result;
result >>= 8;
}
return pkToken;
}
void NextToken(bool assemblyName) {
this.SkipSpaces();
if (this.CurrentIndex >= this.TypeName.Length) {
this.CurrentTypeNameTokenKind = TypeNameTokenKind.EOS;
return;
}
switch (this.TypeName[this.CurrentIndex]) {
case '[':
this.CurrentTypeNameTokenKind = TypeNameTokenKind.OpenBracket;
this.CurrentIndex++;
break;
case ']':
this.CurrentTypeNameTokenKind = TypeNameTokenKind.CloseBracket;
this.CurrentIndex++;
break;
case '*':
this.CurrentTypeNameTokenKind = TypeNameTokenKind.Astrix;
this.CurrentIndex++;
break;
case '.':
this.CurrentTypeNameTokenKind = TypeNameTokenKind.Dot;
this.CurrentIndex++;
break;
case '+':
this.CurrentTypeNameTokenKind = TypeNameTokenKind.Plus;
this.CurrentIndex++;
break;
case ',':
this.CurrentTypeNameTokenKind = TypeNameTokenKind.Comma;
this.CurrentIndex++;
break;
case '&':
this.CurrentTypeNameTokenKind = TypeNameTokenKind.Ampersand;
this.CurrentIndex++;
break;
case '=':
if (assemblyName) {
this.CurrentTypeNameTokenKind = TypeNameTokenKind.Equals;
this.CurrentIndex++;
break;
}
goto default;
default: {
int currIndex = this.CurrentIndex;
StringBuilder sb = StringBuilderCache.Acquire();
string name = this.TypeName;
int arrowNesting = 0;
while (currIndex < this.Length) {
char c = name[currIndex];
if (TypeNameParser.IsEndofIdentifier(c, arrowNesting <= 0, assemblyName))
break;
if (c == '\\') {
currIndex++;
if (currIndex < this.Length) {
sb.Append(name[currIndex]);
currIndex++;
} else {
break;
}
} else {
sb.Append(c);
currIndex++;
if (c == '<') {
// In naming stuff synthesized for async, the C# compiler encloses name text that can contain punctuation like '.' and '+' characters in '<' and '>'.
arrowNesting++;
}
else if (c == '>') {
arrowNesting--;
}
}
}
this.CurrentIndex = currIndex;
this.CurrentIdentifierInfo = this.NameTable.GetNameFor(StringBuilderCache.GetStringAndRelease(sb));
this.CurrentTypeNameTokenKind = TypeNameTokenKind.Identifier;
break;
}
}
}
static bool IsTypeNameStart(
TypeNameTokenKind typeNameTokenKind
) {
return typeNameTokenKind == TypeNameTokenKind.Identifier
|| typeNameTokenKind == TypeNameTokenKind.OpenBracket;
}
internal TypeNameParser(
INameTable nameTable,
string typeName
) {
this.NameTable = nameTable;
this.TypeName = typeName;
this.Length = typeName.Length;
this.Version = nameTable.GetNameFor("Version");
this.Retargetable = nameTable.GetNameFor("Retargetable");
this.PublicKeyToken = nameTable.GetNameFor("PublicKeyToken");
this.Culture = nameTable.GetNameFor("Culture");
this.neutral = nameTable.GetNameFor("neutral");
this.ContentType = nameTable.GetNameFor("ContentType");
this.WindowsRuntime = nameTable.GetNameFor("WindowsRuntime");
this.CurrentIdentifierInfo = nameTable.EmptyName;
this.NextToken(false);
}
NamespaceTypeName/*?*/ ParseNamespaceTypeName() {
if (this.CurrentTypeNameTokenKind != TypeNameTokenKind.Identifier) {
return null;
}
IName lastName = this.CurrentIdentifierInfo;
NamespaceName/*?*/ currNsp = null;
this.NextToken(false);
while (this.CurrentTypeNameTokenKind == TypeNameTokenKind.Dot) {
this.NextToken(false);
if (this.CurrentTypeNameTokenKind != TypeNameTokenKind.Identifier) {
return null;
}
currNsp = new NamespaceName(this.NameTable, currNsp, lastName);
lastName = this.CurrentIdentifierInfo;
this.NextToken(false);
}
return new NamespaceTypeName(this.NameTable, currNsp, lastName);
}
TypeName/*?*/ ParseGenericTypeArgument() {
if (this.CurrentTypeNameTokenKind == TypeNameTokenKind.OpenBracket) {
this.NextToken(false);
TypeName/*?*/ retTypeName = this.ParseTypeNameWithPossibleAssemblyName();
if (retTypeName == null) {
return null;
}
if (this.CurrentTypeNameTokenKind != TypeNameTokenKind.CloseBracket) {
return null;
}
this.NextToken(false);
return retTypeName;
} else {
return this.ParseFullName();
}
}
NominalTypeName/*?*/ ParseNominalTypeName() {
NominalTypeName/*?*/ nomTypeName = this.ParseNamespaceTypeName();
if (nomTypeName == null)
return null;
while (this.CurrentTypeNameTokenKind == TypeNameTokenKind.Plus) {
this.NextToken(false);
if (this.CurrentTypeNameTokenKind != TypeNameTokenKind.Identifier) {
return null;
}
nomTypeName = new NestedTypeName(this.NameTable, nomTypeName, this.CurrentIdentifierInfo);
this.NextToken(false);
}
return nomTypeName;
}
TypeName/*?*/ ParsePossiblyGenericTypeName() {
NominalTypeName/*?*/ nomTypeName = this.ParseNominalTypeName();
if (nomTypeName == null)
return null;
if (this.CurrentTypeNameTokenKind == TypeNameTokenKind.OpenBracket) {
ScannerState scannerSnapshot = this.ScannerSnapshot();
this.NextToken(false);
if (TypeNameParser.IsTypeNameStart(this.CurrentTypeNameTokenKind)) {
List<TypeName> genArgList = new List<TypeName>();
TypeName/*?*/ genArg = this.ParseGenericTypeArgument();
if (genArg == null)
return null;
genArgList.Add(genArg);
while (this.CurrentTypeNameTokenKind == TypeNameTokenKind.Comma) {
this.NextToken(false);
genArg = this.ParseGenericTypeArgument();
if (genArg == null)
return null;
genArgList.Add(genArg);
}
if (this.CurrentTypeNameTokenKind != TypeNameTokenKind.CloseBracket) {
return null;
}
this.NextToken(false);
return new GenericTypeName(nomTypeName, genArgList);
}
this.RestoreScanner(scannerSnapshot);
}
return nomTypeName;
}
TypeName/*?*/ ParseFullName() {
TypeName/*?*/ typeName = this.ParsePossiblyGenericTypeName();
if (typeName == null)
return null;
for (; ; ) {
if (this.CurrentTypeNameTokenKind == TypeNameTokenKind.Astrix) {
this.NextToken(false);
typeName = new PointerTypeName(typeName);
} else if (this.CurrentTypeNameTokenKind == TypeNameTokenKind.OpenBracket) {
this.NextToken(false);
uint rank;
if (this.CurrentTypeNameTokenKind == TypeNameTokenKind.Astrix) {
rank = 1;
} else if (this.CurrentTypeNameTokenKind == TypeNameTokenKind.Comma) {
rank = 1;
while (this.CurrentTypeNameTokenKind == TypeNameTokenKind.Comma) {
this.NextToken(false);
rank++;
}
} else if (this.CurrentTypeNameTokenKind == TypeNameTokenKind.CloseBracket) {
rank = 0; // SZArray Case
} else {
return null;
}
if (this.CurrentTypeNameTokenKind != TypeNameTokenKind.CloseBracket) {
return null;
}
this.NextToken(false);
typeName = new ArrayTypeName(typeName, rank);
} else {
break;
}
}
if (this.CurrentTypeNameTokenKind == TypeNameTokenKind.Ampersand) {
this.NextToken(false);
typeName = new ManagedPointerTypeName(typeName);
}
return typeName;
}
AssemblyIdentity/*?*/ ParseAssemblyName(out bool retargetable) {
retargetable = false;
if (this.CurrentTypeNameTokenKind != TypeNameTokenKind.Identifier) {
return null;
}
IName assemblyName = this.CurrentIdentifierInfo;
this.NextToken(true);
bool versionRead = false;
Version/*?*/ version = Dummy.Version;
bool pkTokenRead = false;
byte[] publicKeyToken = TypeCache.EmptyByteArray;
bool cultureRead = false;
bool retargetableRead = false;
bool containsForeignTypes = false;
IName culture = this.NameTable.EmptyName;
while (this.CurrentTypeNameTokenKind == TypeNameTokenKind.Comma) {
this.NextToken(true);
if (this.CurrentTypeNameTokenKind != TypeNameTokenKind.Identifier)
return null;
IName infoIdent = this.CurrentIdentifierInfo;
this.NextToken(true);
if (this.CurrentTypeNameTokenKind != TypeNameTokenKind.Equals)
return null;
if (infoIdent.UniqueKeyIgnoringCase == this.Culture.UniqueKeyIgnoringCase) {
this.NextToken(true);
if (cultureRead || this.CurrentTypeNameTokenKind != TypeNameTokenKind.Identifier)
return null;
culture = this.CurrentIdentifierInfo;
if (culture.UniqueKeyIgnoringCase == this.neutral.UniqueKeyIgnoringCase)
culture = this.NameTable.EmptyName;
cultureRead = true;
} else if (infoIdent.UniqueKeyIgnoringCase == this.Version.UniqueKeyIgnoringCase) {
if (versionRead)
return null;
version = this.ScanVersion();
if (version == null)
return null;
versionRead = true;
} else if (infoIdent.UniqueKeyIgnoringCase == this.PublicKeyToken.UniqueKeyIgnoringCase) {
if (pkTokenRead)
return null;
publicKeyToken = this.ScanPublicKeyToken();
//if (IteratorHelper.EnumerableIsEmpty(publicKeyToken))
// return null;
pkTokenRead = true;
} else if (infoIdent.UniqueKeyIgnoringCase == this.Retargetable.UniqueKeyIgnoringCase) {
if (retargetableRead)
return null;
if (!this.ScanYesNo(out retargetable))
return null;
retargetableRead = true;
} else if (infoIdent.UniqueKeyIgnoringCase == this.ContentType.UniqueKeyIgnoringCase) {
this.NextToken(true);
if (this.CurrentIdentifierInfo.UniqueKeyIgnoringCase == this.WindowsRuntime.UniqueKeyIgnoringCase)
{
containsForeignTypes = true;
}
} else {
// TODO: Error: Identifier in assembly name.
while (this.CurrentTypeNameTokenKind != TypeNameTokenKind.Comma && this.CurrentTypeNameTokenKind != TypeNameTokenKind.CloseBracket && this.CurrentTypeNameTokenKind != TypeNameTokenKind.EOS) {
this.NextToken(true);
}
}
this.NextToken(true);
}
// TODO: PublicKey also is possible...
return new AssemblyIdentity(assemblyName, culture.Value, version, publicKeyToken, string.Empty, containsForeignTypes);
}
TypeName/*?*/ ParseTypeNameWithPossibleAssemblyName() {
TypeName/*?*/ tn = this.ParseFullName();
if (tn == null)
return null;
if (this.CurrentTypeNameTokenKind == TypeNameTokenKind.Comma) {
this.NextToken(true);
bool retargetable = false;
AssemblyIdentity/*?*/ assemIdentity = this.ParseAssemblyName(out retargetable);
if (assemIdentity == null)
return null;
tn = new AssemblyQualifiedTypeName(tn, assemIdentity, retargetable);
}
return tn;
}
internal TypeName/*?*/ ParseTypeName() {
TypeName/*?*/ tn = this.ParseTypeNameWithPossibleAssemblyName();
if (tn == null || this.CurrentTypeNameTokenKind != TypeNameTokenKind.EOS)
return null;
return tn;
}
}
internal class TypeNameDeserializer {
private readonly PEFileToObjectModel fileToUseAsDeserializationContext;
internal TypeNameDeserializer(PEFileToObjectModel fileToUseAsDeserializationContext) {
this.fileToUseAsDeserializationContext = fileToUseAsDeserializationContext;
}
internal ITypeReference TryGetDeserializedTypeReference(string serializedTypeName) {
PEFileToObjectModel deserializationContext = this.fileToUseAsDeserializationContext;
TypeNameParser typeNameParser = new TypeNameParser(deserializationContext.NameTable, serializedTypeName);
TypeName typeName = typeNameParser.ParseTypeName();
return (typeName == null) ? null : typeName.GetAsTypeReference(deserializationContext, deserializationContext.ContainingAssembly);
}
}
}
namespace Microsoft.Cci.MetadataReader {
internal abstract class AttributeDecoder {
internal bool decodeFailed;
internal bool morePermutationsArePossible;
readonly protected PEFileToObjectModel PEFileToObjectModel;
protected MemoryReader SignatureMemoryReader;
protected object/*?*/ GetPrimitiveValue(ITypeReference type) {
switch (type.TypeCode) {
case PrimitiveTypeCode.Int8:
if (this.SignatureMemoryReader.Offset+1 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return (sbyte)0;
}
return this.SignatureMemoryReader.ReadSByte();
case PrimitiveTypeCode.Int16:
if (this.SignatureMemoryReader.Offset+2 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return (short)0;
}
return this.SignatureMemoryReader.ReadInt16();
case PrimitiveTypeCode.Int32:
if (this.SignatureMemoryReader.Offset+4 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return (int)0;
}
return this.SignatureMemoryReader.ReadInt32();
case PrimitiveTypeCode.Int64:
if (this.SignatureMemoryReader.Offset+8 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return (long)0;
}
return this.SignatureMemoryReader.ReadInt64();
case PrimitiveTypeCode.UInt8:
if (this.SignatureMemoryReader.Offset+1 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return (byte)0;
}
return this.SignatureMemoryReader.ReadByte();
case PrimitiveTypeCode.UInt16:
if (this.SignatureMemoryReader.Offset+2 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return (ushort)0;
}
return this.SignatureMemoryReader.ReadUInt16();
case PrimitiveTypeCode.UInt32:
if (this.SignatureMemoryReader.Offset+4 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return (uint)0;
}
return this.SignatureMemoryReader.ReadUInt32();
case PrimitiveTypeCode.UInt64:
if (this.SignatureMemoryReader.Offset+8 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return (ulong)0;
}
return this.SignatureMemoryReader.ReadUInt64();
case PrimitiveTypeCode.Float32:
if (this.SignatureMemoryReader.Offset+4 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return (float)0;
}
return this.SignatureMemoryReader.ReadSingle();
case PrimitiveTypeCode.Float64:
if (this.SignatureMemoryReader.Offset+8 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return (double)0;
}
return this.SignatureMemoryReader.ReadDouble();
case PrimitiveTypeCode.Boolean: {
if (this.SignatureMemoryReader.Offset+1 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return false;
}
byte val = this.SignatureMemoryReader.ReadByte();
return val == 1;
}
case PrimitiveTypeCode.Char:
if (this.SignatureMemoryReader.Offset+2 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return (char)0;
}
return this.SignatureMemoryReader.ReadChar();
}
this.decodeFailed = true;
return null;
}
protected string/*?*/ GetSerializedString() {
int byteLen = this.SignatureMemoryReader.ReadCompressedUInt32();
if (byteLen == -1)
return null;
if (byteLen == 0)
return string.Empty;
if (this.SignatureMemoryReader.Offset+byteLen > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return null;
}
return this.SignatureMemoryReader.ReadUTF8WithSize(byteLen);
}
protected ITypeReference/*?*/ GetFieldOrPropType() {
if (this.SignatureMemoryReader.Offset+1 > this.SignatureMemoryReader.Length) {
this.decodeFailed = true;
return null;
}
byte elementByte = this.SignatureMemoryReader.ReadByte();
switch (elementByte) {
case SerializationType.Boolean:
return this.PEFileToObjectModel.PlatformType.SystemBoolean;
case SerializationType.Char:
return this.PEFileToObjectModel.PlatformType.SystemChar;
case SerializationType.Int8:
return this.PEFileToObjectModel.PlatformType.SystemInt8;
case SerializationType.UInt8:
return this.PEFileToObjectModel.PlatformType.SystemUInt8;
case SerializationType.Int16:
return this.PEFileToObjectModel.PlatformType.SystemInt16;
case SerializationType.UInt16:
return this.PEFileToObjectModel.PlatformType.SystemUInt16;
case SerializationType.Int32:
return this.PEFileToObjectModel.PlatformType.SystemInt32;
case SerializationType.UInt32:
return this.PEFileToObjectModel.PlatformType.SystemUInt32;
case SerializationType.Int64:
return this.PEFileToObjectModel.PlatformType.SystemInt64;
case SerializationType.UInt64:
return this.PEFileToObjectModel.PlatformType.SystemUInt64;
case SerializationType.Single:
return this.PEFileToObjectModel.PlatformType.SystemFloat32;
case SerializationType.Double:
return this.PEFileToObjectModel.PlatformType.SystemFloat64;
case SerializationType.String:
return this.PEFileToObjectModel.PlatformType.SystemString;
case SerializationType.SZArray: {
ITypeReference/*?*/ elementType = this.GetFieldOrPropType();
if (elementType == null) return null;
return Vector.GetVector(elementType, this.PEFileToObjectModel.InternFactory);
}
case SerializationType.Type:
return this.PEFileToObjectModel.PlatformType.SystemType;
case SerializationType.TaggedObject:
return this.PEFileToObjectModel.PlatformType.SystemObject;
case SerializationType.Enum: {
string/*?*/ typeName = this.GetSerializedString();
if (typeName == null)
return null;
var result = this.PEFileToObjectModel.GetSerializedTypeNameAsTypeReference(typeName);
var tnr = result as TypeNameTypeReference;
if (tnr == null) {
var specializedNestedType = result as ISpecializedNestedTypeReference;
if (specializedNestedType != null)
tnr = specializedNestedType.UnspecializedVersion as TypeNameTypeReference;
}
if (tnr != null) tnr.IsEnum = true;
return result;
}
}
this.decodeFailed = true;
return null;
}
protected TypeName/*?*/ ConvertToTypeName(
string serializedTypeName
) {
TypeNameParser typeNameParser = new TypeNameParser(this.PEFileToObjectModel.NameTable, serializedTypeName);
TypeName/*?*/ typeName = typeNameParser.ParseTypeName();
return typeName;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
protected ExpressionBase/*?*/ ReadSerializedValue(ITypeReference type) {
switch (type.TypeCode) {
case PrimitiveTypeCode.Int8:
case PrimitiveTypeCode.Int16:
case PrimitiveTypeCode.Int32:
case PrimitiveTypeCode.Int64:
case PrimitiveTypeCode.UInt8:
case PrimitiveTypeCode.UInt16:
case PrimitiveTypeCode.UInt32:
case PrimitiveTypeCode.UInt64:
case PrimitiveTypeCode.Float32:
case PrimitiveTypeCode.Float64:
case PrimitiveTypeCode.Boolean:
case PrimitiveTypeCode.Char:
return new ConstantExpression(type, this.GetPrimitiveValue(type));
case PrimitiveTypeCode.String:
return new ConstantExpression(type, this.GetSerializedString());
default:
var typeDef = type.ResolvedType;
if (!(typeDef is Dummy)) {
if (typeDef.IsEnum)
return new ConstantExpression(type, this.GetPrimitiveValue(typeDef.UnderlyingType));
}
if (TypeHelper.TypesAreEquivalent(type, this.PEFileToObjectModel.PlatformType.SystemObject)) {
ITypeReference/*?*/ underlyingType = this.GetFieldOrPropType();
if (underlyingType == null) return null;
return this.ReadSerializedValue(underlyingType);
}
if (TypeHelper.TypesAreEquivalent(type, this.PEFileToObjectModel.PlatformType.SystemType)) {
string/*?*/ typeNameStr = this.GetSerializedString();
if (typeNameStr == null) {
return new ConstantExpression(this.PEFileToObjectModel.PlatformType.SystemType, null);
}
return new TypeOfExpression(this.PEFileToObjectModel, this.PEFileToObjectModel.GetSerializedTypeNameAsTypeReference(typeNameStr));
}
var vectorType = type as IArrayTypeReference;
if (vectorType != null) {
ITypeReference/*?*/ elementType = vectorType.ElementType;
if (elementType == null) {
this.decodeFailed = true;
return null;
}
int size = this.SignatureMemoryReader.ReadInt32();
if (size == -1) {
return new ConstantExpression(vectorType, null);
}
ExpressionBase[] arrayElements = new ExpressionBase[size];
for (int i = 0; i < size; ++i) {
ExpressionBase/*?*/ expr = this.ReadSerializedValue(elementType);
if (expr == null) {
this.decodeFailed = true;
return null;
}
arrayElements[i] = expr;
}
return new ArrayExpression(vectorType, new EnumerableArrayWrapper<ExpressionBase, IMetadataExpression>(arrayElements, Dummy.Expression));
} else {
// If the metadata is correct, type must be a reference to an enum type.
// Problem is, that without resolving this reference, it is not possible to know how many bytes to consume for the enum value
// We'll let the host deal with this by guessing
ITypeReference underlyingType;
switch (this.PEFileToObjectModel.ModuleReader.metadataReaderHost.GuessUnderlyingTypeSizeOfUnresolvableReferenceToEnum(type)) {
case 1: underlyingType = this.PEFileToObjectModel.PlatformType.SystemInt8; break;
case 2: underlyingType = this.PEFileToObjectModel.PlatformType.SystemInt16; break;
case 4: underlyingType = this.PEFileToObjectModel.PlatformType.SystemInt32; break;
case 8: underlyingType = this.PEFileToObjectModel.PlatformType.SystemInt64; break;
default:
this.decodeFailed = true; this.morePermutationsArePossible = false;
return new ConstantExpression(type, 0);
}
return new ConstantExpression(type, this.GetPrimitiveValue(underlyingType));
}
}
}
protected AttributeDecoder(
PEFileToObjectModel peFileToObjectModel,
MemoryReader signatureMemoryReader
) {
this.PEFileToObjectModel = peFileToObjectModel;
this.SignatureMemoryReader = signatureMemoryReader;
this.morePermutationsArePossible = true;
}
}
internal sealed class CustomAttributeDecoder : AttributeDecoder {
internal readonly ICustomAttribute CustomAttribute;
internal CustomAttributeDecoder(PEFileToObjectModel peFileToObjectModel, MemoryReader signatureMemoryReader, uint customAttributeRowId,
IMethodReference attributeConstructor)
: base(peFileToObjectModel, signatureMemoryReader) {
this.CustomAttribute = Dummy.CustomAttribute;
ushort prolog = this.SignatureMemoryReader.ReadUInt16();
if (prolog != SerializationType.CustomAttributeStart) return;
int len = attributeConstructor.ParameterCount;
IMetadataExpression[]/*?*/ exprList = len == 0 ? null : new IMetadataExpression[len];
int i = 0;
foreach (var parameter in attributeConstructor.Parameters) {
var parameterType = parameter.Type;
if (parameterType is Dummy) {
// Error...
return;
}
ExpressionBase/*?*/ argument = this.ReadSerializedValue(parameterType);
if (argument == null) {
// Error...
this.decodeFailed = true;
return;
}
exprList[i++] = argument;
}
IMetadataNamedArgument[]/*?*/ namedArgumentArray = null;
if (2 <= (int)this.SignatureMemoryReader.RemainingBytes) {
ushort numOfNamedArgs = this.SignatureMemoryReader.ReadUInt16();
if (numOfNamedArgs > 0) {
namedArgumentArray = new IMetadataNamedArgument[numOfNamedArgs];
for (i = 0; i < numOfNamedArgs; ++i) {
if (0 >= (int)this.SignatureMemoryReader.RemainingBytes) break;
bool isField = this.SignatureMemoryReader.ReadByte() == SerializationType.Field;
ITypeReference/*?*/ memberType = this.GetFieldOrPropType();
if (memberType == null) {
// Error...
return;
}
string/*?*/ memberStr = this.GetSerializedString();
if (memberStr == null)
return;
IName memberName = this.PEFileToObjectModel.NameTable.GetNameFor(memberStr);
ExpressionBase/*?*/ value = this.ReadSerializedValue(memberType);
if (value == null) {
// Error...
return;
}
ITypeReference/*?*/ moduleTypeRef = attributeConstructor.ContainingType;
if (moduleTypeRef == null) {
// Error...
return;
}
FieldOrPropertyNamedArgumentExpression namedArg = new FieldOrPropertyNamedArgumentExpression(memberName, moduleTypeRef, isField, memberType, value);
namedArgumentArray[i] = namedArg;
}
}
}
this.CustomAttribute = peFileToObjectModel.ModuleReader.metadataReaderHost.Rewrite(peFileToObjectModel.Module,
new CustomAttribute(peFileToObjectModel, customAttributeRowId, attributeConstructor, exprList, namedArgumentArray));
}
}
internal sealed class SecurityAttributeDecoder20 : AttributeDecoder {
internal readonly IEnumerable<ICustomAttribute> SecurityAttributes;
SecurityCustomAttribute/*?*/ ReadSecurityAttribute(SecurityAttribute securityAttribute) {
string/*?*/ typeNameStr = this.GetSerializedString();
if (typeNameStr == null)
return null;
ITypeReference/*?*/ moduleTypeReference = this.PEFileToObjectModel.GetSerializedTypeNameAsTypeReference(typeNameStr);
if (moduleTypeReference == null)
return null;
IMethodReference ctorReference = Dummy.MethodReference;
ITypeDefinition attributeType = moduleTypeReference.ResolvedType;
if (!(attributeType is Dummy)) {
foreach (ITypeDefinitionMember member in attributeType.GetMembersNamed(this.PEFileToObjectModel.NameTable.Ctor, false)) {
IMethodDefinition/*?*/ method = member as IMethodDefinition;
if (method == null) continue;
if (!IteratorHelper.EnumerableHasLength(method.Parameters, 1)) continue;
//TODO: check that parameter has the right type
ctorReference = method;
break;
}
} else {
int ctorKey = this.PEFileToObjectModel.NameTable.Ctor.UniqueKey;
foreach (ITypeMemberReference mref in this.PEFileToObjectModel.GetMemberReferences()) {
IMethodReference/*?*/ methRef = mref as IMethodReference;
if (methRef == null) continue;
if (methRef.ContainingType.InternedKey != moduleTypeReference.InternedKey) continue;
if (methRef.Name.UniqueKey != ctorKey) continue;
if (!IteratorHelper.EnumerableHasLength(methRef.Parameters, 1)) continue;
//TODO: check that parameter has the right type
ctorReference = methRef;
break;
}
}
if (ctorReference is Dummy) {
ctorReference = new MethodReference(this.PEFileToObjectModel.ModuleReader.metadataReaderHost, moduleTypeReference,
CallingConvention.Default|CallingConvention.HasThis, this.PEFileToObjectModel.PlatformType.SystemVoid,
this.PEFileToObjectModel.NameTable.Ctor, 0, this.PEFileToObjectModel.PlatformType.SystemSecurityPermissionsSecurityAction);
}
this.SignatureMemoryReader.ReadCompressedUInt32(); // BlobSize...
int numOfNamedArgs = this.SignatureMemoryReader.ReadCompressedUInt32();
FieldOrPropertyNamedArgumentExpression[]/*?*/ namedArgumentArray = null;
if (numOfNamedArgs > 0) {
namedArgumentArray = new FieldOrPropertyNamedArgumentExpression[numOfNamedArgs];
for (int i = 0; i < numOfNamedArgs; ++i) {
bool isField = this.SignatureMemoryReader.ReadByte() == SerializationType.Field;
ITypeReference/*?*/ memberType = this.GetFieldOrPropType();
if (memberType == null)
return null;
string/*?*/ memberStr = this.GetSerializedString();
if (memberStr == null)
return null;
IName memberName = this.PEFileToObjectModel.NameTable.GetNameFor(memberStr);
ExpressionBase/*?*/ value = this.ReadSerializedValue(memberType);
if (value == null)
return null;
namedArgumentArray[i] = new FieldOrPropertyNamedArgumentExpression(memberName, moduleTypeReference, isField, memberType, value);
}
}
return new SecurityCustomAttribute(securityAttribute, ctorReference, namedArgumentArray);
}
internal SecurityAttributeDecoder20(PEFileToObjectModel peFileToObjectModel, MemoryReader signatureMemoryReader, SecurityAttribute securityAttribute)
: base(peFileToObjectModel, signatureMemoryReader) {
this.SecurityAttributes = Enumerable<ICustomAttribute>.Empty;
byte prolog = this.SignatureMemoryReader.ReadByte();
if (prolog != SerializationType.SecurityAttribute20Start) return;
int numberOfAttributes = this.SignatureMemoryReader.ReadCompressedUInt32();
var securityCustomAttributes = new ICustomAttribute[numberOfAttributes];
for (int i = 0; i < numberOfAttributes; ++i) {
var secAttr = this.ReadSecurityAttribute(securityAttribute);
if (secAttr == null) {
// MDError...
return;
}
securityCustomAttributes[i] = secAttr;
}
this.SecurityAttributes = IteratorHelper.GetReadonly(securityCustomAttributes);
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Parallel.Tests
{
public static class ToLookupTests
{
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))]
public static void ILookup_MembersBehaveCorrectly(Labeled<ParallelQuery<int>> labeled, int count)
{
int NonExistentKey = count * 2;
ILookup<int, int> lookup = labeled.Item.ToLookup(x => x);
// Count
Assert.Equal(count, lookup.Count);
// Contains
Assert.All(lookup, group => lookup.Contains(group.Key));
Assert.False(lookup.Contains(NonExistentKey));
// Indexer
Assert.All(lookup, group => Assert.Equal(group, lookup[group.Key]));
Assert.Equal(Enumerable.Empty<int>(), lookup[NonExistentKey]);
// GetEnumerator
IEnumerator e1 = ((IEnumerable)lookup).GetEnumerator();
IEnumerator<IGrouping<int, int>> e2 = lookup.GetEnumerator();
while (e1.MoveNext())
{
e2.MoveNext();
Assert.Equal(((IGrouping<int, int>)e1.Current).Key, e2.Current.Key);
}
Assert.False(e2.MoveNext());
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void ToLookup(int count)
{
IntegerRangeSet seen = new IntegerRangeSet(0, count);
ILookup<int, int> lookup = UnorderedSources.Default(count).ToLookup(x => x * 2);
Assert.All(lookup,
group => { seen.Add(group.Key / 2); Assert.Equal(group.Key, Assert.Single(group) * 2); });
seen.AssertComplete();
Assert.Empty(lookup[-1]);
}
[Fact]
[OuterLoop]
public static void ToLookup_Longrunning()
{
ToLookup(Sources.OuterLoopCount);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void ToLookup_ElementSelector(int count)
{
IntegerRangeSet seen = new IntegerRangeSet(0, count);
ILookup<int, int> lookup = UnorderedSources.Default(count).ToLookup(x => x, y => y * 2);
Assert.All(lookup,
group => { seen.Add(group.Key); Assert.Equal(group.Key * 2, Assert.Single(group)); });
seen.AssertComplete();
Assert.Empty(lookup[-1]);
}
[Fact]
[OuterLoop]
public static void ToLookup_ElementSelector_Longrunning()
{
ToLookup_ElementSelector(Sources.OuterLoopCount);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void ToLookup_CustomComparator(int count)
{
IntegerRangeSet seen = new IntegerRangeSet(0, count);
ILookup<int, int> lookup = UnorderedSources.Default(count).ToLookup(x => x * 2, new ModularCongruenceComparer(count * 2));
Assert.All(lookup,
group => { seen.Add(group.Key / 2); Assert.Equal(group.Key, Assert.Single(group) * 2); });
seen.AssertComplete();
Assert.Empty(lookup[-1]);
}
[Fact]
[OuterLoop]
public static void ToLookup_CustomComparator_Longrunning()
{
ToLookup_CustomComparator(Sources.OuterLoopCount);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void ToLookup_ElementSelector_CustomComparator(int count)
{
IntegerRangeSet seen = new IntegerRangeSet(0, count);
ILookup<int, int> lookup = UnorderedSources.Default(count).ToLookup(x => x, y => y * 2, new ModularCongruenceComparer(count));
Assert.All(lookup,
group => { seen.Add(group.Key); Assert.Equal(group.Key * 2, Assert.Single(group)); });
seen.AssertComplete();
if (count < 1)
{
Assert.Empty(lookup[-1]);
}
}
[Theory]
[OuterLoop]
public static void ToLookup_ElementSelector_CustomComparator_Longrunning()
{
ToLookup_ElementSelector_CustomComparator(Sources.OuterLoopCount);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void ToLookup_DuplicateKeys(int count)
{
IntegerRangeSet seenOuter = new IntegerRangeSet(0, Math.Min(count, 2));
ILookup<int, int> lookup = UnorderedSources.Default(count).ToLookup(x => x % 2);
Assert.All(lookup,
group =>
{
seenOuter.Add(group.Key);
IntegerRangeSet seenInner = new IntegerRangeSet(0, (count + ((1 + group.Key) % 2)) / 2);
Assert.All(group, y => { Assert.Equal(group.Key, y % 2); seenInner.Add(y / 2); });
seenInner.AssertComplete();
});
seenOuter.AssertComplete();
Assert.Empty(lookup[-1]);
}
[Fact]
[OuterLoop]
public static void ToLookup_DuplicateKeys_Longrunning()
{
ToLookup_DuplicateKeys(Sources.OuterLoopCount);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void ToLookup_DuplicateKeys_ElementSelector(int count)
{
IntegerRangeSet seenOuter = new IntegerRangeSet(0, Math.Min(count, 2));
ILookup<int, int> lookup = UnorderedSources.Default(count).ToLookup(x => x % 2, y => -y);
Assert.All(lookup,
group =>
{
seenOuter.Add(group.Key);
IntegerRangeSet seenInner = new IntegerRangeSet(0, (count + ((1 + group.Key) % 2)) / 2);
Assert.All(group, y => { Assert.Equal(group.Key, -y % 2); seenInner.Add(-y / 2); });
seenInner.AssertComplete();
});
seenOuter.AssertComplete();
Assert.Empty(lookup[-1]);
}
[Fact]
[OuterLoop]
public static void ToLookup_DuplicateKeys_ElementSelector_Longrunning()
{
ToLookup_DuplicateKeys_ElementSelector(Sources.OuterLoopCount);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void ToLookup_DuplicateKeys_CustomComparator(int count)
{
IntegerRangeSet seenOuter = new IntegerRangeSet(0, Math.Min(count, 2));
ILookup<int, int> lookup = UnorderedSources.Default(count).ToLookup(x => x, new ModularCongruenceComparer(2));
Assert.All(lookup,
group =>
{
seenOuter.Add(group.Key % 2);
IntegerRangeSet seenInner = new IntegerRangeSet(0, (count + ((1 + group.Key) % 2)) / 2);
Assert.All(group, y => { Assert.Equal(group.Key % 2, y % 2); seenInner.Add(y / 2); });
seenInner.AssertComplete();
});
seenOuter.AssertComplete();
if (count < 2)
{
Assert.Empty(lookup[-1]);
}
}
[Fact]
[OuterLoop]
public static void ToLookup_DuplicateKeys_CustomComparator_Longrunning()
{
ToLookup_DuplicateKeys_CustomComparator(Sources.OuterLoopCount);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void ToLookup_DuplicateKeys_ElementSelector_CustomComparator(int count)
{
IntegerRangeSet seenOuter = new IntegerRangeSet(0, Math.Min(count, 2));
ILookup<int, int> lookup = UnorderedSources.Default(count).ToLookup(x => x, y => -y, new ModularCongruenceComparer(2));
Assert.All(lookup,
group =>
{
seenOuter.Add(group.Key % 2);
IntegerRangeSet seenInner = new IntegerRangeSet(0, (count + ((1 + group.Key) % 2)) / 2);
Assert.All(group, y => { Assert.Equal(group.Key % 2, -y % 2); seenInner.Add(-y / 2); });
seenInner.AssertComplete();
});
seenOuter.AssertComplete();
if (count < 2)
{
Assert.Empty(lookup[-1]);
}
}
[Fact]
[OuterLoop]
public static void ToLookup_DuplicateKeys_ElementSelector_CustomComparator_Longrunning()
{
ToLookup_DuplicateKeys_ElementSelector_CustomComparator(Sources.OuterLoopCount);
}
[Fact]
public static void ToDictionary_OperationCanceledException()
{
AssertThrows.EventuallyCanceled((source, canceler) => source.ToLookup(x => x, new CancelingEqualityComparer<int>(canceler)));
AssertThrows.EventuallyCanceled((source, canceler) => source.ToLookup(x => x, y => y, new CancelingEqualityComparer<int>(canceler)));
}
[Fact]
public static void ToLookup_AggregateException_Wraps_OperationCanceledException()
{
AssertThrows.OtherTokenCanceled((source, canceler) => source.ToLookup(x => x, new CancelingEqualityComparer<int>(canceler)));
AssertThrows.OtherTokenCanceled((source, canceler) => source.ToLookup(x => x, y => y, new CancelingEqualityComparer<int>(canceler)));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.ToLookup(x => x, new CancelingEqualityComparer<int>(canceler)));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.ToLookup(x => x, y => y, new CancelingEqualityComparer<int>(canceler)));
}
[Fact]
public static void ToLookup_OperationCanceledException_PreCanceled()
{
AssertThrows.AlreadyCanceled(source => source.ToLookup(x => x));
AssertThrows.AlreadyCanceled(source => source.ToLookup(x => x, EqualityComparer<int>.Default));
AssertThrows.AlreadyCanceled(source => source.ToLookup(x => x, y => y));
AssertThrows.AlreadyCanceled(source => source.ToLookup(x => x, y => y, EqualityComparer<int>.Default));
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 1 }, MemberType = typeof(UnorderedSources))]
public static void ToLookup_AggregateException(Labeled<ParallelQuery<int>> labeled, int count)
{
AssertThrows.Wrapped<DeliberateTestException>(() => labeled.Item.ToLookup((Func<int, int>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => labeled.Item.ToLookup((Func<int, int>)(x => { throw new DeliberateTestException(); }), y => y));
AssertThrows.Wrapped<DeliberateTestException>(() => labeled.Item.ToLookup(x => x, (Func<int, int>)(y => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => labeled.Item.ToLookup((Func<int, int>)(x => { throw new DeliberateTestException(); }), EqualityComparer<int>.Default));
AssertThrows.Wrapped<DeliberateTestException>(() => labeled.Item.ToLookup((Func<int, int>)(x => { throw new DeliberateTestException(); }), y => y, EqualityComparer<int>.Default));
AssertThrows.Wrapped<DeliberateTestException>(() => labeled.Item.ToLookup(x => x, (Func<int, int>)(y => { throw new DeliberateTestException(); }), EqualityComparer<int>.Default));
AssertThrows.Wrapped<DeliberateTestException>(() => labeled.Item.ToLookup(x => x, new FailingEqualityComparer<int>()));
AssertThrows.Wrapped<DeliberateTestException>(() => labeled.Item.ToLookup(x => x, y => y, new FailingEqualityComparer<int>()));
}
[Fact]
public static void ToLookup_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int>)null).ToLookup(x => x));
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int>)null).ToLookup(x => x, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int>)null).ToLookup(x => x, y => y));
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int>)null).ToLookup(x => x, y => y, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>("keySelector", () => ParallelEnumerable.Empty<int>().ToLookup((Func<int, int>)null));
Assert.Throws<ArgumentNullException>("keySelector", () => ParallelEnumerable.Empty<int>().ToLookup((Func<int, int>)null, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>("keySelector", () => ParallelEnumerable.Empty<int>().ToLookup((Func<int, int>)null, y => y));
Assert.Throws<ArgumentNullException>("keySelector", () => ParallelEnumerable.Empty<int>().ToLookup((Func<int, int>)null, y => y, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>("elementSelector", () => ParallelEnumerable.Empty<int>().ToLookup(x => x, (Func<int, int>)null));
Assert.Throws<ArgumentNullException>("elementSelector", () => ParallelEnumerable.Empty<int>().ToLookup(x => x, (Func<int, int>)null, EqualityComparer<int>.Default));
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.