context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public static class NguiUtils
{
public static NguiDataContext FindRootContext(GameObject gameObject, int depthToGo)
{
NguiDataContext lastGoodContext = null;
var p = gameObject;//.transform.parent == null ? null : gameObject.transform.parent.gameObject;
depthToGo++;
while (p != null && depthToGo > 0)
{
var context = p.GetComponent<NguiDataContext>();
if (context != null)
{
lastGoodContext = context;
depthToGo--;
}
p = (p.transform.parent == null) ? null : p.transform.parent.gameObject;
}
return lastGoodContext;
}
public const int MaxPathDepth = 100500;
public static int GetPathDepth(string path)
{
if (!path.StartsWith("#"))
return 0;
var depthString = path.Substring(1);
var dotIndex = depthString.IndexOf('.');
if (dotIndex >= 0)
depthString = depthString.Substring(0, dotIndex);
if (depthString == "#")
{
return MaxPathDepth;
}
var depth = 0;
if (int.TryParse(depthString, out depth))
{
return depth;
}
Debug.LogWarning("Failed to get binding context depth for: " + path);
return 0;
}
public static string GetCleanPath(string path)
{
if (!path.StartsWith("#"))
return path;
var dotIndex = path.IndexOf('.');
var result = (dotIndex < 0) ? path : path.Substring(dotIndex + 1);
return result;
}
public static GameObject FindParent(GameObject target, GameObject [] possibleParents)
{
foreach(var p in possibleParents)
{
if (p == target)
return p;
}
return target.transform.parent == null ? null : FindParent(target.transform.parent.gameObject, possibleParents);
}
public static T GetComponentInParents<T>(GameObject gameObject)
where T : Component
{
var p = gameObject;
T component = null;
while (p != null && component == null)
{
component = p.GetComponent<T>();
p = (p.transform.parent == null) ? null : p.transform.parent.gameObject;
}
return component;
}
public static T GetComponentInParentsExcluding<T>(GameObject gameObject)
where T : Component
{
return GetComponentInParents<T>((gameObject.transform.parent == null)
? null
: gameObject.transform.parent.gameObject);
}
public static T GetComponentAs<T>(this GameObject gameObject)
where T : class
{
var mbs = gameObject.GetComponents<Component>();
foreach(var mb in mbs)
{
if (mb is T)
return mb as T;
}
return default(T);
}
public static T[] GetComponentsAs<T>(this GameObject gameObject)
where T : class
{
var result = new List<T>();
var mbs = gameObject.GetComponents<Component>();
foreach(var mb in mbs)
{
if (mb is T)
result.Add(mb as T);
}
return result.ToArray();
}
public static T[] GetComponentsInChildrenAs<T>(this GameObject gameObject)
where T : class
{
var result = new List<T>();
var mbs = gameObject.GetComponentsInChildren<Component>();
foreach(var mb in mbs)
{
if (mb is T)
result.Add(mb as T);
}
return result.ToArray();
}
public static T GetComponentInParentsAs<T>(GameObject gameObject)
where T : class
{
T component = default(T);
var p = gameObject;
while (p != null && component == null)
{
var mbs = p.GetComponents<Component>();
foreach(var mb in mbs)
{
if (mb is T)
{
component = mb as T;
break;
}
}
p = (p.transform.parent == null) ? null : p.transform.parent.gameObject;
}
return component;
}
public static T GetComponentInParentsExcludingAs<T>(GameObject gameObject)
where T : class
{
return GetComponentInParentsAs<T>((gameObject.transform.parent == null)
? null
: gameObject.transform.parent.gameObject);
}
public delegate void ObjectAction(GameObject target);
public static void ForObjectsSubTree(GameObject root, ObjectAction action)
{
if (root == null)
return;
action(root);
for (var i = 0; i < root.transform.childCount; ++i)
{
ForObjectsSubTree(root.transform.GetChild(i).gameObject, action);
}
}
public static string LocalizeFormat(string input)
{
var output = "";
var index = 0;
const char marker = '$';
while(true)
{
var localStart = input.IndexOf(marker, index);
if (localStart < 0)
{
output += input.Substring(index);
break;
}
if (localStart > index)
{
output += input.Substring(index, localStart - index);
index = localStart;
}
var localFinish = input.IndexOf(marker, index + 1);
if (localFinish < 0)
{
break;
}
if (localFinish == localStart + 1)
{
output += marker;
}
else
{
var key = input.Substring(localStart + 1, localFinish - localStart - 1);
output += Localization.Get(key);
}
index = localFinish + 1;
}
return output;
}
public static void SetVisible(GameObject gameObject, bool visible)
{
SetNguiVisible(gameObject, visible);
for (var i = 0; i < gameObject.transform.childCount; ++i)
{
var child = gameObject.transform.GetChild(i).gameObject;
var childVisibilityBinding = child.GetComponentAs<IVisibilityBinding>();
if (childVisibilityBinding != null)
{
SetVisible(child, visible && childVisibilityBinding.ObjectVisible);
}
else
{
SetVisible(child, visible);
}
}
}
private static void SetNguiVisible(GameObject gameObject, bool visible)
{
foreach(var collider in gameObject.GetComponents<Collider>())
{
collider.enabled = visible;
}
foreach(var widget in gameObject.GetComponents<UIWidget>())
{
widget.enabled = visible;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Web;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Com.Aspose.Email.Model;
namespace Com.Aspose.Email
{
public struct FileInfo
{
public string Name;
public string MimeType;
public byte[] file;
}
public class ApiInvoker
{
private static readonly ApiInvoker _instance = new ApiInvoker();
private Dictionary<String, String> defaultHeaderMap = new Dictionary<String, String>();
public string appSid { set; get; }
public string apiKey { set; get; }
public static ApiInvoker GetInstance()
{
return _instance;
}
public void addDefaultHeader(string key, string value)
{
if (!defaultHeaderMap.ContainsKey(key))
{
defaultHeaderMap.Add(key, value);
}
}
public string escapeString(string str)
{
return str;
}
public static object deserialize(string json, Type type)
{
try
{
if (json.StartsWith("{") || json.StartsWith("["))
return JsonConvert.DeserializeObject(json, type);
else
{
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.LoadXml(json);
return JsonConvert.SerializeXmlNode(xmlDoc);
}
}
catch (IOException e)
{
throw new ApiException(500, e.Message);
}
catch (JsonSerializationException jse)
{
throw new ApiException(500, jse.Message);
}
catch (System.Xml.XmlException xmle)
{
throw new ApiException(500, xmle.Message);
}
}
public static object deserialize(byte[] BinaryData, Type type)
{
try
{
return new ResponseMessage(BinaryData, 200, "Ok");
}
catch (IOException e)
{
throw new ApiException(500, e.Message);
}
}
private static string Sign(string url, string appKey)
{
UriBuilder uriBuilder = new UriBuilder(url);
// Remove final slash here as it can be added automatically.
uriBuilder.Path = uriBuilder.Path.TrimEnd('/');
// Compute the hash.
byte[] privateKey = Encoding.UTF8.GetBytes(appKey);
HMACSHA1 algorithm = new HMACSHA1(privateKey);
byte[] sequence = ASCIIEncoding.ASCII.GetBytes(uriBuilder.Uri.AbsoluteUri);
byte[] hash = algorithm.ComputeHash(sequence);
string signature = Convert.ToBase64String(hash);
// Remove invalid symbols.
signature = signature.TrimEnd('=');
//signature = HttpUtility.UrlEncode(signature);
// Convert codes to upper case as they can be updated automatically.
signature = Regex.Replace(signature, "%[0-9a-f]{2}", e => e.Value.ToUpper());
// Add the signature to query string.
return string.Format("{0}&signature={1}", uriBuilder.Uri.AbsoluteUri, signature);
}
public static string serialize(object obj)
{
try
{
return obj != null ? JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }) : null;
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
public string invokeAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams)
{
return invokeAPIInternal(host, path, method, false, queryParams, body, headerParams, formParams) as string;
}
public byte[] invokeBinaryAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams)
{
return invokeAPIInternal(host, path, method, true, queryParams, body, headerParams, formParams) as byte[];
}
public static void CopyTo(Stream source, Stream destination, int bufferSize )
{
byte[] array = new byte[bufferSize];
int count;
while ((count = source.Read(array, 0, array.Length)) != 0)
{
destination.Write(array, 0, count);
}
}
private object invokeAPIInternal(string host, string path, string method, bool binaryResponse, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams)
{
path = path.Replace("{appSid}", this.appSid);
path = Regex.Replace(path, @"{.+?}", "");
//var b = new StringBuilder();
host = host.EndsWith("/") ? host.Substring(0, host.Length - 1) : host;
path = Sign(host + path, this.apiKey);
var client = WebRequest.Create(path);
client.Method = method;
byte[] formData = null;
if (formParams.Count > 0)
{
if (formParams.Count > 1)
{
string formDataBoundary = String.Format("Somthing");
client.ContentType = "multipart/form-data; boundary=" + formDataBoundary;
formData = GetMultipartFormData(formParams, formDataBoundary);
}
else
{
client.ContentType = "multipart/form-data";
formData = GetMultipartFormData(formParams, "");
}
client.ContentLength = formData.Length;
}
else
{
client.ContentType = "application/json";
}
foreach (var headerParamsItem in headerParams)
{
client.Headers.Add(headerParamsItem.Key, headerParamsItem.Value);
}
foreach (var defaultHeaderMapItem in defaultHeaderMap)
{
if (!headerParams.ContainsKey(defaultHeaderMapItem.Key))
{
client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value);
}
}
switch (method)
{
case "GET":
break;
case "POST":
case "PUT":
case "DELETE":
using (Stream requestStream = client.GetRequestStream())
{
if (formData != null)
{
requestStream.Write(formData, 0, formData.Length);
}
if (body != null)
{
var swRequestWriter = new StreamWriter(requestStream);
swRequestWriter.Write(serialize(body));
swRequestWriter.Close();
}
}
break;
default:
throw new ApiException(500, "unknown method type " + method);
}
try
{
var webResponse = (HttpWebResponse)client.GetResponse();
if (webResponse.StatusCode != HttpStatusCode.OK)
{
webResponse.Close();
throw new ApiException((int)webResponse.StatusCode, webResponse.StatusDescription);
}
if (binaryResponse)
{
using (var memoryStream = new MemoryStream())
{
CopyTo(webResponse.GetResponseStream(), memoryStream, 81920);
return memoryStream.ToArray();
}
}
else
{
using (var responseReader = new StreamReader(webResponse.GetResponseStream()))
{
var responseData = responseReader.ReadToEnd();
return responseData;
}
}
}
catch (WebException ex)
{
var response = ex.Response as HttpWebResponse;
int statusCode = 0;
if (response != null)
{
statusCode = (int)response.StatusCode;
response.Close();
}
throw new ApiException(statusCode, ex.Message);
}
}
private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
{
Stream formDataStream = new System.IO.MemoryStream();
bool needsCLRF = false;
if (postParameters.Count > 1)
{
foreach (var param in postParameters)
{
// Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
// Skip it on the first parameter, add it to subsequent parameters.
if (needsCLRF)
formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n"));
needsCLRF = true;
var fileInfo = (FileInfo)param.Value;
if (param.Value is FileInfo)
{
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n",
boundary,
param.Key,
fileInfo.MimeType);
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
// Write the file data directly to the Stream, rather than serializing it to a string.
formDataStream.Write((fileInfo.file as byte[]), 0, (fileInfo.file as byte[]).Length);
}
else
{
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
boundary,
param.Key,
fileInfo.file);
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
}
}
// Add the end of the request. Start with a newline
string footer = "\r\n--" + boundary + "--\r\n";
formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
}
else
{
foreach (var param in postParameters)
{
var fileInfo = (FileInfo)param.Value;
if (param.Value is FileInfo)
{
// Write the file data directly to the Stream, rather than serializing it to a string.
formDataStream.Write((fileInfo.file as byte[]), 0, (fileInfo.file as byte[]).Length);
}
else
{
string postData = (string)param.Value;
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
}
}
}
// Dump the Stream into a byte[]
formDataStream.Position = 0;
byte[] formData = new byte[formDataStream.Length];
formDataStream.Read(formData, 0, formData.Length);
formDataStream.Close();
return formData;
}
/**
* Overloaded method for returning the path value
* For a string value an empty value is returned if the value is null
* @param value
* @return
*/
public String ToPathValue(String value)
{
return (value == null) ? "" : value;
}
public String ToPathValue(int value)
{
return value.ToString();
}
public String ToPathValue(int? value)
{
return value.ToString();
}
public String ToPathValue(float value)
{
return value.ToString();
}
public String ToPathValue(float? value)
{
return value.ToString();
}
public String ToPathValue(long value)
{
return value.ToString();
}
public String ToPathValue(long? value)
{
return value.ToString();
}
public String ToPathValue(bool value)
{
return value.ToString();
}
public String ToPathValue(bool? value)
{
return value.ToString();
}
public String ToPathValue(double value)
{
return value.ToString();
}
public String ToPathValue(double? value)
{
return value.ToString();
}
//public String ToPathValue(Com.Aspose.Email.Model.DateTime value)
//{
// //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
// //return format.format(value);
// return value.ToString();
//}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Xml;
using Nop.Core.Domain.Affiliates;
using Nop.Core.Domain.Common;
using Nop.Core.Domain.Directory;
using Nop.Core.Domain.Forums;
using Nop.Core.Domain.Localization;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Tax;
namespace Nop.Core.Domain.Customers
{
/// <summary>
/// Represents a customer
/// </summary>
public partial class Customer : BaseEntity
{
private ICollection<ExternalAuthenticationRecord> _externalAuthenticationRecords;
private ICollection<CustomerContent> _customerContent;
private ICollection<CustomerRole> _customerRoles;
private ICollection<ShoppingCartItem> _shoppingCartItems;
private ICollection<Order> _orders;
private ICollection<RewardPointsHistory> _rewardPointsHistory;
private ICollection<ReturnRequest> _returnRequests;
private ICollection<Address> _addresses;
private ICollection<ForumTopic> _forumTopics;
private ICollection<ForumPost> _forumPosts;
public Customer()
{
this.CustomerGuid = Guid.NewGuid();
this.PasswordFormat = PasswordFormat.Clear;
}
/// <summary>
/// Gets or sets the customer Guid
/// </summary>
public virtual Guid CustomerGuid { get; set; }
public virtual string Username { get; set; }
public virtual string Email { get; set; }
public virtual string Password { get; set; }
public virtual int PasswordFormatId { get; set; }
public virtual PasswordFormat PasswordFormat
{
get { return (PasswordFormat)PasswordFormatId; }
set { this.PasswordFormatId = (int)value; }
}
public virtual string PasswordSalt { get; set; }
/// <summary>
/// Gets or sets the admin comment
/// </summary>
public virtual string AdminComment { get; set; }
/// <summary>
/// Gets or sets the language identifier
/// </summary>
public virtual int? LanguageId { get; set; }
/// <summary>
/// Gets or sets the currency identifier
/// </summary>
public virtual int? CurrencyId { get; set; }
/// <summary>
/// Gets or sets the tax display type identifier
/// </summary>
public virtual int TaxDisplayTypeId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the customer is tax exempt
/// </summary>
public virtual bool IsTaxExempt { get; set; }
/// <summary>
/// Gets or sets a VAT number (including counry code)
/// </summary>
public virtual string VatNumber { get; set; }
/// <summary>
/// Gets or sets the VAT number status identifier
/// </summary>
public virtual int VatNumberStatusId { get; set; }
/// <summary>
/// Gets or sets the last payment method system name (selected one)
/// </summary>
public virtual string SelectedPaymentMethodSystemName { get; set; }
/// <summary>
/// Gets or sets the selected checkout attributes (serialized)
/// </summary>
public virtual string CheckoutAttributes { get; set; }
/// <summary>
/// Gets or sets the applied discount coupon code
/// </summary>
public virtual string DiscountCouponCode { get; set; }
/// <summary>
/// Gets or sets the applied gift card coupon codes (serialized)
/// </summary>
public virtual string GiftCardCouponCodes { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to use reward points during checkout
/// </summary>
public virtual bool UseRewardPointsDuringCheckout { get; set; }
/// <summary>
/// Gets or sets the time zone identifier
/// </summary>
public virtual string TimeZoneId { get; set; }
/// <summary>
/// Gets or sets the affiliate identifier
/// </summary>
public virtual int? AffiliateId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the customer is active
/// </summary>
public virtual bool Active { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the customer has been deleted
/// </summary>
public virtual bool Deleted { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the customer account is system
/// </summary>
public virtual bool IsSystemAccount { get; set; }
/// <summary>
/// Gets or sets the customer system name
/// </summary>
public virtual string SystemName { get; set; }
/// <summary>
/// Gets or sets the last IP address
/// </summary>
public virtual string LastIpAddress { get; set; }
/// <summary>
/// Gets or sets the date and time of entity creation
/// </summary>
public virtual DateTimeOffset CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the date and time of last login
/// </summary>
public virtual DateTimeOffset? LastLoginDateUtc { get; set; }
/// <summary>
/// Gets or sets the date and time of last activity
/// </summary>
public virtual DateTimeOffset LastActivityDateUtc { get; set; }
#region Custom properties
/// <summary>
/// Gets the tax display type
/// </summary>
public virtual TaxDisplayType TaxDisplayType
{
get
{
return (TaxDisplayType)this.TaxDisplayTypeId;
}
set
{
this.TaxDisplayTypeId = (int)value;
}
}
/// <summary>
/// Gets the VAT number status
/// </summary>
public virtual VatNumberStatus VatNumberStatus
{
get
{
return (VatNumberStatus)this.VatNumberStatusId;
}
set
{
this.VatNumberStatusId = (int)value;
}
}
#endregion
#region Navigation properties
/// <summary>
/// Gets or sets the affiliate
/// </summary>
public virtual Affiliate Affiliate { get; set; }
/// <summary>
/// Gets or sets the language
/// </summary>
public virtual Language Language { get; set; }
/// <summary>
/// Gets or sets the currency
/// </summary>
public virtual Currency Currency { get; set; }
/// <summary>
/// Gets or sets customer generated content
/// </summary>
public virtual ICollection<ExternalAuthenticationRecord> ExternalAuthenticationRecords
{
get { return _externalAuthenticationRecords ?? (_externalAuthenticationRecords = new List<ExternalAuthenticationRecord>()); }
protected set { _externalAuthenticationRecords = value; }
}
/// <summary>
/// Gets or sets customer generated content
/// </summary>
public virtual ICollection<CustomerContent> CustomerContent
{
get { return _customerContent ?? (_customerContent = new List<CustomerContent>()); }
protected set { _customerContent = value; }
}
/// <summary>
/// Gets or sets the customer roles
/// </summary>
public virtual ICollection<CustomerRole> CustomerRoles
{
get { return _customerRoles ?? (_customerRoles = new List<CustomerRole>()); }
protected set { _customerRoles = value; }
}
/// <summary>
/// Gets or sets shopping cart items
/// </summary>
public virtual ICollection<ShoppingCartItem> ShoppingCartItems
{
get { return _shoppingCartItems ?? (_shoppingCartItems = new List<ShoppingCartItem>()); }
protected set { _shoppingCartItems = value; }
}
/// <summary>
/// Gets or sets orders
/// </summary>
public virtual ICollection<Order> Orders
{
get { return _orders ?? (_orders = new List<Order>()); }
protected set { _orders = value; }
}
/// <summary>
/// Gets or sets reward points history
/// </summary>
public virtual ICollection<RewardPointsHistory> RewardPointsHistory
{
get { return _rewardPointsHistory ?? (_rewardPointsHistory = new List<RewardPointsHistory>()); }
protected set { _rewardPointsHistory = value; }
}
/// <summary>
/// Gets or sets return request of this customer
/// </summary>
public virtual ICollection<ReturnRequest> ReturnRequests
{
get { return _returnRequests ?? (_returnRequests = new List<ReturnRequest>()); }
protected set { _returnRequests = value; }
}
/// <summary>
/// Default billing address
/// </summary>
public virtual Address BillingAddress { get; set; }
/// <summary>
/// Default shipping address
/// </summary>
public virtual Address ShippingAddress { get; set; }
/// <summary>
/// Gets or sets customer addresses
/// </summary>
public virtual ICollection<Address> Addresses
{
get { return _addresses ?? (_addresses = new List<Address>()); }
protected set { _addresses = value; }
}
/// <summary>
/// Gets or sets the created forum topics
/// </summary>
public virtual ICollection<ForumTopic> ForumTopics
{
get { return _forumTopics ?? (_forumTopics = new List<ForumTopic>()); }
protected set { _forumTopics = value; }
}
/// <summary>
/// Gets or sets the created forum posts
/// </summary>
public virtual ICollection<ForumPost> ForumPosts
{
get { return _forumPosts ?? (_forumPosts = new List<ForumPost>()); }
protected set { _forumPosts = value; }
}
#endregion
#region Addresses
public virtual void RemoveAddress(Address address)
{
if (this.Addresses.Contains(address))
{
if (this.BillingAddress == address) this.BillingAddress = null;
if (this.ShippingAddress == address) this.ShippingAddress = null;
this.Addresses.Remove(address);
}
}
#endregion
#region Reward points
public virtual void AddRewardPointsHistoryEntry(int points, string message = "",
Order usedWithOrder = null, decimal usedAmount = 0M)
{
int newPointsBalance = this.GetRewardPointsBalance() + points;
var rewardPointsHistory = new RewardPointsHistory()
{
Customer = this,
UsedWithOrder = usedWithOrder,
Points = points,
PointsBalance = newPointsBalance,
UsedAmount = usedAmount,
Message = message,
CreatedOnUtc = DateTime.UtcNow
};
this.RewardPointsHistory.Add(rewardPointsHistory);
}
/// <summary>
/// Gets reward points balance
/// </summary>
public virtual int GetRewardPointsBalance()
{
int result = 0;
if (this.RewardPointsHistory.Count > 0)
result = this.RewardPointsHistory.OrderByDescending(rph => rph.CreatedOnUtc).ThenByDescending(rph => rph.Id).FirstOrDefault().PointsBalance;
return result;
}
#endregion
#region Gift cards
/// <summary>
/// Gets coupon codes
/// </summary>
/// <returns>Coupon codes</returns>
public virtual string[] ParseAppliedGiftCardCouponCodes()
{
string serializedGiftCartCouponCodes = this.GiftCardCouponCodes;
var couponCodes = new List<string>();
if (String.IsNullOrEmpty(serializedGiftCartCouponCodes))
return couponCodes.ToArray();
try
{
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(serializedGiftCartCouponCodes);
var nodeList1 = xmlDoc.SelectNodes(@"//GiftCardCouponCodes/CouponCode");
foreach (XmlNode node1 in nodeList1)
{
if (node1.Attributes != null && node1.Attributes["Code"] != null)
{
string code = node1.Attributes["Code"].InnerText.Trim();
couponCodes.Add(code);
}
}
}
catch (Exception exc)
{
Debug.Write(exc.ToString());
}
return couponCodes.ToArray();
}
/// <summary>
/// Adds a coupon code
/// </summary>
/// <param name="couponCode">Coupon code</param>
/// <returns>New coupon codes document</returns>
public virtual void ApplyGiftCardCouponCode(string couponCode)
{
string result = string.Empty;
try
{
var serializedGiftCartCouponCodes = this.GiftCardCouponCodes;
couponCode = couponCode.Trim().ToLower();
var xmlDoc = new XmlDocument();
if (String.IsNullOrEmpty(serializedGiftCartCouponCodes))
{
var element1 = xmlDoc.CreateElement("GiftCardCouponCodes");
xmlDoc.AppendChild(element1);
}
else
{
xmlDoc.LoadXml(serializedGiftCartCouponCodes);
}
var rootElement = (XmlElement)xmlDoc.SelectSingleNode(@"//GiftCardCouponCodes");
XmlElement element = null;
//find existing
var nodeList1 = xmlDoc.SelectNodes(@"//GiftCardCouponCodes/CouponCode");
foreach (XmlNode node1 in nodeList1)
{
if (node1.Attributes != null && node1.Attributes["Code"] != null)
{
string _couponCode = node1.Attributes["Code"].InnerText.Trim();
if (_couponCode.ToLower() == couponCode.ToLower())
{
element = (XmlElement)node1;
break;
}
}
}
//create new one if not found
if (element == null)
{
element = xmlDoc.CreateElement("CouponCode");
element.SetAttribute("Code", couponCode);
rootElement.AppendChild(element);
}
result = xmlDoc.OuterXml;
}
catch (Exception exc)
{
Debug.Write(exc.ToString());
}
//apply new value
this.GiftCardCouponCodes = result;
}
/// <summary>
/// Removes a coupon code
/// </summary>
/// <param name="couponCode">Coupon code to remove</param>
/// <returns>New coupon codes document</returns>
public virtual void RemoveGiftCardCouponCode(string couponCode)
{
//get applied coupon codes
var existingCouponCodes = ParseAppliedGiftCardCouponCodes();
//clear them
this.GiftCardCouponCodes = string.Empty;
//save again except removed one
foreach (string existingCouponCode in existingCouponCodes)
if (!existingCouponCode.Equals(couponCode, StringComparison.InvariantCultureIgnoreCase))
ApplyGiftCardCouponCode(existingCouponCode);
}
#endregion
}
}
| |
///////////////////////////////////////////////////////////////////////////
// Description: Data Access class for the table 'RS_Tarif'
// Generated by LLBLGen v1.21.2003.712 Final on: 28 October 2007, 23:20:14
// Because the Base Class already implements IDispose, this class doesn't.
///////////////////////////////////////////////////////////////////////////
using System;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
namespace SIMRS.DataAccess
{
/// <summary>
/// Purpose: Data Access class for the table 'RS_Tarif'.
/// </summary>
public class RS_Tarif : DBInteractionBase
{
#region Class Member Declarations
private SqlBoolean _published;
private SqlDateTime _modifiedDate, _createdDate;
private SqlInt32 _createdBy, _id, _layananId, _layananIdOld, _kelasId, _kelasIdOld, _modifiedBy;
private SqlMoney _tarif;
private SqlString _satuan, _mataUang, _keterangan;
#endregion
/// <summary>
/// Purpose: Class constructor.
/// </summary>
public RS_Tarif()
{
// Nothing for now.
}
public bool IsExist()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_Tarif_IsExist]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@LayananId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _layananId));
cmdToExecute.Parameters.Add(new SqlParameter("@KelasId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _kelasId));
cmdToExecute.Parameters.Add(new SqlParameter("@IsExist", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, false, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
int IsExist = int.Parse(cmdToExecute.Parameters["@IsExist"].Value.ToString());
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_Tarif_IsExist' reported the ErrorCode: " + _errorCode);
}
return IsExist == 1;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_Tarif::IsExist::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Insert method. This method will insert one new row into the database.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// <LI>LayananId</LI>
/// <LI>KelasId. May be SqlInt32.Null</LI>
/// <LI>Satuan. May be SqlString.Null</LI>
/// <LI>MataUang</LI>
/// <LI>Tarif</LI>
/// <LI>Keterangan. May be SqlString.Null</LI>
/// <LI>Published</LI>
/// <LI>CreatedBy</LI>
/// <LI>CreatedDate</LI>
/// <LI>ModifiedBy. May be SqlInt32.Null</LI>
/// <LI>ModifiedDate. May be SqlDateTime.Null</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override bool Insert()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_Tarif_Insert]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@LayananId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _layananId));
cmdToExecute.Parameters.Add(new SqlParameter("@KelasId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _kelasId));
cmdToExecute.Parameters.Add(new SqlParameter("@Satuan", SqlDbType.VarChar, 50, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _satuan));
cmdToExecute.Parameters.Add(new SqlParameter("@MataUang", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _mataUang));
cmdToExecute.Parameters.Add(new SqlParameter("@Tarif", SqlDbType.Money, 8, ParameterDirection.Input, false, 19, 4, "", DataRowVersion.Proposed, _tarif));
cmdToExecute.Parameters.Add(new SqlParameter("@Keterangan", SqlDbType.VarChar, 255, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keterangan));
cmdToExecute.Parameters.Add(new SqlParameter("@Published", SqlDbType.Bit, 1, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _published));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _createdBy));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _createdDate));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _modifiedBy));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _modifiedDate));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_Tarif_Insert' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_Tarif::Insert::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Update method. This method will Update one existing row in the database.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// <LI>LayananId</LI>
/// <LI>KelasId. May be SqlInt32.Null</LI>
/// <LI>Satuan. May be SqlString.Null</LI>
/// <LI>MataUang</LI>
/// <LI>Tarif</LI>
/// <LI>Keterangan. May be SqlString.Null</LI>
/// <LI>Published</LI>
/// <LI>CreatedBy</LI>
/// <LI>CreatedDate</LI>
/// <LI>ModifiedBy. May be SqlInt32.Null</LI>
/// <LI>ModifiedDate. May be SqlDateTime.Null</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override bool Update()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_Tarif_Update]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@LayananId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _layananId));
cmdToExecute.Parameters.Add(new SqlParameter("@KelasId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _kelasId));
cmdToExecute.Parameters.Add(new SqlParameter("@Satuan", SqlDbType.VarChar, 50, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _satuan));
cmdToExecute.Parameters.Add(new SqlParameter("@MataUang", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _mataUang));
cmdToExecute.Parameters.Add(new SqlParameter("@Tarif", SqlDbType.Money, 8, ParameterDirection.Input, false, 19, 4, "", DataRowVersion.Proposed, _tarif));
cmdToExecute.Parameters.Add(new SqlParameter("@Keterangan", SqlDbType.VarChar, 255, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keterangan));
cmdToExecute.Parameters.Add(new SqlParameter("@Published", SqlDbType.Bit, 1, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _published));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _createdBy));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _createdDate));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _modifiedBy));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _modifiedDate));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_Tarif_Update' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_Tarif::Update::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Update method for updating one or more rows using the Foreign Key 'LayananId.
/// This method will Update one or more existing rows in the database. It will reset the field 'LayananId' in
/// all rows which have as value for this field the value as set in property 'LayananIdOld' to
/// the value as set in property 'LayananId'.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>LayananId</LI>
/// <LI>LayananIdOld</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public bool UpdateAllWLayananIdLogic()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_Tarif_UpdateAllWLayananIdLogic]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@LayananId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _layananId));
cmdToExecute.Parameters.Add(new SqlParameter("@LayananIdOld", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _layananIdOld));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_Tarif_UpdateAllWLayananIdLogic' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_Tarif::UpdateAllWLayananIdLogic::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Update method for updating one or more rows using the Foreign Key 'KelasId.
/// This method will Update one or more existing rows in the database. It will reset the field 'KelasId' in
/// all rows which have as value for this field the value as set in property 'KelasIdOld' to
/// the value as set in property 'KelasId'.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>KelasId. May be SqlInt32.Null</LI>
/// <LI>KelasIdOld. May be SqlInt32.Null</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public bool UpdateAllWKelasIdLogic()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_Tarif_UpdateAllWKelasIdLogic]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@KelasId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _kelasId));
cmdToExecute.Parameters.Add(new SqlParameter("@KelasIdOld", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _kelasIdOld));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_Tarif_UpdateAllWKelasIdLogic' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_Tarif::UpdateAllWKelasIdLogic::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Delete method. This method will Delete one existing row in the database, based on the Primary Key.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override bool Delete()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_Tarif_Delete]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_Tarif_Delete' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_Tarif::Delete::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Delete method for a foreign key. This method will Delete one or more rows from the database, based on the Foreign Key 'LayananId'
/// </summary>
/// <returns>True if succeeded, false otherwise. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>LayananId</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public bool DeleteAllWLayananIdLogic()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_Tarif_DeleteAllWLayananIdLogic]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@LayananId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _layananId));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_Tarif_DeleteAllWLayananIdLogic' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_Tarif::DeleteAllWLayananIdLogic::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Delete method for a foreign key. This method will Delete one or more rows from the database, based on the Foreign Key 'KelasId'
/// </summary>
/// <returns>True if succeeded, false otherwise. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>KelasId. May be SqlInt32.Null</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public bool DeleteAllWKelasIdLogic()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_Tarif_DeleteAllWKelasIdLogic]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@KelasId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _kelasId));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_Tarif_DeleteAllWKelasIdLogic' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_Tarif::DeleteAllWKelasIdLogic::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Select method. This method will Select one existing row from the database, based on the Primary Key.
/// </summary>
/// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// <LI>Id</LI>
/// <LI>LayananId</LI>
/// <LI>KelasId</LI>
/// <LI>Satuan</LI>
/// <LI>MataUang</LI>
/// <LI>Tarif</LI>
/// <LI>Keterangan</LI>
/// <LI>Published</LI>
/// <LI>CreatedBy</LI>
/// <LI>CreatedDate</LI>
/// <LI>ModifiedBy</LI>
/// <LI>ModifiedDate</LI>
/// </UL>
/// Will fill all properties corresponding with a field in the table with the value of the row selected.
/// </remarks>
public override DataTable SelectOne()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_Tarif_SelectOne]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("RS_Tarif");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_Tarif_SelectOne' reported the ErrorCode: " + _errorCode);
}
if(toReturn.Rows.Count > 0)
{
_id = (Int32)toReturn.Rows[0]["Id"];
_layananId = (Int32)toReturn.Rows[0]["LayananId"];
_kelasId = toReturn.Rows[0]["KelasId"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["KelasId"];
_satuan = toReturn.Rows[0]["Satuan"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["Satuan"];
_mataUang = (string)toReturn.Rows[0]["MataUang"];
_tarif = (Decimal)toReturn.Rows[0]["Tarif"];
_keterangan = toReturn.Rows[0]["Keterangan"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["Keterangan"];
_published = (bool)toReturn.Rows[0]["Published"];
_createdBy = (Int32)toReturn.Rows[0]["CreatedBy"];
_createdDate = (DateTime)toReturn.Rows[0]["CreatedDate"];
_modifiedBy = toReturn.Rows[0]["ModifiedBy"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["ModifiedBy"];
_modifiedDate = toReturn.Rows[0]["ModifiedDate"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["ModifiedDate"];
}
return toReturn;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_Tarif::SelectOne::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
/// <summary>
/// Purpose: SelectAll method. This method will Select all rows from the table.
/// </summary>
/// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override DataTable SelectAll()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_Tarif_SelectAll]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("RS_Tarif");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_Tarif_SelectAll' reported the ErrorCode: " + _errorCode);
}
return toReturn;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_Tarif::SelectAll::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
/// <summary>
/// Purpose: Select method for a foreign key. This method will Select one or more rows from the database, based on the Foreign Key 'LayananId'
/// </summary>
/// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>LayananId</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public DataTable SelectAllWLayananIdLogic()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_Tarif_SelectAllWLayananIdLogic]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("RS_Tarif");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@LayananId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _layananId));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_Tarif_SelectAllWLayananIdLogic' reported the ErrorCode: " + _errorCode);
}
return toReturn;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_Tarif::SelectAllWLayananIdLogic::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
/// <summary>
/// Purpose: Select method for a foreign key. This method will Select one or more rows from the database, based on the Foreign Key 'KelasId'
/// </summary>
/// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>KelasId. May be SqlInt32.Null</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public DataTable SelectAllWKelasIdLogic()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_Tarif_SelectAllWKelasIdLogic]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("RS_Tarif");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@KelasId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _kelasId));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_Tarif_SelectAllWKelasIdLogic' reported the ErrorCode: " + _errorCode);
}
return toReturn;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_Tarif::SelectAllWKelasIdLogic::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
#region Class Property Declarations
public SqlInt32 Id
{
get
{
return _id;
}
set
{
SqlInt32 idTmp = (SqlInt32)value;
if(idTmp.IsNull)
{
throw new ArgumentOutOfRangeException("Id", "Id can't be NULL");
}
_id = value;
}
}
public SqlInt32 LayananId
{
get
{
return _layananId;
}
set
{
SqlInt32 layananIdTmp = (SqlInt32)value;
if(layananIdTmp.IsNull)
{
throw new ArgumentOutOfRangeException("LayananId", "LayananId can't be NULL");
}
_layananId = value;
}
}
public SqlInt32 LayananIdOld
{
get
{
return _layananIdOld;
}
set
{
SqlInt32 layananIdOldTmp = (SqlInt32)value;
if(layananIdOldTmp.IsNull)
{
throw new ArgumentOutOfRangeException("LayananIdOld", "LayananIdOld can't be NULL");
}
_layananIdOld = value;
}
}
public SqlInt32 KelasId
{
get
{
return _kelasId;
}
set
{
_kelasId = value;
}
}
public SqlInt32 KelasIdOld
{
get
{
return _kelasIdOld;
}
set
{
_kelasIdOld = value;
}
}
public SqlString Satuan
{
get
{
return _satuan;
}
set
{
_satuan = value;
}
}
public SqlString MataUang
{
get
{
return _mataUang;
}
set
{
_mataUang = value;
}
}
public SqlMoney Tarif
{
get
{
return _tarif;
}
set
{
_tarif = value;
}
}
public SqlString Keterangan
{
get
{
return _keterangan;
}
set
{
_keterangan = value;
}
}
public SqlBoolean Published
{
get
{
return _published;
}
set
{
_published = value;
}
}
public SqlInt32 CreatedBy
{
get
{
return _createdBy;
}
set
{
SqlInt32 createdByTmp = (SqlInt32)value;
if(createdByTmp.IsNull)
{
throw new ArgumentOutOfRangeException("CreatedBy", "CreatedBy can't be NULL");
}
_createdBy = value;
}
}
public SqlDateTime CreatedDate
{
get
{
return _createdDate;
}
set
{
SqlDateTime createdDateTmp = (SqlDateTime)value;
if(createdDateTmp.IsNull)
{
throw new ArgumentOutOfRangeException("CreatedDate", "CreatedDate can't be NULL");
}
_createdDate = value;
}
}
public SqlInt32 ModifiedBy
{
get
{
return _modifiedBy;
}
set
{
_modifiedBy = value;
}
}
public SqlDateTime ModifiedDate
{
get
{
return _modifiedDate;
}
set
{
_modifiedDate = value;
}
}
#endregion
}
}
| |
using System;
using System.Xml;
using System.Web.Caching;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Data;
using System.Web.UI;
using System.Collections;
using System.Collections.Generic;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Configuration;
using Umbraco.Web;
using Umbraco.Web.Cache;
using umbraco.DataLayer;
using umbraco.BusinessLogic;
using Umbraco.Core.IO;
using System.Web;
namespace umbraco
{
/// <summary>
/// Holds methods for parsing and building umbraco templates
/// </summary>
[Obsolete("Do not use this class, use Umbraco.Core.Service.IFileService to work with templates")]
public class template
{
#region private variables
readonly StringBuilder _templateOutput = new StringBuilder();
private string _templateDesign = "";
int _masterTemplate = -1;
private string _templateName = "";
private string _templateAlias = "";
#endregion
#region public properties
public String TemplateContent
{
set
{
_templateOutput.Append(value);
}
get
{
return _templateOutput.ToString();
}
}
public int MasterTemplate
{
get { return _masterTemplate; }
}
//added fallback to the default template to avoid nasty .net errors.
//This is referenced in /default.aspx.cs during page rendering.
public string MasterPageFile
{
get
{
string file = TemplateAlias.Replace(" ", "") + ".master";
string path = SystemDirectories.Masterpages + "/" + file;
if (System.IO.File.Exists(IOHelper.MapPath(VirtualPathUtility.ToAbsolute(path))))
return path;
else
return SystemDirectories.Umbraco + "/masterPages/default.master";
}
}
//Support for template folders, if a alternative skin folder is requested
//we will try to look for template files in another folder
public string AlternateMasterPageFile(string templateFolder)
{
string file = TemplateAlias.Replace(" ", "") + ".master";
string path = SystemDirectories.Masterpages + "/" + templateFolder + "/" + file;
//if it doesn't exists then we return the normal file
if (!System.IO.File.Exists(IOHelper.MapPath(VirtualPathUtility.ToAbsolute(path))))
{
string originalPath = IOHelper.MapPath(VirtualPathUtility.ToAbsolute(MasterPageFile));
string copyPath = IOHelper.MapPath(VirtualPathUtility.ToAbsolute(path));
FileStream fs = new FileStream(originalPath, FileMode.Open, FileAccess.ReadWrite);
StreamReader f = new StreamReader(fs);
String newfile = f.ReadToEnd();
f.Close();
fs.Close();
newfile = newfile.Replace("MasterPageFile=\"~/masterpages/", "MasterPageFile=\"");
fs = new FileStream(copyPath, FileMode.Create, FileAccess.Write);
StreamWriter replacement = new StreamWriter(fs);
replacement.Write(newfile);
replacement.Close();
}
return path;
}
public string TemplateAlias
{
get { return _templateAlias; }
}
#endregion
#region public methods
public override string ToString()
{
return this._templateName;
}
public Control ParseWithControls(page umbPage)
{
System.Web.HttpContext.Current.Trace.Write("umbracoTemplate", "Start parsing");
if (System.Web.HttpContext.Current.Items["macrosAdded"] == null)
System.Web.HttpContext.Current.Items.Add("macrosAdded", 0);
StringBuilder tempOutput = _templateOutput;
Control pageLayout = new Control();
Control pageHeader = new Control();
Control pageFooter = new Control();
Control pageContent = new Control();
System.Web.UI.HtmlControls.HtmlForm pageForm = new System.Web.UI.HtmlControls.HtmlForm();
System.Web.UI.HtmlControls.HtmlHead pageAspNetHead = new System.Web.UI.HtmlControls.HtmlHead();
// Find header and footer of page if there is an aspnet-form on page
if (_templateOutput.ToString().ToLower().IndexOf("<?aspnet_form>") > 0 ||
_templateOutput.ToString().ToLower().IndexOf("<?aspnet_form disablescriptmanager=\"true\">") > 0)
{
pageForm.Attributes.Add("method", "post");
pageForm.Attributes.Add("action", Convert.ToString(System.Web.HttpContext.Current.Items["VirtualUrl"]));
// Find header and footer from tempOutput
int aspnetFormTagBegin = tempOutput.ToString().ToLower().IndexOf("<?aspnet_form>");
int aspnetFormTagLength = 14;
int aspnetFormTagEnd = tempOutput.ToString().ToLower().IndexOf("</?aspnet_form>") + 15;
// check if we should disable the script manager
if (aspnetFormTagBegin == -1)
{
aspnetFormTagBegin =
_templateOutput.ToString().ToLower().IndexOf("<?aspnet_form disablescriptmanager=\"true\">");
aspnetFormTagLength = 42;
}
else
{
ScriptManager sm = new ScriptManager();
sm.ID = "umbracoScriptManager";
pageForm.Controls.Add(sm);
}
StringBuilder header = new StringBuilder(tempOutput.ToString().Substring(0, aspnetFormTagBegin));
// Check if there's an asp.net head element in the header
if (header.ToString().ToLower().Contains("<?aspnet_head>"))
{
StringBuilder beforeHeader = new StringBuilder(header.ToString().Substring(0, header.ToString().ToLower().IndexOf("<?aspnet_head>")));
header.Remove(0, header.ToString().ToLower().IndexOf("<?aspnet_head>") + 14);
StringBuilder afterHeader = new StringBuilder(header.ToString().Substring(header.ToString().ToLower().IndexOf("</?aspnet_head>") + 15, header.Length - header.ToString().ToLower().IndexOf("</?aspnet_head>") - 15));
header.Remove(header.ToString().ToLower().IndexOf("</?aspnet_head>"), header.Length - header.ToString().ToLower().IndexOf("</?aspnet_head>"));
// Find the title from head
MatchCollection matches = Regex.Matches(header.ToString(), @"<title>(.*?)</title>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
if (matches.Count > 0)
{
StringBuilder titleText = new StringBuilder();
HtmlTextWriter titleTextTw = new HtmlTextWriter(new System.IO.StringWriter(titleText));
parseStringBuilder(new StringBuilder(matches[0].Groups[1].Value), umbPage).RenderControl(titleTextTw);
pageAspNetHead.Title = titleText.ToString();
header = new StringBuilder(header.ToString().Replace(matches[0].Value, ""));
}
pageAspNetHead.Controls.Add(parseStringBuilder(header, umbPage));
pageAspNetHead.ID = "head1";
// build the whole header part
pageHeader.Controls.Add(parseStringBuilder(beforeHeader, umbPage));
pageHeader.Controls.Add(pageAspNetHead);
pageHeader.Controls.Add(parseStringBuilder(afterHeader, umbPage));
}
else
pageHeader.Controls.Add(parseStringBuilder(header, umbPage));
pageFooter.Controls.Add(parseStringBuilder(new StringBuilder(tempOutput.ToString().Substring(aspnetFormTagEnd, tempOutput.Length - aspnetFormTagEnd)), umbPage));
tempOutput.Remove(0, aspnetFormTagBegin + aspnetFormTagLength);
aspnetFormTagEnd = tempOutput.ToString().ToLower().IndexOf("</?aspnet_form>");
tempOutput.Remove(aspnetFormTagEnd, tempOutput.Length - aspnetFormTagEnd);
//throw new ArgumentException(tempOutput.ToString());
pageForm.Controls.Add(parseStringBuilder(tempOutput, umbPage));
pageContent.Controls.Add(pageHeader);
pageContent.Controls.Add(pageForm);
pageContent.Controls.Add(pageFooter);
return pageContent;
}
else
return parseStringBuilder(tempOutput, umbPage);
}
public Control parseStringBuilder(StringBuilder tempOutput, page umbPage)
{
Control pageContent = new Control();
bool stop = false;
bool debugMode = umbraco.presentation.UmbracoContext.Current.Request.IsDebug;
while (!stop)
{
System.Web.HttpContext.Current.Trace.Write("template", "Begining of parsing rutine...");
int tagIndex = tempOutput.ToString().ToLower().IndexOf("<?umbraco");
if (tagIndex > -1)
{
String tempElementContent = "";
pageContent.Controls.Add(new LiteralControl(tempOutput.ToString().Substring(0, tagIndex)));
tempOutput.Remove(0, tagIndex);
String tag = tempOutput.ToString().Substring(0, tempOutput.ToString().IndexOf(">") + 1);
Hashtable attributes = helper.ReturnAttributes(tag);
// Check whether it's a single tag (<?.../>) or a tag with children (<?..>...</?...>)
if (tag.Substring(tag.Length - 2, 1) != "/" && tag.IndexOf(" ") > -1)
{
String closingTag = "</" + (tag.Substring(1, tag.IndexOf(" ") - 1)) + ">";
// Tag with children are only used when a macro is inserted by the umbraco-editor, in the
// following format: "<?UMBRACO_MACRO ...><IMG SRC="..."..></?UMBRACO_MACRO>", so we
// need to delete extra information inserted which is the image-tag and the closing
// umbraco_macro tag
if (tempOutput.ToString().IndexOf(closingTag) > -1)
{
tempOutput.Remove(0, tempOutput.ToString().IndexOf(closingTag));
}
}
System.Web.HttpContext.Current.Trace.Write("umbTemplate", "Outputting item: " + tag);
// Handle umbraco macro tags
if (tag.ToString().ToLower().IndexOf("umbraco_macro") > -1)
{
if (debugMode)
pageContent.Controls.Add(new LiteralControl("<div title=\"Macro Tag: '" + System.Web.HttpContext.Current.Server.HtmlEncode(tag) + "'\" style=\"border: 1px solid #009;\">"));
// NH: Switching to custom controls for macros
if (UmbracoConfig.For.UmbracoSettings().Templates.UseAspNetMasterPages)
{
umbraco.presentation.templateControls.Macro macroControl = new umbraco.presentation.templateControls.Macro();
macroControl.Alias = helper.FindAttribute(attributes, "macroalias");
IDictionaryEnumerator ide = attributes.GetEnumerator();
while (ide.MoveNext())
if (macroControl.Attributes[ide.Key.ToString()] == null)
macroControl.Attributes.Add(ide.Key.ToString(), ide.Value.ToString());
pageContent.Controls.Add(macroControl);
}
else
{
macro tempMacro;
String macroID = helper.FindAttribute(attributes, "macroid");
if (macroID != String.Empty)
tempMacro = getMacro(macroID);
else
tempMacro = macro.GetMacro(helper.FindAttribute(attributes, "macroalias"));
if (tempMacro != null)
{
try
{
Control c = tempMacro.renderMacro(attributes, umbPage.Elements, umbPage.PageID);
if (c != null)
pageContent.Controls.Add(c);
else
System.Web.HttpContext.Current.Trace.Warn("Template", "Result of macro " + tempMacro.Name + " is null");
}
catch (Exception e)
{
System.Web.HttpContext.Current.Trace.Warn("Template", "Error adding macro " + tempMacro.Name, e);
}
}
}
if (debugMode)
pageContent.Controls.Add(new LiteralControl("</div>"));
}
else
{
if (tag.ToLower().IndexOf("umbraco_getitem") > -1)
{
// NH: Switching to custom controls for items
if (UmbracoConfig.For.UmbracoSettings().Templates.UseAspNetMasterPages)
{
umbraco.presentation.templateControls.Item itemControl = new umbraco.presentation.templateControls.Item();
itemControl.Field = helper.FindAttribute(attributes, "field");
IDictionaryEnumerator ide = attributes.GetEnumerator();
while (ide.MoveNext())
if (itemControl.Attributes[ide.Key.ToString()] == null)
itemControl.Attributes.Add(ide.Key.ToString(), ide.Value.ToString());
pageContent.Controls.Add(itemControl);
}
else
{
try
{
if (helper.FindAttribute(attributes, "nodeId") != "" && int.Parse(helper.FindAttribute(attributes, "nodeId")) != 0)
{
cms.businesslogic.Content c = new umbraco.cms.businesslogic.Content(int.Parse(helper.FindAttribute(attributes, "nodeId")));
item umbItem = new item(c.getProperty(helper.FindAttribute(attributes, "field")).Value.ToString(), attributes);
tempElementContent = umbItem.FieldContent;
// Check if the content is published
if (c.nodeObjectType == cms.businesslogic.web.Document._objectType)
{
try
{
cms.businesslogic.web.Document d = (cms.businesslogic.web.Document)c;
if (!d.Published)
tempElementContent = "";
}
catch { }
}
}
else
{
// NH adds Live Editing test stuff
item umbItem = new item(umbPage.Elements, attributes);
// item umbItem = new item(umbPage.PageElements[helper.FindAttribute(attributes, "field")].ToString(), attributes);
tempElementContent = umbItem.FieldContent;
}
if (debugMode)
tempElementContent =
"<div title=\"Field Tag: '" + System.Web.HttpContext.Current.Server.HtmlEncode(tag) + "'\" style=\"border: 1px solid #fc6;\">" + tempElementContent + "</div>";
}
catch (Exception e)
{
System.Web.HttpContext.Current.Trace.Warn("umbracoTemplate", "Error reading element (" + helper.FindAttribute(attributes, "field") + ")", e);
}
}
}
}
tempOutput.Remove(0, tempOutput.ToString().IndexOf(">") + 1);
tempOutput.Insert(0, tempElementContent);
}
else
{
pageContent.Controls.Add(new LiteralControl(tempOutput.ToString()));
break;
}
}
return pageContent;
}
[Obsolete("Use Umbraco.Web.Templates.TemplateUtilities.ParseInternalLinks instead")]
public static string ParseInternalLinks(string pageContents)
{
return Umbraco.Web.Templates.TemplateUtilities.ParseInternalLinks(pageContents);
}
/// <summary>
/// Parses the content of the templateOutput stringbuilder, and matches any tags given in the
/// XML-file /umbraco/config/umbracoTemplateTags.xml.
/// Replaces the found tags in the StringBuilder object, with "real content"
/// </summary>
/// <param name="umbPage"></param>
public void Parse(page umbPage)
{
System.Web.HttpContext.Current.Trace.Write("umbracoTemplate", "Start parsing");
// First parse for known umbraco tags
// <?UMBRACO_MACRO/> - macros
// <?UMBRACO_GETITEM/> - print item from page, level, or recursive
MatchCollection tags = Regex.Matches(_templateOutput.ToString(), "<\\?UMBRACO_MACRO[^>]*/>|<\\?UMBRACO_GETITEM[^>]*/>|<\\?(?<tagName>[\\S]*)[^>]*/>", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
foreach (Match tag in tags)
{
Hashtable attributes = helper.ReturnAttributes(tag.Value.ToString());
if (tag.ToString().ToLower().IndexOf("umbraco_macro") > -1)
{
String macroID = helper.FindAttribute(attributes, "macroid");
if (macroID != "")
{
macro tempMacro = getMacro(macroID);
_templateOutput.Replace(tag.Value.ToString(), tempMacro.MacroContent.ToString());
}
}
else
{
if (tag.ToString().ToLower().IndexOf("umbraco_getitem") > -1)
{
try
{
String tempElementContent = umbPage.Elements[helper.FindAttribute(attributes, "field")].ToString();
MatchCollection tempMacros = Regex.Matches(tempElementContent, "<\\?UMBRACO_MACRO(?<attributes>[^>]*)><img[^>]*><\\/\\?UMBRACO_MACRO>", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
foreach (Match tempMacro in tempMacros)
{
Hashtable tempAttributes = helper.ReturnAttributes(tempMacro.Groups["attributes"].Value.ToString());
String macroID = helper.FindAttribute(tempAttributes, "macroid");
if (Convert.ToInt32(macroID) > 0)
{
macro tempContentMacro = getMacro(macroID);
_templateOutput.Replace(tag.Value.ToString(), tempContentMacro.MacroContent.ToString());
}
}
_templateOutput.Replace(tag.Value.ToString(), tempElementContent);
}
catch (Exception e)
{
System.Web.HttpContext.Current.Trace.Warn("umbracoTemplate", "Error reading element (" + helper.FindAttribute(attributes, "field") + ")", e);
}
}
}
}
System.Web.HttpContext.Current.Trace.Write("umbracoTemplate", "Done parsing");
}
#endregion
#region private methods
private macro getMacro(String macroID)
{
System.Web.HttpContext.Current.Trace.Write("umbracoTemplate", "Starting macro (" + macroID.ToString() + ")");
return macro.GetMacro(Convert.ToInt16(macroID));
}
private String FindAttribute(Hashtable attributes, String key)
{
if (attributes[key] != null)
return attributes[key].ToString();
else
return "";
}
#endregion
/// <summary>
/// Unused, please do not use
/// </summary>
[Obsolete("Obsolete, For querying the database use the new UmbracoDatabase object ApplicationContext.Current.DatabaseContext.Database", false)]
protected static ISqlHelper SqlHelper
{
get { return Application.SqlHelper; }
}
#region constructors
public static string GetMasterPageName(int templateID)
{
return GetMasterPageName(templateID, null);
}
public static string GetMasterPageName(int templateID, string templateFolder)
{
var t = new template(templateID);
return !string.IsNullOrEmpty(templateFolder)
? t.AlternateMasterPageFile(templateFolder)
: t.MasterPageFile;
}
public template(int templateID)
{
var tId = templateID;
var t = ApplicationContext.Current.ApplicationCache.RuntimeCache.GetCacheItem<template>(
string.Format("{0}{1}", CacheKeys.TemplateFrontEndCacheKey, tId), () =>
{
using (var sqlHelper = Application.SqlHelper)
using (var templateData = sqlHelper.ExecuteReader(@"select nodeId, alias, node.parentID as master, text, design
from cmsTemplate
inner join umbracoNode node on (node.id = cmsTemplate.nodeId)
where nodeId = @templateID",
sqlHelper.CreateParameter("@templateID", templateID)))
{
if (templateData.Read())
{
// Get template master and replace content where the template
if (!templateData.IsNull("master"))
_masterTemplate = templateData.GetInt("master");
if (!templateData.IsNull("alias"))
_templateAlias = templateData.GetString("alias");
if (!templateData.IsNull("text"))
_templateName = templateData.GetString("text");
if (!templateData.IsNull("design"))
_templateDesign = templateData.GetString("design");
}
}
return this;
});
if (t == null)
throw new InvalidOperationException("Could not find a tempalte with id " + templateID);
this._masterTemplate = t._masterTemplate;
this._templateAlias = t._templateAlias;
this._templateDesign = t._templateDesign;
this._masterTemplate = t._masterTemplate;
this._templateName = t._templateName;
// Only check for master on legacy templates - can show error when using master pages.
if (!UmbracoConfig.For.UmbracoSettings().Templates.UseAspNetMasterPages)
{
checkForMaster(tId);
}
}
private void checkForMaster(int templateID) {
// Get template design
if (_masterTemplate != 0 && _masterTemplate != templateID) {
template masterTemplateDesign = new template(_masterTemplate);
if (masterTemplateDesign.TemplateContent.IndexOf("<?UMBRACO_TEMPLATE_LOAD_CHILD/>") > -1
|| masterTemplateDesign.TemplateContent.IndexOf("<?UMBRACO_TEMPLATE_LOAD_CHILD />") > -1) {
_templateOutput.Append(
masterTemplateDesign.TemplateContent.Replace("<?UMBRACO_TEMPLATE_LOAD_CHILD/>",
_templateDesign).Replace("<?UMBRACO_TEMPLATE_LOAD_CHILD />", _templateDesign)
);
} else
_templateOutput.Append(_templateDesign);
} else {
if (_masterTemplate == templateID)
{
cms.businesslogic.template.Template t = cms.businesslogic.template.Template.GetTemplate(templateID);
string templateName = (t != null) ? t.Text : string.Format("'Template with id: '{0}", templateID);
System.Web.HttpContext.Current.Trace.Warn("template",
String.Format("Master template is the same as the current template. It would cause an endless loop! Make sure that the current template '{0}' has another Master Template than itself. You can change this in the template editor under 'Settings'", templateName));
_templateOutput.Append(_templateDesign);
}
}
}
[Obsolete("Use ApplicationContext.Current.ApplicationCache.ClearCacheForTemplate instead")]
public static void ClearCachedTemplate(int templateID)
{
DistributedCache.Instance.RefreshTemplateCache(templateID);
}
public template(String templateContent)
{
_templateOutput.Append(templateContent);
_masterTemplate = 0;
}
#endregion
}
}
| |
/* Copyright (c) 2006-2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Change history
* Oct 13 2008 Joe Feser [email protected]
* Converted ArrayLists and other .NET 1.1 collections to use Generics
* Combined IExtensionElement and IExtensionElementFactory interfaces
*
*/
#region Using directives
#define USE_TRACING
using System;
using System.Collections;
using Google.GData.Client;
using System.Collections.Generic;
#endregion
//////////////////////////////////////////////////////////////////////
// contains typed collections based on the 1.1 .NET framework
// using typed collections has the benefit of additional code reliability
// and using them in the collection editor
//
//////////////////////////////////////////////////////////////////////
namespace Google.GData.Extensions
{
/// <summary>
/// base class to take an object pointer with extension information
/// and expose a localname/namespace subset as a collection
/// that still works on the original
/// </summary>
public class ExtensionCollection<T> : IList<T> where T : class, IExtensionElementFactory, new()
{
/// <summary>holds the owning feed</summary>
private IExtensionContainer container;
private List<T> _items = new List<T>();
private static Dictionary<Type, IExtensionElementFactory> _cache = new Dictionary<Type, IExtensionElementFactory>();
/// <summary>
/// Get the XmlName for the Type
/// </summary>
/// <returns></returns>
private static string CtorXmlName()
{
IExtensionElementFactory val;
Type t = typeof(T);
lock (_cache)
{
if (!_cache.TryGetValue(t, out val))
{
val = new T();
_cache[t] = val;
}
}
return val.XmlName;
}
/// <summary>
/// Get the Xml Namespace for the Type
/// </summary>
/// <returns></returns>
private static string CtorXmlNS()
{
IExtensionElementFactory val;
Type t = typeof(T);
lock (_cache)
{
if (!_cache.TryGetValue(t, out val))
{
val = new T();
_cache[t] = val;
}
}
return val.XmlNameSpace;
}
/// <summary>
/// protected default constructor, not usable by outside
/// </summary>
public ExtensionCollection()
{
}
/// <summary>
/// takes the base object, and the localname/ns combo to look for
/// will copy objects to an internal array for caching. Note that when the external
/// ExtensionList is modified, this will have no effect on this copy
/// </summary>
/// <param name="containerElement">the base element holding the extension list</param>
public ExtensionCollection(IExtensionContainer containerElement)
: this(containerElement, CtorXmlName(), CtorXmlNS())
{
}
/// <summary>
/// takes the base object, and the localname/ns combo to look for
/// will copy objects to an internal array for caching. Note that when the external
/// ExtensionList is modified, this will have no effect on this copy
/// </summary>
/// <param name="containerElement">the base element holding the extension list</param>
/// <param name="localName">the local name of the extension</param>
/// <param name="ns">the namespace</param>
public ExtensionCollection(IExtensionContainer containerElement, string localName, string ns)
: base()
{
this.container = containerElement;
if (this.container != null)
{
ExtensionList arr = this.container.FindExtensions(localName, ns);
foreach (T o in arr)
{
_items.Add(o);
}
}
}
/// <summary>standard typed accessor method </summary>
public T this[int index]
{
get
{
return ((T)_items[index]);
}
set
{
setItem(index, value);
}
}
/// <summary>
/// useful for subclasses that want to overload the set method
/// </summary>
/// <param name="index">the index in the array</param>
/// <param name="item">the item to set </param>
protected void setItem(int index, T item)
{
if (_items[index] != null)
{
if (this.container != null)
{
this.container.ExtensionElements.Remove(_items[index]);
}
}
_items[index] = item;
if (item != null && this.container != null)
{
this.container.ExtensionElements.Add(item);
}
}
/// <summary>
/// default untyped add implementation. Adds the object as well to the parent
/// object ExtensionList
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public int Add(T value)
{
if (this.container != null)
{
this.container.ExtensionElements.Add(value);
}
_items.Add(value);
return _items.Count - 1;
}
/// <summary>
/// inserts an element into the collection by index
/// </summary>
/// <param name="index"></param>
/// <param name="value"></param>
public void Insert(int index, T value)
{
if (this.container != null && this.container.ExtensionElements.Contains(value))
{
this.container.ExtensionElements.Remove(value);
}
this.container.ExtensionElements.Add(value);
_items.Insert(index, value);
}
/// <summary>
/// removes an element from the collection
/// </summary>
/// <param name="value"></param>
public bool Remove(T value)
{
bool success = _items.Remove(value);
if (success && this.container != null)
{
success &= this.container.ExtensionElements.Remove(value);
}
return success;
}
/// <summary>standard typed indexOf method </summary>
public int IndexOf(T value)
{
return (_items.IndexOf(value));
}
/// <summary>standard typed Contains method </summary>
public bool Contains(T value)
{
// If value is not of type AtomEntry, this will return false.
return (_items.Contains(value));
}
/// <summary>standard override OnClear, to remove the objects from the extension list</summary>
protected void OnClear()
{
if (this.container != null)
{
for (int i = 0; i < this.Count; i++)
{
this.container.ExtensionElements.Remove(_items[i]);
}
}
}
#region IList<T> Members
public void RemoveAt(int index)
{
T item = _items[index];
//_items.RemoveAt(index);
Remove(item);
}
#endregion
#region ICollection<T> Members
void ICollection<T>.Add(T item)
{
Add(item);
}
public void Clear()
{
OnClear();
_items.Clear();
}
public void CopyTo(T[] array, int arrayIndex)
{
_items.ToArray().CopyTo(array, arrayIndex);
}
public int Count
{
get
{
return _items.Count;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
bool ICollection<T>.Remove(T item)
{
return Remove(item);
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
return _items.GetEnumerator();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return _items.GetEnumerator();
}
#endregion
}
}
| |
using System;
using Signum.Utilities;
using Signum.Utilities.ExpressionTrees;
namespace Signum.Entities
{
[Serializable]
public class OperationSymbol : Symbol
{
private OperationSymbol() { }
private OperationSymbol(Type declaringType, string fieldName)
: base(declaringType, fieldName)
{
}
public static class Construct<T>
where T : class, IEntity
{
public static ConstructSymbol<T>.Simple Simple(Type declaringType, string fieldName)
{
return new SimpleImp(new OperationSymbol(declaringType, fieldName));
}
public static ConstructSymbol<T>.From<F> From<F>(Type declaringType, string fieldName)
where F : class, IEntity
{
return new FromImp<F>(new OperationSymbol(declaringType, fieldName));
}
public static ConstructSymbol<T>.FromMany<F> FromMany<F>(Type declaringType, string fieldName)
where F : class, IEntity
{
return new FromManyImp<F>(new OperationSymbol(declaringType, fieldName));
}
[Serializable]
class SimpleImp : ConstructSymbol<T>.Simple
{
public SimpleImp(OperationSymbol symbol)
{
this.Symbol = symbol;
}
public OperationSymbol Symbol { get; internal set; }
public override string ToString()
{
return "{0}({1})".FormatWith(this.GetType().TypeName(), Symbol);
}
}
[Serializable]
class FromImp<F> : ConstructSymbol<T>.From<F>
where F : class, IEntity
{
public FromImp(OperationSymbol symbol)
{
Symbol = symbol;
}
public OperationSymbol Symbol { get; private set; }
public Type BaseType
{
get { return typeof(F); }
}
public override string ToString()
{
return "{0}({1})".FormatWith(this.GetType().TypeName(), Symbol);
}
}
[Serializable]
class FromManyImp<F> : ConstructSymbol<T>.FromMany<F>
where F : class, IEntity
{
public FromManyImp(OperationSymbol symbol)
{
Symbol = symbol;
}
public OperationSymbol Symbol { get; set; }
public Type BaseType
{
get { return typeof(F); }
}
public override string ToString()
{
return "{0}({1})".FormatWith(this.GetType().TypeName(), Symbol);
}
}
}
public static ExecuteSymbol<T> Execute<T>(Type declaringType, string fieldName)
where T : class, IEntity
{
return new ExecuteSymbolImp<T>(new OperationSymbol(declaringType, fieldName));
}
public static DeleteSymbol<T> Delete<T>(Type declaringType, string fieldName)
where T : class, IEntity
{
return new DeleteSymbolImp<T>(new OperationSymbol(declaringType, fieldName));
}
[Serializable]
class ExecuteSymbolImp<T> : ExecuteSymbol<T>
where T : class, IEntity
{
public ExecuteSymbolImp(OperationSymbol symbol)
{
Symbol = symbol;
}
public OperationSymbol Symbol { get; private set; }
public Type BaseType
{
get { return typeof(T); }
}
public override string ToString()
{
return "{0}({1})".FormatWith(this.GetType().TypeName(), Symbol);
}
}
[Serializable]
class DeleteSymbolImp<T> : DeleteSymbol<T>
where T : class, IEntity
{
public DeleteSymbolImp(OperationSymbol symbol)
{
Symbol = symbol;
}
public OperationSymbol Symbol { get; private set; }
public Type BaseType
{
get { return typeof(T); }
}
public override string ToString()
{
return "{0}({1})".FormatWith(this.GetType().TypeName(), Symbol);
}
}
}
public interface IOperationSymbolContainer
{
OperationSymbol Symbol { get; }
}
public interface IEntityOperationSymbolContainer : IOperationSymbolContainer
{
}
public interface IEntityOperationSymbolContainer<in T> : IEntityOperationSymbolContainer
where T : class, IEntity
{
Type BaseType { get; }
}
public static class ConstructSymbol<T>
where T : class, IEntity
{
public interface Simple : IOperationSymbolContainer
{
}
public interface From<in F> : IEntityOperationSymbolContainer<F>
where F : class, IEntity
{
}
public interface FromMany<in F> : IOperationSymbolContainer
where F : class, IEntity
{
Type BaseType { get; }
}
}
public interface ExecuteSymbol<in T> : IEntityOperationSymbolContainer<T>
where T : class, IEntity
{
}
public interface DeleteSymbol<in T> : IEntityOperationSymbolContainer<T>
where T : class, IEntity
{
}
[Serializable]
public class OperationInfo
{
public OperationInfo(OperationSymbol symbol, OperationType type)
{
this.OperationSymbol = symbol;
this.OperationType = type;
}
public OperationSymbol OperationSymbol { get; internal set; }
public OperationType OperationType { get; internal set; }
public bool? CanBeModified { get; internal set; }
public bool? CanBeNew { get; internal set; }
public bool? HasStates { get; internal set; }
public bool? HasCanExecute { get; internal set; }
public bool Returns { get; internal set; }
public Type? ReturnType { get; internal set; }
public Type? BaseType { get; internal set; }
public override string ToString()
{
return "{0} ({1})".FormatWith(OperationSymbol, OperationType);
}
public bool IsEntityOperation
{
get
{
return OperationType == OperationType.Execute ||
OperationType == OperationType.ConstructorFrom ||
OperationType == OperationType.Delete;
}
}
}
[InTypeScript(true)]
public enum OperationType
{
Execute,
Delete,
Constructor,
ConstructorFrom,
ConstructorFromMany
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* This version has been heavily modified from it's original version by InWorldz,LLC
* Beth Reischl - 2/28/2010
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Xml;
using OpenMetaverse;
using DirFindFlags = OpenMetaverse.DirectoryManager.DirFindFlags;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Data.SimpleDB;
namespace OpenSim.Region.CoreModules.Avatar.Search
{
public class AvatarSearchModule : IRegionModule
{
//
// Log module
//
//private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
//
// Module vars
//
private ConnectionFactory _connFactory;
// private IConfigSource profileConfig;
private List<Scene> m_Scenes = new List<Scene>();
//private string m_SearchServer = String.Empty;
private bool m_Enabled = true;
// NOTE: RDB-related code is all grouped here and is copied in LandManagementModule (for now).
// This needs to be factored. I'd like to see MySQLSimpleDB be extended to
// a MySQLSimpleRegionDB class that wraps the underlying single-db calls into combined calls
// and redirects queries to the correct database.
private string _rdbConnectionTemplate;
private string _rdbConnectionTemplateDebug;
private readonly TimeSpan RDB_CACHE_TIMEOUT = TimeSpan.FromHours(4);
private DateTime _rdbCacheTime;
private List<string> _rdbHostCache = new List<string>();
// Filter land search results to online regions to remove dead parcels.
private const int REGIONS_CACHE_TIME = 300; // regions update land search results filters once every 5 minutes
private List<UUID> mRegionsOnline = new List<UUID>(); // Count of 0 means no filter, initially.
private DateTime mRegionsOnlineStamp = DateTime.MinValue; // first reference requires an update
// status flags embedded in search replay messages of classifieds, events, groups, and places.
// Places
private const uint STATUS_SEARCH_PLACES_NONE = 0x0;
private const uint STATUS_SEARCH_PLACES_BANNEDWORD = 0x1 << 0;
private const uint STATUS_SEARCH_PLACES_SHORTSTRING = 0x1 << 1;
private const uint STATUS_SEARCH_PLACES_FOUNDNONE = 0x1 << 2;
private const uint STATUS_SEARCH_PLACES_SEARCHDISABLED = 0x1 << 3;
private const uint STATUS_SEARCH_PLACES_ESTATEEMPTY = 0x1 << 4;
// Events
private const uint STATUS_SEARCH_EVENTS_NONE = 0x0;
private const uint STATUS_SEARCH_EVENTS_BANNEDWORD = 0x1 << 0;
private const uint STATUS_SEARCH_EVENTS_SHORTSTRING = 0x1 << 1;
private const uint STATUS_SEARCH_EVENTS_FOUNDNONE = 0x1 << 2;
private const uint STATUS_SEARCH_EVENTS_SEARCHDISABLED = 0x1 << 3;
private const uint STATUS_SEARCH_EVENTS_NODATEOFFSET = 0x1 << 4;
private const uint STATUS_SEARCH_EVENTS_NOCATEGORY = 0x1 << 5;
private const uint STATUS_SEARCH_EVENTS_NOQUERY = 0x1 << 6;
//Classifieds
private const uint STATUS_SEARCH_CLASSIFIEDS_NONE = 0x0;
private const uint STATUS_SEARCH_CLASSIFIEDS_BANNEDWORD = 0x1 << 0;
private const uint STATUS_SEARCH_CLASSIFIEDS_SHORTSTRING = 0x1 << 1;
private const uint STATUS_SEARCH_CLASSIFIEDS_FOUNDNONE = 0x1 << 2;
private const uint STATUS_SEARCH_CLASSIFIEDS_SEARCHDISABLED = 0x1 << 3;
public void Initialize(Scene scene, IConfigSource config)
{
if (!m_Enabled)
return;
IConfig myConfig = config.Configs["Startup"];
string connstr = myConfig.GetString("core_connection_string", String.Empty);
_rdbConnectionTemplate = myConfig.GetString("rdb_connection_template", String.Empty);
if (!String.IsNullOrWhiteSpace(_rdbConnectionTemplate))
{
if (!_rdbConnectionTemplate.ToLower().Contains("data source"))
{
_rdbConnectionTemplate = "Data Source={0};" + _rdbConnectionTemplate;
}
}
_rdbConnectionTemplateDebug = myConfig.GetString("rdb_connection_template_debug", String.Empty);
if (!String.IsNullOrWhiteSpace(_rdbConnectionTemplateDebug))
{
if (!_rdbConnectionTemplateDebug.ToLower().Contains("data source"))
{
_rdbConnectionTemplateDebug = "Data Source={0};" + _rdbConnectionTemplateDebug;
}
}
_connFactory = new ConnectionFactory("MySQL", connstr);
CacheRdbHosts();
if (!m_Scenes.Contains(scene))
m_Scenes.Add(scene);
scene.EventManager.OnNewClient += OnNewClient;
}
private void CacheRdbHosts()
{
using (ISimpleDB db = _connFactory.GetConnection())
{
CacheRdbHosts(db);
}
}
private void CacheRdbHosts(ISimpleDB db)
{
List<Dictionary<string, string>> hostNames = db.QueryWithResults("SELECT host_name FROM RdbHosts");
_rdbHostCache.Clear();
foreach (var hostNameDict in hostNames)
{
_rdbHostCache.Add(hostNameDict["host_name"]);
}
_rdbCacheTime = DateTime.Now;
}
private void RefreshList(ISimpleDB rdb, string query, Dictionary<string, object> parms, List<Dictionary<string, string>> results)
{
results.AddRange(rdb.QueryWithResults(query, parms));
}
private const int MAX_RESULTS = 100;
class RDBConnectionQuery
{
private const int QUERY_SIZE = 50;
private ISimpleDB m_rdb = null;
private string m_query = String.Empty;
private Dictionary<string, object> m_parms = null;
private int m_offset = 0;
private List<Dictionary<string, string>> m_results = new List<Dictionary<string, string>>();
public RDBConnectionQuery(ISimpleDB rdb, string query, uint queryFlags, Dictionary<string, object> parms)
{
m_rdb = rdb;
m_query = query;
m_parms = parms;
RefreshResults();
}
private void RefreshResults()
{
string limited_query = m_query + " LIMIT " + m_offset.ToString() + ", " + QUERY_SIZE.ToString();
m_results.AddRange(m_rdb.QueryWithResults(limited_query, m_parms));
}
public Dictionary<string, string> GetNext()
{
if (m_results.Count < 1)
{
// Don't auto-fetch the next block when there are none, otherwise at the end we'll keep trying to fetch more.
return null;
}
return m_results[0];
}
public void Consume()
{
m_results.RemoveAt(0);
if (m_results.Count < 1)
{
// We transitioned from having results to an empty list. Update this once.
m_offset += QUERY_SIZE; // advance the query to the next block
RefreshResults();
}
}
} // class RDBQuery
private Dictionary<string, string> ConsumeNext(List<RDBConnectionQuery> rdbQueries, uint queryFlags)
{
Dictionary<string, string> best = null;
RDBConnectionQuery bestDB = null;
float bestValue = 0f;
string bestText = String.Empty;
foreach (RDBConnectionQuery rdb in rdbQueries)
{
// we need to compare the first item in each list to see which one comes next
Dictionary<string, string> first = rdb.GetNext();
if (first == null) continue;
bool ascending = ((queryFlags & (uint)DirFindFlags.SortAsc) != 0);
bool better = false;
if ((queryFlags & (uint)DirFindFlags.NameSort) != 0)
{
if (first.ContainsKey("Name"))
{
string name = first["Name"];
better = (name.CompareTo(bestText) < 0);
if (!ascending)
better = !better;
if (better || (best == null))
{
best = first;
bestDB = rdb;
bestText = name;
}
}
}
else if ((queryFlags & (uint)DirFindFlags.PricesSort) != 0)
{
if (first.ContainsKey("SalePrice"))
{
float price = (float)Convert.ToInt32(first["SalePrice"]);
better = (price < bestValue);
if (!ascending)
better = !better;
if (better || (best == null))
{
best = first;
bestDB = rdb;
bestValue = price;
}
}
}
else if ((queryFlags & (uint)DirFindFlags.PerMeterSort) != 0)
{
if (first.ContainsKey("SalePrice") && first.ContainsKey("Area"))
{
float price = (float)Convert.ToInt32(first["SalePrice"]);
float area = (float)Convert.ToInt32(first["Area"]);
float ppm = -1.0f;
if (area > 0)
ppm = price / area;
better = (ppm < bestValue);
if (!ascending)
better = !better;
if (better || (best == null))
{
best = first;
bestDB = rdb;
bestValue = ppm;
}
}
}
else if ((queryFlags & (uint)DirFindFlags.AreaSort) != 0)
{
if (first.ContainsKey("Area"))
{
float area = (float)Convert.ToInt32(first["Area"]);
better = (area < bestValue);
if (!ascending)
better = !better;
if (better || (best == null))
{
best = first;
bestDB = rdb;
bestValue = area;
}
}
}
else // any order will do
{
// just grab the first one available
best = first;
bestDB = rdb;
break;
}
}
if (best != null)
bestDB.Consume();
return best;
}
private List<Dictionary<string, string>> DoLandQueryAndCombine(IClientAPI remoteClient, ISimpleDB coreDb,
string query, Dictionary<string, object> parms,
uint queryFlags, int queryStart, int queryEnd,
List<UUID> regionsToInclude)
{
string[] rdbHosts = this.CheckAndRetrieveRdbHostList(coreDb);
if (rdbHosts.Length == 0)
{
// RDB not configured. Fall back to core db.
return coreDb.QueryWithResults(query, parms);
}
List<RDBConnectionQuery> rdbQueries = new List<RDBConnectionQuery>();
int whichDB = 0;
foreach (string host in rdbHosts)
{
// Initialize the RDB connection and initial results lists
ConnectionFactory rdbFactory;
if ((++whichDB == 1) || String.IsNullOrWhiteSpace(_rdbConnectionTemplateDebug))
rdbFactory = new ConnectionFactory("MySQL", String.Format(_rdbConnectionTemplate, host));
else // Special debugging support for multiple RDBs on one machine ("inworldz_rdb2", etc)
rdbFactory = new ConnectionFactory("MySQL", String.Format(_rdbConnectionTemplateDebug, host, whichDB));
RDBConnectionQuery rdb = new RDBConnectionQuery(rdbFactory.GetConnection(), query, queryFlags, parms);
rdbQueries.Add(rdb);
}
List<Dictionary<string, string>> finalList = new List<Dictionary<string, string>>();
int current = 0;
Dictionary<string, string> result = null;
while ((result = ConsumeNext(rdbQueries, queryFlags)) != null)
{
UUID regionUUID = new UUID(result["RegionUUID"]);
// When regionsToInclude.Count==0, it means do not filter by regions.
if ((regionsToInclude.Count == 0) || regionsToInclude.Contains(regionUUID))
{
// 0-based numbering
if ((current >= queryStart) && (current <= queryEnd))
finalList.Add(result);
current++;
}
}
return finalList;
}
private string[] CheckAndRetrieveRdbHostList(ISimpleDB coreDb)
{
lock (_rdbHostCache)
{
if (DateTime.Now - _rdbCacheTime >= RDB_CACHE_TIMEOUT)
{
//recache
CacheRdbHosts(coreDb);
}
return _rdbHostCache.ToArray();
}
}
// NOTE: END OF RDB-related code copied in LandManagementModule (for now).
public void PostInitialize()
{
if (!m_Enabled)
return;
}
public void Close()
{
}
public string Name
{
get { return "SearchModule"; }
}
public bool IsSharedModule
{
get { return true; }
}
/// New Client Event Handler
private void OnNewClient(IClientAPI client)
{
// Subscribe to messages
client.OnDirPlacesQuery += DirPlacesQuery;
client.OnDirFindQuery += DirFindQuery;
client.OnDirPopularQuery += DirPopularQuery;
client.OnDirLandQuery += DirLandQuery;
client.OnDirClassifiedQuery += DirClassifiedQuery;
// Response after Directory Queries
client.OnEventInfoRequest += EventInfoRequest;
client.OnClassifiedInfoRequest += ClassifiedInfoRequest;
}
/// <summary>
/// Return the current regions UP after possibly refreshing if stale.
/// </summary>
/// <returns>
/// null if could not fetch the list (error, unreliable list)
/// a list (possibly empty although it should always find this one) otherwise
/// </returns>
protected List<UUID> UpdateRegionsList(ISimpleDB coredb)
{
List<UUID> regions = new List<UUID>();
lock (mRegionsOnline)
{
// The viewer fires 3 parallel requests together.
// Protect against multiple initial parallel requests by using
// the lock to block the other threads during the refresh. They need it anyway.
// If we're up to date though, just return it.
if ((DateTime.Now - mRegionsOnlineStamp).TotalSeconds < REGIONS_CACHE_TIME)
return mRegionsOnline;
List<Dictionary<string, string>> results = coredb.QueryWithResults("SELECT uuid FROM regions LIMIT 999999999999"); // no limit
foreach (var row in results)
{
regions.Add(new UUID(row["UUID"]));
}
// Now stamp it inside the lock so that if we reenter,
// second caller will not make another request.
mRegionsOnline = regions;
mRegionsOnlineStamp = DateTime.Now;
}
return regions;
}
protected void DirPlacesQuery(IClientAPI remoteClient, UUID queryID, string queryText, int queryFlags, int category, string simName,
int queryStart)
{
// m_log.DebugFormat("[LAND SEARCH]: In Places Search for queryText: {0} with queryFlag: {1} with category {2} for simName {3}",
// queryText, queryFlags.ToString("X"), category.ToString(), simName);
queryText = queryText.Trim(); // newer viewers sometimes append a space
string query = String.Empty;
//string newQueryText = "%" + queryText + "%";
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?searchText", queryText);
parms.Add("?searchFlags", queryFlags);
if (category > 0)
parms.Add("?searchCategory", category);
//parms.Add("?searchSimName", simName);
Single dwell = 0;
int count = MAX_RESULTS + 1; // +1 so that the viewer knows to enable the NEXT button (it seems)
int i = 0;
int queryEnd = queryStart + count - 1; // 0-based
query = "select * from land where LandFlags & "+ParcelFlags.ShowDirectory.ToString("d");
if (category > 0)
query += " AND Category=?searchCategory";
query += " AND (Name REGEXP ?searchText OR Description REGEXP ?searchText) order by Name, Description";
using (ISimpleDB db = _connFactory.GetConnection())
{
List<UUID> regionsToInclude = UpdateRegionsList(db);
List<Dictionary<string, string>> results = DoLandQueryAndCombine(remoteClient, db, query, parms, 0, queryStart, queryEnd, regionsToInclude);
DirPlacesReplyData[] data = new DirPlacesReplyData[results.Count < 1 ? 1 : results.Count];
foreach (Dictionary<string, string> row in results)
{
bool auction = false;
data[i] = new DirPlacesReplyData();
data[i].parcelID = new UUID(row["uuid"]);
data[i].name = row["name"];
data[i].forSale = (Convert.ToInt16(row["SalePrice"]) > 0);
data[i].auction = auction;
data[i].dwell = dwell;
data[i].Status = STATUS_SEARCH_PLACES_NONE; // 0, success
i++;
}
if (results.Count == 0)
{
data[0] = new DirPlacesReplyData();
data[0].parcelID = UUID.Zero;
data[0].name = String.Empty;
data[0].forSale = false;
data[0].auction = false;
data[0].dwell = 0;
data[0].Status = STATUS_SEARCH_PLACES_FOUNDNONE; // empty results
}
remoteClient.SendDirPlacesReply(queryID, data);
}
}
public void DirPopularQuery(IClientAPI remoteClient, UUID queryID, uint queryFlags)
{
// This is not even in place atm, and really needs just a complete
// rewrite as Popular places doesn't even take Traffic into consideration.
remoteClient.SendAgentAlertMessage(
"We're sorry, Popular Places is not in place yet!", false);
/*
Hashtable ReqHash = new Hashtable();
ReqHash["flags"] = queryFlags.ToString();
Hashtable result = GenericXMLRPCRequest(ReqHash,
"dir_popular_query");
if (!Convert.ToBoolean(result["success"]))
{
remoteClient.SendAgentAlertMessage(
result["errorMessage"].ToString(), false);
return;
}
ArrayList dataArray = (ArrayList)result["data"];
int count = dataArray.Count;
if (count > 100)
count = MAX_RESULTS + 1; // +1 so that the viewer knows to enable the NEXT button (it seems)
DirPopularReplyData[] data = new DirPopularReplyData[count];
int i = 0;
foreach (Object o in dataArray)
{
Hashtable d = (Hashtable)o;
data[i] = new DirPopularReplyData();
data[i].parcelID = new UUID(d["parcel_id"].ToString());
data[i].name = d["name"].ToString();
data[i].dwell = Convert.ToSingle(d["dwell"]);
i++;
if (i >= count)
break;
}
remoteClient.SendDirPopularReply(queryID, data);
*/
}
public void DirLandQuery(IClientAPI remoteClient, UUID queryID, uint queryFlags, uint searchType, int price, int area,
int queryStart)
{
//m_log.DebugFormat("[LAND SEARCH]: In Land Search, queryFlag = " + queryFlags.ToString("X"));
string query = String.Empty;
int count = MAX_RESULTS + 1; // +1 so that the viewer knows to enable the NEXT button (it seems)
int queryEnd = queryStart + count - 1; // 0-based
int i = 0;
string sqlTerms = String.Empty;
if ((queryFlags & ((uint)DirFindFlags.NameSort|(uint)DirFindFlags.AreaSort|(uint)DirFindFlags.PricesSort|(uint)DirFindFlags.PerMeterSort)) == 0)
{
// No sort options specified. Substitute price per meter sort for Land Sales.
queryFlags |= (uint)DirFindFlags.PerMeterSort;
queryFlags |= (uint)DirFindFlags.SortAsc;
}
bool checkPriceFlag = Convert.ToBoolean(queryFlags & (uint)DirFindFlags.LimitByPrice);
bool checkAreaFlag = Convert.ToBoolean(queryFlags & (uint)DirFindFlags.LimitByArea);
bool checkPGFlag = Convert.ToBoolean(queryFlags & (uint)DirFindFlags.IncludePG);
bool checkMatureFlag = Convert.ToBoolean(queryFlags & (uint)DirFindFlags.IncludeMature);
bool checkAdultFlag = Convert.ToBoolean(queryFlags & (uint)DirFindFlags.IncludeAdult);
//sqlTerms = "select parcelUUID, parcelname, area, saleprice from parcelsales";
sqlTerms = "select land.UUID, land.RegionUUID, land.Name, land.Area, land.SalePrice, regionsettings.maturity from land LEFT JOIN regionsettings ON land.RegionUUID=regionsettings.regionUUID";
// Limit "Land Sales" returns to parcels for sale.
sqlTerms += " where (LandFlags & " + ((int)ParcelFlags.ForSale).ToString() + ")";
// Limit "Land Sales" returns to parcels visible in search.
sqlTerms += " and (LandFlags & " + ((int)ParcelFlags.ShowDirectory).ToString() + ")";
if (!(checkPGFlag || checkMatureFlag || checkAdultFlag))
{
// nothing to search for
remoteClient.SendAgentAlertMessage("You must specify a search with at least one maturity level checked.", false);
remoteClient.SendDirLandReply(queryID, new DirLandReplyData[1]);
return;
}
if (searchType == 2)
{
remoteClient.SendAgentAlertMessage("Auctions not available.", false);
remoteClient.SendDirLandReply(queryID, new DirLandReplyData[1]);
return;
}
/*else if (searchType == 8)
{
sqlTerms += " AND parentestate='1' ";
}
else if (searchType == 16)
{
sqlTerms += " AND parentestate>'1' ";
}*/
int maturities = 0;
sqlTerms += " and (";
if (checkPGFlag)
{
sqlTerms += "regionsettings.maturity='0'";
maturities++;
}
if (checkMatureFlag)
{
if (maturities > 0) sqlTerms += " or ";
sqlTerms += "regionsettings.maturity='1'";
maturities++;
}
if (checkAdultFlag)
{
if (maturities > 0) sqlTerms += " or ";
sqlTerms += "regionsettings.maturity='2'";
maturities++;
}
sqlTerms += ")";
if (checkPriceFlag && (price > 0))
{
sqlTerms += " and (land.SalePrice<=" + Convert.ToString(price) + " AND land.SalePrice >= 1) ";
}
if (checkAreaFlag && (area > 0))
{
sqlTerms += " and land.Area>=" + Convert.ToString(area);
}
string order = ((queryFlags & (uint)DirFindFlags.SortAsc) != 0) ? "ASC" : "DESC";
string norder = ((queryFlags & (uint)DirFindFlags.SortAsc) == 0) ? "ASC" : "DESC";
if ((queryFlags & (uint)DirFindFlags.NameSort) != 0)
{
sqlTerms += " order by land.Name " + order;
}
else if ((queryFlags & (uint)DirFindFlags.PerMeterSort) != 0)
{
sqlTerms += " and land.Area > 0 order by land.SalePrice / land.Area " + order + ", land.SalePrice " + order + ", land.Area " + norder + ", land.Name ASC";
}
else if ((queryFlags & (uint)DirFindFlags.PricesSort) != 0)
{
sqlTerms += " order by land.SalePrice " + order + ", land.Area " + norder + ", land.Name ASC";
}
else if ((queryFlags & (uint)DirFindFlags.AreaSort) != 0)
{
sqlTerms += " order by land.Area " + order + ", land.SalePrice ASC, land.Name ASC";
}
Dictionary<string, object> parms = new Dictionary<string, object>();
query = sqlTerms; // nothing extra to add anymore
// m_log.Debug("Query is: " + query);
List<Dictionary<string, string>> results;
using (ISimpleDB db = _connFactory.GetConnection())
{
List<UUID> regionsToInclude = UpdateRegionsList(db);
results = DoLandQueryAndCombine(remoteClient, db, query, parms, queryFlags, queryStart, queryEnd, regionsToInclude);
}
if (results.Count < count)
count = results.Count; // no Next button
if (count < 1)
count = 1; // a single empty DirLandReplyData will just cause the viewer to report no results found.
DirLandReplyData[] data = new DirLandReplyData[count];
foreach (Dictionary<string, string> row in results)
{
bool forSale = true;
bool auction = false;
data[i] = new DirLandReplyData();
data[i].parcelID = new UUID(row["UUID"]);
data[i].name = row["Name"].ToString();
data[i].auction = auction;
data[i].forSale = forSale;
data[i].salePrice = Convert.ToInt32(row["SalePrice"]);
data[i].actualArea = Convert.ToInt32(row["Area"]);
i++;
if (i >= count)
break;
}
remoteClient.SendDirLandReply(queryID, data);
}
public void DirFindQuery(IClientAPI remoteClient, UUID queryID,
string queryText, uint queryFlags, int queryStart)
{
if ((queryFlags & 1) != 0)
{
DirPeopleQuery(remoteClient, queryID, queryText, queryFlags,
queryStart);
return;
}
else if ((queryFlags & 32) != 0)
{
DirEventsQuery(remoteClient, queryID, queryText, queryFlags,
queryStart);
return;
}
}
public void DirPeopleQuery(IClientAPI remoteClient, UUID queryID,
string queryText, uint queryFlags, int queryStart)
{
queryText = queryText.Trim(); // newer viewers sometimes append a space
List<AvatarPickerAvatar> AvatarResponses =
new List<AvatarPickerAvatar>();
AvatarResponses = m_Scenes[0].SceneGridService.
GenerateAgentPickerRequestResponse(queryID, queryText);
DirPeopleReplyData[] data =
new DirPeopleReplyData[AvatarResponses.Count];
int i = 0;
foreach (AvatarPickerAvatar item in AvatarResponses)
{
data[i] = new DirPeopleReplyData();
data[i].agentID = item.AvatarID;
data[i].firstName = item.firstName;
data[i].lastName = item.lastName;
data[i].group = String.Empty;
data[i].online = false;
data[i].reputation = 0;
i++;
}
remoteClient.SendDirPeopleReply(queryID, data);
}
public void DirEventsQuery(IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, int queryStart)
{
// Flags are going to be 0 or 32 for Mature
// We also know text comes in 3 segments X|Y|Text where X is the day difference from
// the current day, Y is the category to search, Text is the user input for search string
// so let's 'split up the queryText to get our values we need first off
string eventTime = String.Empty;
string eventCategory = String.Empty;
string userText = String.Empty;
queryText = queryText.Trim(); // newer viewers sometimes append a space
string[] querySplode = queryText.Split(new Char[] { '|' });
if (querySplode.Length > 0)
eventTime = querySplode[0];
if (querySplode.Length > 1)
eventCategory = querySplode[1];
if (querySplode.Length > 0)
{
userText = querySplode[2];
userText = userText.Trim(); // newer viewers sometimes append a space
}
// Ok we have values, now we need to do something with all this lovely information
string query = String.Empty;
string searchStart = Convert.ToString(queryStart);
int count = 100;
DirEventsReplyData[] data = new DirEventsReplyData[count];
string searchEnd = Convert.ToString(queryStart + count);
int i = 0;
int unixEventUpcomingEndDateToCheck = 0;
int eventTimeAmt = 0;
int unixEventDateToCheckMidnight = 0;
int unixEventEndDateToCheckMidnight = 0;
string sqlAddTerms = String.Empty;
DateTime saveNow = DateTime.Now;
int startDateCheck;
// Quick catch to see if the eventTime is set to "u" for In Progress & Upcoming Radio button
if (eventTime == "u")
{
DateTime eventUpcomingEndDateToCheck = saveNow.AddDays(+7);
DateTime eventUpcomingEndDateToCheckMidnight = new DateTime(eventUpcomingEndDateToCheck.Year, eventUpcomingEndDateToCheck.Month, eventUpcomingEndDateToCheck.Day);
unixEventUpcomingEndDateToCheck = Util.ToUnixTime(eventUpcomingEndDateToCheckMidnight);
// for "in progress" events, show everything that has started within the last three hours (arbitrary)
startDateCheck = Util.ToUnixTime(saveNow.AddHours(-3.0));
sqlAddTerms = " where (dateUTC>=?startDateCheck AND dateUTC<=?unixEventUpcomingEndDateToCheck)";
}
else
{
// we need the current date, in order to subtract/add the days to view, or see the week upcoming.
// this will probably be some really ugly code :)
startDateCheck = Util.ToUnixTime(saveNow);
eventTimeAmt = Convert.ToInt16(eventTime);
DateTime eventDateToCheck = saveNow.AddDays(Convert.ToInt16(eventTime));
DateTime eventEndDateToCheck = new DateTime();
if (eventTime == "0")
{
eventEndDateToCheck = saveNow.AddDays(+2);
}
else
{
eventEndDateToCheck = saveNow.AddDays(eventTimeAmt + 1);
}
// now truncate the information so we get the midnight value (and yes David, I'm sure there's an
// easier way to do this, but this will work for now :) )
DateTime eventDateToCheckMidnight = new DateTime(eventDateToCheck.Year, eventDateToCheck.Month, eventDateToCheck.Day);
DateTime eventEndDateToCheckMidnight = new DateTime(eventEndDateToCheck.Year, eventEndDateToCheck.Month, eventEndDateToCheck.Day);
// this is the start unix timestamp to look for, we still need the end which is the next day, plus
// we need the week end unix timestamp for the In Progress & upcoming radio button
unixEventDateToCheckMidnight = Util.ToUnixTime(eventDateToCheckMidnight);
unixEventEndDateToCheckMidnight = Util.ToUnixTime(eventEndDateToCheckMidnight);
sqlAddTerms = " where (dateUTC>=?unixEventDateToCheck AND dateUTC<=?unixEventEndDateToCheckMidnight)";
}
if ((queryFlags & ((uint)DirFindFlags.IncludeAdult|(uint)DirFindFlags.IncludeAdult|(uint)DirFindFlags.IncludeAdult)) == 0)
{
// don't just give them an empty list...
remoteClient.SendAlertMessage("You must included at least one maturity rating.");
remoteClient.SendDirEventsReply(queryID, data);
return;
}
// Event DB storage does not currently support adult events, so if someone asks for adult, search mature for now.
if ((queryFlags & (uint)DirFindFlags.IncludeAdult) != 0)
queryFlags |= (uint)DirFindFlags.IncludeMature;
if ((queryFlags & (uint)DirFindFlags.IncludeMature) != 0)
{
// they included mature and possibly others
if ((queryFlags & (uint)DirFindFlags.IncludePG) == 0)
sqlAddTerms += " AND mature='true'"; // exclude PG
}
if ((queryFlags & (uint)DirFindFlags.IncludePG) != 0)
{
// they included PG and possibly others
if ((queryFlags & (uint)DirFindFlags.IncludeMature) == 0)
sqlAddTerms += " AND mature='false'"; // exclude mature
}
if (eventCategory != "0")
{
sqlAddTerms += " AND category=?category";
}
if(!String.IsNullOrEmpty(userText))
{
sqlAddTerms += " AND (description LIKE ?userText OR name LIKE ?userText)";
}
// Events results should come back sorted by date
sqlAddTerms += " order by dateUTC ASC";
query = "select owneruuid, name, eventid, dateUTC, eventflags from events" + sqlAddTerms + " limit " + searchStart + ", " + searchEnd + String.Empty;
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?startDateCheck", Convert.ToString(startDateCheck));
parms.Add("?unixEventUpcomingEndDateToCheck", Convert.ToString(unixEventUpcomingEndDateToCheck));
parms.Add("?unixEventDateToCheck", Convert.ToString(unixEventDateToCheckMidnight));
parms.Add("?unixEventEndDateToCheckMidnight", Convert.ToString(unixEventEndDateToCheckMidnight));
parms.Add("?category", eventCategory);
parms.Add("?userText", "%" + Convert.ToString(userText) + "%");
using (ISimpleDB db = _connFactory.GetConnection())
{
List<Dictionary<string, string>> results = db.QueryWithResults(query, parms);
foreach (Dictionary<string, string> row in results)
{
data[i] = new DirEventsReplyData();
data[i].ownerID = new UUID(row["owneruuid"].ToString());
data[i].name = row["name"].ToString();
data[i].eventID = Convert.ToUInt32(row["eventid"]);
// need to convert the unix timestamp we get into legible date for viewer
DateTime localViewerEventTime = Util.UnixToLocalDateTime(Convert.ToInt32(row["dateUTC"]));
string newSendingDate = String.Format("{0:MM/dd hh:mm tt}", localViewerEventTime);
data[i].date = newSendingDate;
data[i].unixTime = Convert.ToUInt32(row["dateUTC"]);
data[i].eventFlags = Convert.ToUInt32(row["eventflags"]);
i++;
if (i >= count)
break;
}
}
remoteClient.SendDirEventsReply(queryID, data);
}
public void DirClassifiedQuery(IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, uint category,
int queryStart)
{
// This is pretty straightforward here, get the input, set up the query, run it through, send back to viewer.
string query = String.Empty;
string sqlAddTerms = String.Empty;
string userText = queryText.Trim(); // newer viewers sometimes append a space
string searchStart = Convert.ToString(queryStart);
int count = MAX_RESULTS + 1; // +1 so that the viewer knows to enable the NEXT button (it seems)
string searchEnd = Convert.ToString(queryStart + count);
int i = 0;
// There is a slight issue with the parcel data not coming from land first so the
// parcel information is never displayed correctly within in the classified ad.
//stop blank queries here before they explode mysql
if (String.IsNullOrEmpty(userText))
{
remoteClient.SendDirClassifiedReply(queryID, new DirClassifiedReplyData[0]);
return;
}
if (queryFlags == 0)
{
sqlAddTerms = " AND (classifiedflags='2' OR classifiedflags='34') ";
}
if (category != 0)
{
sqlAddTerms = " AND category=?category ";
}
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?matureFlag", queryFlags);
parms.Add("?category", category);
parms.Add("?userText", userText);
// Ok a test cause the query pulls fine direct in MySQL, but not from here, so WTF?!
//query = "select classifieduuid, name, classifiedflags, creationdate, expirationdate, priceforlisting from classifieds " +
// "where name LIKE '" + userText + "' OR description LIKE '" + userText + "' " + sqlAddTerms;
query = "select classifieduuid, name, classifiedflags, creationdate, expirationdate, priceforlisting from classifieds " +
"where (description REGEXP ?userText OR name REGEXP ?userText) " +sqlAddTerms + " order by priceforlisting DESC limit " + searchStart + ", " + searchEnd + String.Empty;
using (ISimpleDB db = _connFactory.GetConnection())
{
List<Dictionary<string, string>> results = db.QueryWithResults(query, parms);
count = results.Count;
DirClassifiedReplyData[] data = new DirClassifiedReplyData[count];
foreach (Dictionary<string, string> row in results)
{
data[i] = new DirClassifiedReplyData();
data[i].classifiedID = new UUID(row["classifieduuid"].ToString());
data[i].name = row["name"].ToString();
data[i].classifiedFlags = Convert.ToByte(row["classifiedflags"]);
data[i].creationDate = Convert.ToUInt32(row["creationdate"]);
data[i].expirationDate = Convert.ToUInt32(row["expirationdate"]);
data[i].price = Convert.ToInt32(row["priceforlisting"]);
i++;
}
remoteClient.SendDirClassifiedReply(queryID, data);
}
}
public void EventInfoRequest(IClientAPI remoteClient, uint queryEventID)
{
EventData data = new EventData();
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?eventID", queryEventID);
string query = "select * from events where eventid=?eventID";
using (ISimpleDB db = _connFactory.GetConnection())
{
List<Dictionary<string, string>> results = db.QueryWithResults(query, parms);
foreach (Dictionary<string, string> row in results)
{
data.eventID = Convert.ToUInt32(row["eventid"]);
data.creator = row["creatoruuid"].ToString();
data.name = row["name"].ToString();
// need to convert this from the integer it is to the
// real string value so it shows correctly
if (row["category"] == "18")
data.category = "Discussion";
if (row["category"] == "19")
data.category = "Sports";
if (row["category"] == "20")
data.category = "Live Music";
if (row["category"] == "22")
data.category = "Commercial";
if (row["category"] == "23")
data.category = "Nightlife/Entertainment";
if (row["category"] == "24")
data.category = "Games/Contests";
if (row["category"] == "25")
data.category = "Pageants";
if (row["category"] == "26")
data.category = "Education";
if (row["category"] == "27")
data.category = "Arts and Culture";
if (row["category"] == "28")
data.category = "Charity/Support Groups";
if (row["category"] == "29")
data.category = "Miscellaneous";
data.description = row["description"].ToString();
// do something here with date to format it correctly for what
// the viewer needs!
//data.date = row["date"].ToString();
// need to convert the unix timestamp we get into legible date for viewer
DateTime localViewerEventTime = Util.UnixToLocalDateTime(Convert.ToInt32(row["dateUTC"]));
string newSendingDate = String.Format("{0:yyyy-MM-dd HH:MM:ss}", localViewerEventTime);
data.date = newSendingDate;
data.dateUTC = Convert.ToUInt32(row["dateUTC"]);
data.duration = Convert.ToUInt32(row["duration"]);
data.cover = Convert.ToUInt32(row["covercharge"]);
data.amount = Convert.ToUInt32(row["coveramount"]);
data.simName = row["simname"].ToString();
Vector3.TryParse(row["globalPos"].ToString(), out data.globalPos);
data.eventFlags = Convert.ToUInt32(row["eventflags"]);
}
}
remoteClient.SendEventInfoReply(data);
}
public void ClassifiedInfoRequest(UUID queryClassifiedID, IClientAPI remoteClient)
{
// okies this is pretty simple straightforward stuff as well... pull the info from the
// db based on the Classified ID we got back from viewer from the original query above
// and send it back.
//ClassifiedData data = new ClassifiedData();
string query = "select * from classifieds where classifieduuid=?classifiedID";
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?classifiedID", queryClassifiedID);
Vector3 globalPos = new Vector3();
using (ISimpleDB db = _connFactory.GetConnection())
{
List<Dictionary<string, string>> results = db.QueryWithResults(query, parms);
foreach (Dictionary<string, string> row in results)
{
Vector3.TryParse(row["posglobal"].ToString(), out globalPos);
//remoteClient.SendClassifiedInfoReply(data);
remoteClient.SendClassifiedInfoReply(
new UUID(row["classifieduuid"].ToString()),
new UUID(row["creatoruuid"].ToString()),
Convert.ToUInt32(row["creationdate"]),
Convert.ToUInt32(row["expirationdate"]),
Convert.ToUInt32(row["category"]),
row["name"].ToString(),
row["description"].ToString(),
new UUID(row["parceluuid"].ToString()),
Convert.ToUInt32(row["parentestate"]),
new UUID(row["snapshotuuid"].ToString()),
row["simname"].ToString(),
globalPos,
row["parcelname"].ToString(),
Convert.ToByte(row["classifiedflags"]),
Convert.ToInt32(row["priceforlisting"]));
}
}
}
}
}
| |
// 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.DirectoryServices.Protocols
{
using System;
using System.Collections;
using System.IO;
using System.Diagnostics;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Specialized;
using System.Security.Permissions;
public abstract class DirectoryRequest : DirectoryOperation
{
internal DirectoryControlCollection directoryControlCollection = null;
internal DirectoryRequest()
{
directoryControlCollection = new DirectoryControlCollection();
}
public string RequestId
{
get
{
return directoryRequestID;
}
set
{
directoryRequestID = value;
}
}
public DirectoryControlCollection Controls
{
get
{
return directoryControlCollection;
}
}
}
public class DeleteRequest : DirectoryRequest
{
//
// Public
//
public DeleteRequest() { }
public DeleteRequest(string distinguishedName)
{
_dn = distinguishedName;
}
// Member properties
public string DistinguishedName
{
get
{
return _dn;
}
set
{
_dn = value;
}
}
//
// Private/protected
//
private string _dn;
}
public class AddRequest : DirectoryRequest
{
//
// Public
//
public AddRequest()
{
_attributeList = new DirectoryAttributeCollection();
}
public AddRequest(string distinguishedName, params DirectoryAttribute[] attributes) : this()
{
// Store off the distinguished name
_dn = distinguishedName;
if (attributes != null)
{
for (int i = 0; i < attributes.Length; i++)
{
_attributeList.Add(attributes[i]);
}
}
}
public AddRequest(string distinguishedName, string objectClass) : this()
{
// parameter validation
if (objectClass == null)
throw new ArgumentNullException("objectClass");
// Store off the distinguished name
_dn = distinguishedName;
// Store off the objectClass in an object class attribute
DirectoryAttribute objClassAttr = new DirectoryAttribute();
objClassAttr.Name = "objectClass";
objClassAttr.Add(objectClass);
_attributeList.Add(objClassAttr);
}
// Properties
public string DistinguishedName
{
get
{
return _dn;
}
set
{
_dn = value;
}
}
public DirectoryAttributeCollection Attributes
{
get
{
return _attributeList;
}
}
//
// Private/protected
//
private string _dn;
private DirectoryAttributeCollection _attributeList;
}
public class ModifyRequest : DirectoryRequest
{
//
// Public
//
public ModifyRequest()
{
_attributeModificationList = new DirectoryAttributeModificationCollection();
}
public ModifyRequest(string distinguishedName, params DirectoryAttributeModification[] modifications) : this()
{
// Store off the distinguished name
_dn = distinguishedName;
// Store off the initial list of modifications
_attributeModificationList.AddRange(modifications);
}
public ModifyRequest(string distinguishedName, DirectoryAttributeOperation operation, string attributeName, params object[] values) : this()
{
// Store off the distinguished name
_dn = distinguishedName;
// validate the attributeName
if (attributeName == null)
throw new ArgumentNullException("attributeName");
DirectoryAttributeModification mod = new DirectoryAttributeModification();
mod.Operation = operation;
mod.Name = attributeName;
if (values != null)
{
for (int i = 0; i < values.Length; i++)
mod.Add(values[i]);
}
_attributeModificationList.Add(mod);
}
// Properties
public string DistinguishedName
{
get
{
return _dn;
}
set
{
_dn = value;
}
}
public DirectoryAttributeModificationCollection Modifications
{
get
{
return _attributeModificationList;
}
}
//
// Private/protected
//
private string _dn;
private DirectoryAttributeModificationCollection _attributeModificationList;
}
public class CompareRequest : DirectoryRequest
{
//
// Public
//
public CompareRequest() { }
public CompareRequest(string distinguishedName, string attributeName, string value)
{
CompareRequestHelper(distinguishedName, attributeName, value);
}
public CompareRequest(string distinguishedName, string attributeName, byte[] value)
{
CompareRequestHelper(distinguishedName, attributeName, value);
}
public CompareRequest(string distinguishedName, string attributeName, Uri value)
{
CompareRequestHelper(distinguishedName, attributeName, value);
}
public CompareRequest(string distinguishedName, DirectoryAttribute assertion)
{
if (assertion == null)
throw new ArgumentNullException("assertion");
if (assertion.Count != 1)
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.WrongNumValuesCompare));
CompareRequestHelper(distinguishedName, assertion.Name, assertion[0]);
}
private void CompareRequestHelper(string distinguishedName, string attributeName, object value)
{
// parameter validation
if (attributeName == null)
throw new ArgumentNullException("attributeName");
if (value == null)
throw new ArgumentNullException("value");
// store off the DN
_dn = distinguishedName;
// store off the attribute name and value
_attribute.Name = attributeName;
_attribute.Add(value);
}
// Properties
public string DistinguishedName
{
get
{
return _dn;
}
set
{
_dn = value;
}
}
public DirectoryAttribute Assertion
{
get
{
return _attribute;
}
}
//
// Private/protected
//
private string _dn;
private DirectoryAttribute _attribute = new DirectoryAttribute();
}
public class ModifyDNRequest : DirectoryRequest
{
//
// Public
//
public ModifyDNRequest() { }
public ModifyDNRequest(string distinguishedName,
string newParentDistinguishedName,
string newName)
{
// store off the DN
_dn = distinguishedName;
_newSuperior = newParentDistinguishedName;
_newRDN = newName;
}
// Properties
public string DistinguishedName
{
get
{
return _dn;
}
set
{
_dn = value;
}
}
public string NewParentDistinguishedName
{
get
{
return _newSuperior;
}
set
{
_newSuperior = value;
}
}
public string NewName
{
get
{
return _newRDN;
}
set
{
_newRDN = value;
}
}
public bool DeleteOldRdn
{
get
{
return _deleteOldRDN;
}
set
{
_deleteOldRDN = value;
}
}
//
// Private/protected
//
private string _dn;
private string _newSuperior;
private string _newRDN;
private bool _deleteOldRDN = true;
}
/// <summary>
/// The representation of a <extendedRequest>
/// </summary>
public class ExtendedRequest : DirectoryRequest
{
//
// Public
//
public ExtendedRequest() { }
public ExtendedRequest(string requestName)
{
_requestName = requestName;
}
public ExtendedRequest(string requestName, byte[] requestValue) : this(requestName)
{
_requestValue = requestValue;
}
// Properties
public string RequestName
{
get
{
return _requestName;
}
set
{
_requestName = value;
}
}
public byte[] RequestValue
{
get
{
if (_requestValue == null)
return new byte[0];
else
{
byte[] tempValue = new byte[_requestValue.Length];
for (int i = 0; i < _requestValue.Length; i++)
tempValue[i] = _requestValue[i];
return tempValue;
}
}
set
{
_requestValue = value;
}
}
//
// Private/protected
//
private string _requestName;
private byte[] _requestValue = null;
}
public class SearchRequest : DirectoryRequest
{
//
// Public
//
public SearchRequest()
{
_directoryAttributes = new StringCollection();
}
public SearchRequest(string distinguishedName,
string ldapFilter,
SearchScope searchScope,
params string[] attributeList) : this()
{
_dn = distinguishedName;
if (attributeList != null)
{
for (int i = 0; i < attributeList.Length; i++)
_directoryAttributes.Add(attributeList[i]);
}
Scope = searchScope;
Filter = ldapFilter;
}
// Properties
public string DistinguishedName
{
get
{
return _dn;
}
set
{
_dn = value;
}
}
public StringCollection Attributes
{
get
{
return _directoryAttributes;
}
}
public object Filter
{
get
{
return _directoryFilter;
}
set
{
// do we need to validate the filter here?
if ((value is string) || (value == null))
_directoryFilter = value;
else
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.ValidFilterType), "value");
}
}
public SearchScope Scope
{
get
{
return _directoryScope;
}
set
{
if (value < SearchScope.Base || value > SearchScope.Subtree)
throw new InvalidEnumArgumentException("value", (int)value, typeof(SearchScope));
_directoryScope = value;
}
}
public DereferenceAlias Aliases
{
get
{
return _directoryRefAlias;
}
set
{
if (value < DereferenceAlias.Never || value > DereferenceAlias.Always)
throw new InvalidEnumArgumentException("value", (int)value, typeof(DereferenceAlias));
_directoryRefAlias = value;
}
}
public int SizeLimit
{
get
{
return _directorySizeLimit;
}
set
{
if (value < 0)
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.NoNegativeSizeLimit), "value");
}
_directorySizeLimit = value;
}
}
public TimeSpan TimeLimit
{
get
{
return _directoryTimeLimit;
}
set
{
if (value < TimeSpan.Zero)
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.NoNegativeTime), "value");
}
// prevent integer overflow
if (value.TotalSeconds > Int32.MaxValue)
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.TimespanExceedMax), "value");
_directoryTimeLimit = value;
}
}
public bool TypesOnly
{
get
{
return _directoryTypesOnly;
}
set
{
_directoryTypesOnly = value;
}
}
//
// Private/protected
//
private string _dn = null;
private StringCollection _directoryAttributes = new StringCollection();
private object _directoryFilter = null;
private SearchScope _directoryScope = SearchScope.Subtree;
private DereferenceAlias _directoryRefAlias = DereferenceAlias.Never;
private int _directorySizeLimit = 0;
private TimeSpan _directoryTimeLimit = new TimeSpan(0);
private bool _directoryTypesOnly = false;
}
}
namespace System.DirectoryServices.Protocols
{
using System;
public class DsmlAuthRequest : DirectoryRequest
{
private string _directoryPrincipal = "";
public DsmlAuthRequest() { }
public DsmlAuthRequest(string principal)
{
_directoryPrincipal = principal;
}
public string Principal
{
get
{
return _directoryPrincipal;
}
set
{
_directoryPrincipal = value;
}
}
}
}
| |
using System;
using System.Threading;
using System.Windows.Forms;
using System.Collections;
using DAQ.Environment;
using Data;
using Data.Scans;
using ScanMaster.Acquire.Plugin;
namespace ScanMaster.Acquire
{
public delegate void DataEventHandler(object sender, DataEventArgs e);
public delegate void ScanFinishedEventHandler(object sender, EventArgs e);
/// <summary>
/// This is a brave attempt at making a generic backend component. The idea is that
/// it only knows how to generically scan and switch. Plugin classes provide all the
/// specific functionality, like scanning and analog output, gathering shot data
/// from the board, generating patterns, controlling the laser. The aim is that me
/// and Mike can use exactly the same code, with our own custom plugins. I'm not sure
/// whether it will work or not.
/// </summary>
public class Acquisitor
{
public event DataEventHandler Data;
public event ScanFinishedEventHandler ScanFinished;
public object AcquisitorMonitorLock = new Object();
private AcquisitorConfiguration config;
public AcquisitorConfiguration Configuration
{
set { config = value; }
get { return config; }
}
private Thread acquireThread;
private int numberOfScans = 0;
enum AcquisitorState {stopped, running, stopping};
private AcquisitorState backendState = AcquisitorState.stopped;
public void AcquireStart(int numberOfScans)
{
this.numberOfScans = numberOfScans;
acquireThread = new Thread(new ThreadStart(this.Acquire));
acquireThread.Name = "ScanMaster Acquisitor";
acquireThread.Priority = ThreadPriority.Normal;
backendState = AcquisitorState.running;
acquireThread.Start();
}
public void AcquireStop()
{
lock(this)
{
backendState = AcquisitorState.stopping;
}
}
private void Acquire()
{
try
{
// lock a monitor onto the acquisitor, to synchronise with the controller
// when acquiring a set number of scans - the monitor is released in
// AcquisitionFinishing()
Monitor.Enter(AcquisitorMonitorLock);
// initialise all of the plugins
config.outputPlugin.AcquisitionStarting();
config.pgPlugin.AcquisitionStarting();
config.shotGathererPlugin.AcquisitionStarting();
config.switchPlugin.AcquisitionStarting();
config.yagPlugin.AcquisitionStarting();
config.analogPlugin.AcquisitionStarting();
config.gpibPlugin.AcquisitionStarting();
for (int scanNumber = 0 ;; scanNumber++)
{
// prepare for the scan start
config.outputPlugin.ScanStarting();
config.pgPlugin.ScanStarting();
config.shotGathererPlugin.ScanStarting();
config.switchPlugin.ScanStarting();
config.yagPlugin.ScanStarting();
config.analogPlugin.ScanStarting();
config.gpibPlugin.ScanStarting();
for (int pointNumber = 0 ; pointNumber < (int)config.outputPlugin.Settings["pointsPerScan"] ; pointNumber++)
{
// calculate the new scan parameter and move the scan along
config.outputPlugin.ScanParameter = NextScanParameter(pointNumber, scanNumber);
// check for a change in the pg parameters
lock(this)
{
if (tweakFlag)
{
// now it's safe to update the pattern generator settings
// and ask the pg to reload
SettingsReflector sr = new SettingsReflector();
sr.SetField(config.pgPlugin,
latestTweak.parameter, latestTweak.newValue.ToString());
config.pgPlugin.ReloadPattern();
tweakFlag = false;
}
}
ScanPoint sp = new ScanPoint();
sp.ScanParameter = config.outputPlugin.ScanParameter;
for (int shotNum = 0; shotNum < (int)(config.outputPlugin.Settings["shotsPerPoint"]); shotNum++)
{
// Set the switch state
config.switchPlugin.State = true;
// wait for the data gatherer to finish
config.shotGathererPlugin.ArmAndWait();
// read out the data
sp.OnShots.Add(config.shotGathererPlugin.Shot);
if ((bool)config.switchPlugin.Settings["switchActive"])
{
config.switchPlugin.State = false;
config.shotGathererPlugin.ArmAndWait();
sp.OffShots.Add(config.shotGathererPlugin.Shot);
}
}
// sample the analog channels and add them to the ScanPoint
config.analogPlugin.ArmAndWait();
sp.Analogs.AddRange(config.analogPlugin.Analogs);
// sample the gpib channels and add them to the ScanPoint
config.gpibPlugin.ArmAndWait();
sp.gpibval = config.gpibPlugin.GPIBval;
// send up the data bundle
DataEventArgs evArgs = new DataEventArgs();
evArgs.point = sp;
OnData(evArgs);
// check for exit
if (CheckIfStopping())
{
AcquisitionFinishing(config);
return;
}
}
// prepare for the start of the next scan
OnScanFinished();
config.pgPlugin.ScanFinished();
config.yagPlugin.ScanFinished();
config.outputPlugin.ScanFinished();
config.shotGathererPlugin.ScanFinished();
config.switchPlugin.ScanFinished();
config.analogPlugin.ScanFinished();
config.gpibPlugin.ScanFinished();
// I think that this pause will workaround an annoying threading bug
// I should probably be less cheezy and put a lock in, but I'm not really
// sure that I know what the bug is as it's intermittent (and rare).
Thread.Sleep(750);
// check if we are finished scanning
if (scanNumber + 1 == numberOfScans)
{
backendState = AcquisitorState.stopped;
// set the controller state to stopped
Controller.GetController().appState = Controller.AppState.stopped;
AcquisitionFinishing(config);
return;
}
}
}
catch (Exception e)
{
// last chance exception handler - this stops a rogue exception in the
// acquire loop from killing the whole program
Console.Error.Write(e.Message + e.StackTrace);
MessageBox.Show("Exception caught in acquire loop.\nTake care - the program " +
"is probably unstable.\n" + e.Message + "\n" + e.StackTrace, "Acquire error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
// Try and stop the pattern gracefully before the program dies
config.pgPlugin.AcquisitionFinished();
lock (this) backendState = AcquisitorState.stopped;
}
}
private void AcquisitionFinishing(AcquisitorConfiguration config)
{
config.pgPlugin.AcquisitionFinished();
config.shotGathererPlugin.AcquisitionFinished();
config.switchPlugin.AcquisitionFinished();
config.yagPlugin.AcquisitionFinished();
config.analogPlugin.AcquisitionFinished();
config.outputPlugin.AcquisitionFinished();
Monitor.Pulse(AcquisitorMonitorLock);
Monitor.Exit(AcquisitorMonitorLock);
}
private ArrayList scanValues;
private double NextScanParameter(int pointNumber, int scanNumber)
{
PluginSettings outputSettings = config.outputPlugin.Settings;
double scanParameter;
string mode = (string)outputSettings["scanMode"];
switch (mode)
{
case "up":
scanParameter = (double)outputSettings["start"] +
((double)outputSettings["end"] - (double)outputSettings["start"]) * (pointNumber + 0.5)
/ ((int)outputSettings["pointsPerScan"]);
break;
case "down":
scanParameter = (double)outputSettings["end"] +
((double)outputSettings["start"] - (double)outputSettings["end"]) * (pointNumber + 0.5)
/ ((int)outputSettings["pointsPerScan"]);
break;
case "updown":
if (scanNumber % 2 == 0)
{
scanParameter = (double)outputSettings["start"] +
((double)outputSettings["end"] - (double)outputSettings["start"]) * (pointNumber + 0.5)
/ ((int)outputSettings["pointsPerScan"]);
}
else
{
scanParameter = (double)outputSettings["end"] +
((double)outputSettings["start"] - (double)outputSettings["end"]) * (pointNumber + 0.5)
/ ((int)outputSettings["pointsPerScan"]);
}
break;
case "downup":
if (scanNumber % 2 != 0)
{
scanParameter = (double)outputSettings["start"] +
((double)outputSettings["end"] - (double)outputSettings["start"]) * (pointNumber + 0.5)
/ ((int)outputSettings["pointsPerScan"]);
}
else
{
scanParameter = (double)outputSettings["end"] +
((double)outputSettings["start"] - (double)outputSettings["end"]) * (pointNumber + 0.5)
/ ((int)outputSettings["pointsPerScan"]);
}
break;
case "random":
if (pointNumber == 0)
{
scanValues = new ArrayList();
for (int i = 0; i < (int)outputSettings["pointsPerScan"]; i++) // fill the array at the beginning of the scan
{
scanValues.Add((double)outputSettings["start"] +
((double)outputSettings["end"] - (double)outputSettings["start"]) * (i + 0.5)
/ ((int)outputSettings["pointsPerScan"]));
}
}
Random rnd = new Random();
int selectedIndex = rnd.Next(0, scanValues.Count);
scanParameter = (double)scanValues[selectedIndex];
scanValues.RemoveAt(selectedIndex);
break;
default: //scan up by default
scanParameter = (double)outputSettings["start"] +
((double)outputSettings["end"] - (double)outputSettings["start"]) * (pointNumber + 0.5)
/ ((int)outputSettings["pointsPerScan"]);
break;
}
return scanParameter;
}
private bool CheckIfStopping()
{
lock(this)
{
if (backendState == AcquisitorState.stopping)
{
backendState = AcquisitorState.stopped;
return true;
}
else return false;
}
}
bool tweakFlag = false;
TweakEventArgs latestTweak;
public void HandleTweak(object sender, TweakEventArgs e)
{
lock(this)
{
latestTweak = e;
tweakFlag = true;
}
}
protected virtual void OnData( DataEventArgs e )
{
if (Data != null) Data(this, e);
}
protected virtual void OnScanFinished()
{
if (ScanFinished != null) ScanFinished(this, new EventArgs());
}
}
/// <summary>
/// Instances of this class are used to send data to interested listeners.
/// </summary>
public class DataEventArgs : EventArgs
{
public ScanPoint point;
}
}
| |
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
namespace Alchemi.Updater
{
public enum UpdatePhases:int {Complete=0, InProgress=1, Scavenging=2, Downloading=3, Validating=4, Merging=5, Finalizing=6};
//**************************************************************
// AppManifest Class
// - This class is used for accessing and updating the application
// updater manifest. The Manifest stores information such as the
// current phase the update operation is in.
// - Xml serialization is used to persist the manifest.
//**************************************************************
[Serializable]
public class AppManifest
{
//Manifest File Path
[NonSerialized]
private string _FilePath;
public string FilePath
{ get { return _FilePath; } set { _FilePath = value; } }
// Resources
private ResourceFiles _Resources;
public ResourceFiles Resources
{ get { return _Resources; } set { _Resources = value; } }
//VersionInfo
private AppVersionInfo _VersionInfo;
public AppVersionInfo VersionInfo
{ get { return _VersionInfo; } set { _VersionInfo = value; } }
//State
private UpdateState _State;
public UpdateState State
{ get { return _State; } set { _State = value; } }
//**************************************************************
// AppState constructor
//**************************************************************
public AppManifest(string manifestFilePath)
{
FilePath = manifestFilePath;
Resources = new ResourceFiles();
State = new UpdateState();
VersionInfo = new AppVersionInfo();
}
//**************************************************************
// Load()
// This static method is the way to instantiate manifest objects
//**************************************************************
public static AppManifest Load(string manifestFilePath)
{
Stream stream = null;
try
{
if (!File.Exists(manifestFilePath))
return new AppManifest(manifestFilePath);
IFormatter formatter = new SoapFormatter();
stream = new FileStream(manifestFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
AppManifest Manifest = (AppManifest) formatter.Deserialize(stream);
Manifest.FilePath = manifestFilePath;
stream.Close();
return Manifest;
}
catch (Exception e)
{
if (stream != null)
stream.Close();
Debug.WriteLine("APPMANAGER: ERROR loading app manifest, creating a new manifest.");
Debug.WriteLine("APPMANAGER: " + e.ToString());
return new AppManifest(manifestFilePath);
}
}
//**************************************************************
// Update()
//**************************************************************
public void Update()
{
Stream stream = null;
try
{
IFormatter formatter = new SoapFormatter();
stream = new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, this);
stream.Close();
}
catch (Exception e)
{
if (stream != null)
stream.Close();
Debug.WriteLine("APPMANAGER: Error saving app manfiest.");
throw e;
}
}
}
//**************************************************************
// State
//**************************************************************
[Serializable]
public class UpdateState
{
private UpdatePhases _Phase = UpdatePhases.Complete;
public UpdatePhases Phase
{ get { return _Phase; } set { _Phase = value; } }
private bool _UpdateFailureEncoutered = false;
public bool UpdateFailureEncoutered
{ get { return _UpdateFailureEncoutered; } set { _UpdateFailureEncoutered = value; } }
private int _UpdateFailureCount = 0;
public int UpdateFailureCount
{ get { return _UpdateFailureCount; } set { _UpdateFailureCount = value; } }
private string _DownloadSource = "";
public string DownloadSource
{ get { return _DownloadSource; } set { _DownloadSource = value; } }
private string _DownloadDestination = "";
public string DownloadDestination
{ get { return _DownloadDestination; } set { _DownloadDestination = value; Debug.WriteLine("************ some set this value to Download destination-" + value) ; } }
private string _NewVersionDirectory = "";
private string[] _filesToDownload;
public string NewVersionDirectory
{ get { return _NewVersionDirectory; } set { _NewVersionDirectory = value; } }
//krishna added this property to avoid using HTTP DAV to copy directories. Just copying files now.
public string[] FilesToDownload
{
get { return _filesToDownload; }
set { _filesToDownload = value; }
}
}
//**************************************************************
// VersionInfo
//**************************************************************
[Serializable]
public class AppVersionInfo
{
private string _VersionManifestUrl = "";
public string VersionManifestUrl
{ get { return _VersionManifestUrl; } set { _VersionManifestUrl = value; } }
private string _VersionNumber = "";
public string VersionNumber
{ get { return _VersionNumber; } set { _VersionNumber = value; } }
private DateTime _VersionLastChangeTime = DateTime.Now;
public DateTime VersionLastChangeTime
{ get { return _VersionLastChangeTime; } set { _VersionLastChangeTime = value; } }
}
//**************************************************************
// ResourceFiles class
//**************************************************************
[Serializable]
public class ResourceFiles
{
public readonly SortedList ResourceList;
public ResourceFiles()
{
ResourceList = new SortedList();
}
//**************************************************************
// AddResource()
//**************************************************************
public void AddResource(Resource newResource)
{
Resource tempResource = (Resource)ResourceList[newResource.Name];
if (tempResource == null)
ResourceList.Add(newResource.Name,newResource);
}
//**************************************************************
// GetResource()
//**************************************************************
public Resource GetResource(string name)
{
return (Resource)ResourceList[name];
}
//**************************************************************
// ResourceExists()
//**************************************************************
public bool ResourceExists(string name)
{
Resource tempResource = (Resource)ResourceList[name];
if (tempResource == null)
return false;
else
return true;
}
}
//**************************************************************
// Resource Class()
//A resource is a file / assembly
//**************************************************************
[Serializable]
public class Resource
{
private string _Name;
public string Name
{ get { return _Name; } set { _Name = value; } }
private string _Url;
public string Url
{ get { return _Url; } set { _Url = value; } }
private string _FilePath;
public string FilePath
{ get { return _FilePath; } set { _FilePath = value; } }
private bool _IsFolder;
public bool IsFolder
{ get { return _IsFolder; } set { _IsFolder = value; } }
private DateTime _LastModified;
public DateTime LastModified
{ get { return _LastModified; } set { _LastModified = value; } }
private bool _AddedAtRuntime;
public bool AddedAtRuntime
{ get { return _AddedAtRuntime; } set { _AddedAtRuntime = value; } }
}
}
| |
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using Orleans.Streams;
using UnitTests.GrainInterfaces;
namespace UnitTests.Grains
{
internal class SampleConsumerObserver<T> : IAsyncObserver<T>
{
private readonly SampleStreaming_ConsumerGrain hostingGrain;
internal SampleConsumerObserver(SampleStreaming_ConsumerGrain hostingGrain)
{
this.hostingGrain = hostingGrain;
}
public Task OnNextAsync(T item, StreamSequenceToken token = null)
{
hostingGrain.logger.Info("OnNextAsync(item={0}, token={1})", item, token != null ? token.ToString() : "null");
hostingGrain.numConsumedItems++;
return Task.CompletedTask;
}
public Task OnCompletedAsync()
{
hostingGrain.logger.Info("OnCompletedAsync()");
return Task.CompletedTask;
}
public Task OnErrorAsync(Exception ex)
{
hostingGrain.logger.Info("OnErrorAsync({0})", ex);
return Task.CompletedTask;
}
}
public class SampleStreaming_ProducerGrain : Grain, ISampleStreaming_ProducerGrain
{
private IAsyncStream<int> producer;
private int numProducedItems;
private IDisposable producerTimer;
internal Logger logger;
internal readonly static string RequestContextKey = "RequestContextField";
internal readonly static string RequestContextValue = "JustAString";
public override Task OnActivateAsync()
{
logger = this.GetLogger("SampleStreaming_ProducerGrain " + base.IdentityString);
logger.Info("OnActivateAsync");
numProducedItems = 0;
return Task.CompletedTask;
}
public Task BecomeProducer(Guid streamId, string streamNamespace, string providerToUse)
{
logger.Info("BecomeProducer");
IStreamProvider streamProvider = base.GetStreamProvider(providerToUse);
producer = streamProvider.GetStream<int>(streamId, streamNamespace);
return Task.CompletedTask;
}
public Task StartPeriodicProducing()
{
logger.Info("StartPeriodicProducing");
producerTimer = base.RegisterTimer(TimerCallback, null, TimeSpan.Zero, TimeSpan.FromMilliseconds(10));
return Task.CompletedTask;
}
public Task StopPeriodicProducing()
{
logger.Info("StopPeriodicProducing");
producerTimer.Dispose();
producerTimer = null;
return Task.CompletedTask;
}
public Task<int> GetNumberProduced()
{
logger.Info("GetNumberProduced {0}", numProducedItems);
return Task.FromResult(numProducedItems);
}
public Task ClearNumberProduced()
{
numProducedItems = 0;
return Task.CompletedTask;
}
public Task Produce()
{
return Fire();
}
private Task TimerCallback(object state)
{
return producerTimer != null? Fire(): Task.CompletedTask;
}
private async Task Fire([CallerMemberName] string caller = null)
{
RequestContext.Set(RequestContextKey, RequestContextValue);
await producer.OnNextAsync(numProducedItems);
numProducedItems++;
logger.Info("{0} (item={1})", caller, numProducedItems);
}
public override Task OnDeactivateAsync()
{
logger.Info("OnDeactivateAsync");
return Task.CompletedTask;
}
}
public class SampleStreaming_ConsumerGrain : Grain, ISampleStreaming_ConsumerGrain
{
private IAsyncObservable<int> consumer;
internal int numConsumedItems;
internal Logger logger;
private IAsyncObserver<int> consumerObserver;
private StreamSubscriptionHandle<int> consumerHandle;
public override Task OnActivateAsync()
{
logger = this.GetLogger("SampleStreaming_ConsumerGrain " + base.IdentityString);
logger.Info("OnActivateAsync");
numConsumedItems = 0;
consumerHandle = null;
return Task.CompletedTask;
}
public async Task BecomeConsumer(Guid streamId, string streamNamespace, string providerToUse)
{
logger.Info("BecomeConsumer");
consumerObserver = new SampleConsumerObserver<int>(this);
IStreamProvider streamProvider = base.GetStreamProvider(providerToUse);
consumer = streamProvider.GetStream<int>(streamId, streamNamespace);
consumerHandle = await consumer.SubscribeAsync(consumerObserver);
}
public async Task StopConsuming()
{
logger.Info("StopConsuming");
if (consumerHandle != null)
{
await consumerHandle.UnsubscribeAsync();
consumerHandle = null;
}
}
public Task<int> GetNumberConsumed()
{
return Task.FromResult(numConsumedItems);
}
public override Task OnDeactivateAsync()
{
logger.Info("OnDeactivateAsync");
return Task.CompletedTask;
}
}
public class SampleStreaming_InlineConsumerGrain : Grain, ISampleStreaming_InlineConsumerGrain
{
private IAsyncObservable<int> consumer;
internal int numConsumedItems;
internal Logger logger;
private StreamSubscriptionHandle<int> consumerHandle;
public override Task OnActivateAsync()
{
logger = this.GetLogger( "SampleStreaming_InlineConsumerGrain " + base.IdentityString );
logger.Info( "OnActivateAsync" );
numConsumedItems = 0;
consumerHandle = null;
return Task.CompletedTask;
}
public async Task BecomeConsumer(Guid streamId, string streamNamespace, string providerToUse)
{
logger.Info( "BecomeConsumer" );
IStreamProvider streamProvider = base.GetStreamProvider( providerToUse );
consumer = streamProvider.GetStream<int>(streamId, streamNamespace);
consumerHandle = await consumer.SubscribeAsync( OnNextAsync, OnErrorAsync, OnCompletedAsync );
}
public async Task StopConsuming()
{
logger.Info( "StopConsuming" );
if ( consumerHandle != null )
{
await consumerHandle.UnsubscribeAsync();
//consumerHandle.Dispose();
consumerHandle = null;
}
}
public Task<int> GetNumberConsumed()
{
return Task.FromResult( numConsumedItems );
}
public Task OnNextAsync( int item, StreamSequenceToken token = null )
{
logger.Info( "OnNextAsync({0}{1})", item, token != null ? token.ToString() : "null" );
numConsumedItems++;
return Task.CompletedTask;
}
public Task OnCompletedAsync()
{
logger.Info( "OnCompletedAsync()" );
return Task.CompletedTask;
}
public Task OnErrorAsync( Exception ex )
{
logger.Info( "OnErrorAsync({0})", ex );
return Task.CompletedTask;
}
public override Task OnDeactivateAsync()
{
logger.Info("OnDeactivateAsync");
return Task.CompletedTask;
}
}
}
| |
using System.Collections.Generic;
using FluentAssertions.Equivalency;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json.Linq;
namespace FluentAssertions.Json
{
[TestClass]
// ReSharper disable InconsistentNaming
public class JTokenAssertionsSpecs
{
[TestMethod]
public void When_both_values_are_the_same_or_equal_Be_should_succeed()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var a = JToken.Parse("{\"id\":1}");
var b = JToken.Parse("{\"id\":1}");
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
a.Should().Be(a);
b.Should().Be(b);
a.Should().Be(b);
}
[TestMethod]
public void When_values_differ_NotBe_should_succeed()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var a = JToken.Parse("{\"id\":1}");
var b = JToken.Parse("{\"id\":2}");
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
a.Should().NotBeNull();
a.Should().NotBe(null);
a.Should().NotBe(b);
}
[TestMethod]
public void When_values_are_equal_or_equivalent_NotBe_should_fail()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var a = JToken.Parse("{\"id\":1}");
var b = JToken.Parse("{\"id\":1}");
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
a.Invoking(x => x.Should().NotBe(b))
.ShouldThrow<AssertFailedException>()
.WithMessage($"Expected JSON document not to be {_formatter.ToString(b)}.");
}
[TestMethod]
public void When_both_values_are_equal_BeEquivalentTo_should_succeed()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var testCases = new Dictionary<string, string>
{
{ "{friends:[{id:123,name:\"Corby Page\"},{id:456,name:\"Carter Page\"}]}", "{friends:[{name:\"Corby Page\",id:123},{id:456,name:\"Carter Page\"}]}" },
{ "{id:2,admin:true}", "{admin:true,id:2}" }
};
foreach (var testCase in testCases)
{
var actualJson = testCase.Key;
var expectedJson = testCase.Value;
var a = JToken.Parse(actualJson);
var b = JToken.Parse(expectedJson);
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
a.Should().BeEquivalentTo(b);
}
}
[TestMethod]
public void When_values_differ_NotBeEquivalentTo_should_succeed()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var testCases = new Dictionary<string, string>
{
{ "{id:1,admin:true}", "{id:1,admin:false}" }
};
foreach (var testCase in testCases)
{
var actualJson = testCase.Key;
var expectedJson = testCase.Value;
var a = JToken.Parse(actualJson);
var b = JToken.Parse(expectedJson);
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
a.Should().NotBeEquivalentTo(b);
}
}
[TestMethod]
public void When_values_differ_Be_should_fail()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var testCases = new Dictionary<string, string>
{
{ "{id:1}", "{id:2}" }
, { "{id:1,admin:true}", "{id:1,admin:false}" }
};
foreach (var testCase in testCases)
{
var actualJson = testCase.Key;
var expectedJson = testCase.Value;
var a = JToken.Parse(actualJson);
var b = JToken.Parse(expectedJson);
var expectedMessage =
$"Expected JSON document to be {_formatter.ToString(b)}, but found {_formatter.ToString(a)}.";
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
a.Should().Invoking(x => x.Be(b))
.ShouldThrow<AssertFailedException>()
.WithMessage(expectedMessage);
}
}
[TestMethod]
public void When_values_differ_BeEquivalentTo_should_fail()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var testCases = new Dictionary<string, string>
{
{ "{id:1,admin:true}", "{id:1,admin:false}" }
};
foreach (var testCase in testCases)
{
var actualJson = testCase.Key;
var expectedJson = testCase.Value;
var a = JToken.Parse(actualJson);
var b = JToken.Parse(expectedJson);
var expectedMessage = GetNotEquivalentMessage(a, b);
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
a.Should().Invoking(x => x.BeEquivalentTo(b))
.ShouldThrow<AssertFailedException>()
.WithMessage(expectedMessage);
}
}
[TestMethod]
public void Fail_with_descriptive_message_when_child_element_differs()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = JToken.Parse("{child:{subject:'foo'}}");
var expected = JToken.Parse("{child:{expected:'bar'}}");
var expectedMessage = GetNotEquivalentMessage(subject, expected, "we want to test the failure {0}", "message");
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
subject.Should().Invoking(x => x.BeEquivalentTo(expected, "we want to test the failure {0}", "message"))
.ShouldThrow<AssertFailedException>()
.WithMessage(expectedMessage);
}
[TestMethod]
public void When_jtoken_has_value_HaveValue_should_succeed()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = JToken.Parse("{ 'id':42}");
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
subject["id"].Should().HaveValue("42");
}
[TestMethod]
public void When_jtoken_not_has_value_HaveValue_should_fail()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = JToken.Parse("{ 'id':42}");
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
subject["id"].Should().Invoking(x => x.HaveValue("43", "because foo"))
.ShouldThrow<AssertFailedException>()
.WithMessage("Expected JSON property \"id\" to have value \"43\" because foo, but found \"42\".");
}
[TestMethod]
public void When_jtoken_has_element_HaveElement_should_succeed()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = JToken.Parse("{ 'id':42}");
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
subject.Should().HaveElement("id");
subject.Should().Invoking(x => x.HaveElement("name", "because foo"))
.ShouldThrow<AssertFailedException>()
.WithMessage($"Expected JSON document {_formatter.ToString(subject)} to have element \"name\" because foo, but no such element was found.");
}
[TestMethod]
public void When_jtoken_not_has_element_HaveElement_should_fail()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = JToken.Parse("{ 'id':42}");
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
subject.Should().Invoking(x => x.HaveElement("name", "because foo"))
.ShouldThrow<AssertFailedException>()
.WithMessage($"Expected JSON document {_formatter.ToString(subject)} to have element \"name\" because foo, but no such element was found.");
}
private static readonly JTokenFormatter _formatter = new JTokenFormatter();
private static string GetNotEquivalentMessage(JToken actual, JToken expected,
string reason = null, params object[] reasonArgs)
{
var diff = ObjectDiffPatch.GenerateDiff(actual, expected);
var key = diff.NewValues?.First ?? diff.OldValues?.First;
var because = string.Empty;
if (!string.IsNullOrWhiteSpace(reason))
because = " because " + string.Format(reason, reasonArgs);
var expectedMessage = $"Expected JSON document {_formatter.ToString(actual)}" +
$" to be equivalent to {_formatter.ToString(expected)}" +
$"{because}, but differs at {_formatter.ToString(key)}.";
return expectedMessage;
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using ESRI.ArcGIS.Schematic;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.esriSystem;
namespace DigitTool
{
/// <summary>
/// Designer class of the dockable window add-in. It contains user interfaces that
/// make up the dockable window.
/// </summary>
public partial class DigitDockableWindow : UserControl
{
private DigitTool m_digitCommand;
private XmlDocument m_dom = null;
private bool m_loading = true;
private bool m_clickPanel = false;
private long m_curfrmWidth;
private System.Windows.Forms.SplitterPanel m_Panel1;
private System.Windows.Forms.SplitterPanel m_Panel2;
private System.Windows.Forms.SplitterPanel m_curPanel;
private System.Drawing.Color m_MandatoryColor = System.Drawing.Color.White;
private ISchematicLayer m_schematicLayer;
private ISchematicFeature m_schematicFeature1 = null;
private ISchematicFeature m_schematicFeature2 = null;
private bool m_createNode = true; //update when click on panel and on new
private bool m_isClosed = false;
private ESRI.ArcGIS.Framework.IApplication m_app;
//For button OK to retrieve the coordinate of the digit feature
private int m_x;
private int m_y;
private XmlElement m_curLink = null;
private XmlElement m_curNode = null;
private XmlNodeList m_relations = null;
private ISchematicDataset m_schDataset = null;
private ISchematicElementClassContainer m_schEltClassCont = null;
private ISchematicElementClass m_schEltClass = null;
private ISchematicInMemoryDiagram m_SchematicInMemoryDiagram = null;
private bool m_autoClear = false;
public DigitDockableWindow(object hook)
{
InitializeComponent();
this.Hook = hook;
}
/// <summary>
/// Host object of the dockable window
/// </summary>
private object Hook
{
get;
set;
}
/// <summary>
/// Implementation class of the dockable window add-in. It is responsible for
/// creating and disposing the user interface class of the dockable window.
/// </summary>
public class AddinImpl : ESRI.ArcGIS.Desktop.AddIns.DockableWindow
{
private DigitDockableWindow m_windowUI;
public AddinImpl()
{
}
protected override IntPtr OnCreateChild()
{
m_windowUI = new DigitDockableWindow(this.Hook);
CurrentDigitTool.CurrentTool.digitDockableWindow = m_windowUI;
if (CurrentDigitTool.CurrentTool.currentDigit != null)
{
m_windowUI.m_digitCommand = CurrentDigitTool.CurrentTool.currentDigit;
m_windowUI.m_digitCommand.m_dockableDigit = m_windowUI;
}
else
{
// CurrentDigitTool.CurrentTool.CurrentDigit is null when we open ArcMap, but OnCreateChild
// is called if the dockable window was shown during the last ArcMap session.
ESRI.ArcGIS.Framework.IDockableWindowManager dockWinMgr = ArcMap.DockableWindowManager;
UID u = new UID();
u.Value = "DigitTool_DockableWindowCS";
CurrentDigitTool.CurrentTool.currentDockableWindow = dockWinMgr.GetDockableWindow(u);
}
return m_windowUI.Handle;
}
protected override void Dispose(bool disposing)
{
if (m_windowUI != null)
m_windowUI.Dispose(disposing);
base.Dispose(disposing);
}
}
public void Init(ISchematicLayer schematicLayer)
{
// CR229717: Lost the ElementClass if the dockable window is deactivate
if (schematicLayer == m_schematicLayer)
if (m_schEltClass != null)
return;
try
{
if (schematicLayer == null)
return;
m_schematicLayer = schematicLayer;
XmlNode col = null;
String myString = "";
m_schDataset = schematicLayer.SchematicDiagram.SchematicDiagramClass.SchematicDataset;
m_schEltClassCont = (ISchematicElementClassContainer)m_schDataset;
m_SchematicInMemoryDiagram = schematicLayer.SchematicInMemoryDiagram;
m_dom = new XmlDocument();
ISchematicDiagram schematicDiagram;
schematicDiagram = m_SchematicInMemoryDiagram.SchematicDiagram;
// get the path of the xml file that contains the definitions of the digitize dockable window
String path;
ISchematicDiagramClass schematicDiagramClass = schematicDiagram.SchematicDiagramClass;
ISchematicAttributeContainer schematicAttributeContainer = (ISchematicAttributeContainer)schematicDiagramClass;
ISchematicAttribute schematicAttribute = schematicAttributeContainer.GetSchematicAttribute("DigitizePropertiesLocation", true);
if (schematicAttribute == null)
{
System.Windows.Forms.MessageBox.Show("Need an attribute named DigitizePropertiesLocation in the corresponding DiagramTemplate attributes");
return;
}
path = (string)schematicAttribute.GetValue((ISchematicObject)schematicDiagram);
if (IsRelative(path)) //Concat the workspace's path with this path
{
//current workspace path
ISchematicDataset myDataset = schematicDiagramClass.SchematicDataset;
if (myDataset != null)
{
ISchematicWorkspace mySchematicWorkspace = myDataset.SchematicWorkspace;
if (mySchematicWorkspace != null)
{
ESRI.ArcGIS.Geodatabase.IWorkspace myWorkspace = mySchematicWorkspace.Workspace;
if (myWorkspace != null)
{
string workspacePath = myWorkspace.PathName;
//add "..\" to path to step back one level...
string stepBack = "..\\";
path = stepBack + path;
path = System.IO.Path.Combine(workspacePath, path);
}
}
}
}
//else keep the original hard path
XmlReader reader = XmlReader.Create(path);
m_dom.Load(reader);
//Load Nodes
XmlNodeList nodes = m_dom.SelectNodes("descendant::NodeFeature");
//Clear combo box after each call
cboNodeType.Items.Clear();
foreach (XmlElement node in nodes)
{
cboNodeType.Items.Add(node.GetAttribute("FeatureClassName").ToString());
}
//Load Links
XmlNodeList links = m_dom.SelectNodes("descendant::LinkFeature");
//Clear combo box after each call
cboLinkType.Items.Clear();
foreach (XmlElement link in links)
{
cboLinkType.Items.Add(link.GetAttribute("FeatureClassName").ToString());
}
col = m_dom.SelectSingleNode("descendant::MandatoryColor");
if (col != null)
{
myString = "System.Drawing.";
myString = col.InnerText.ToString();
m_MandatoryColor = System.Drawing.Color.FromName(myString);
}
col = m_dom.SelectSingleNode("descendant::FormName");
if (col != null)
{
myString = col.InnerText.ToString();
Text = myString;
}
XmlNodeList rels = m_dom.SelectNodes("descendant::Relation");
if (rels.Count > 0)
m_relations = rels;
col = m_dom.SelectSingleNode("descendant::AutoClearAfterCreate");
if ((col != null) && col.InnerText.ToString() == "True")
m_autoClear = true;
}
catch (System.Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
}
m_Panel1 = Splitter.Panel1;
m_Panel2 = Splitter.Panel2;
m_curPanel = Splitter.Panel1;
lblMode.Text = "Create Node";
m_loading = false;
m_clickPanel = false;
m_schEltClass = null;
}
public bool ValidateFields()
{
bool blnValidated = true;
System.Windows.Forms.MaskedTextBox mctrl = null;
string errors = "";
string linkTypeChoice = "";
bool firstime = true;
//check all mandatory fields
System.Windows.Forms.Control ctrl2;
foreach (System.Windows.Forms.Control ctrl in m_curPanel.Controls)
{
ctrl2 = ctrl;
if (ctrl2.GetType() == typeof(System.Windows.Forms.Label))
{
}
//ignore labels
else
{
if ((string)ctrl2.Tag == "Mandatory")
{
if (ctrl2.GetType() == typeof(System.Windows.Forms.MaskedTextBox))
{
mctrl = (System.Windows.Forms.MaskedTextBox)ctrl2;
if (mctrl.MaskCompleted == false)
{
blnValidated = false;
if (errors.Length > 0)
errors = "Incomplete mandatory field" + Environment.NewLine + "Complete missing data and click on OK button";
else
errors = errors + Environment.NewLine + "Incomplete mandatory field" + Environment.NewLine + "Complete missing data and click on OK button";
}
}
else
{
if (ctrl2.Text.Length <= 0)
{
blnValidated = false;
if (errors.Length <= 0)
errors = "Incomplete mandatory field" + Environment.NewLine + "Complete missing data and click on OK button";
else
errors = errors + Environment.NewLine + "Incomplete mandatory field" + Environment.NewLine + "Complete missing data and click on OK button";
}
}
}
//check masked edit controls
if (ctrl2.GetType() == typeof(System.Windows.Forms.MaskedTextBox))
{
mctrl = (System.Windows.Forms.MaskedTextBox)ctrl2;
//if they typed something, but didn't complete it, then error
//if they typed nothing and it is not mandatory, then it is OK
if ((mctrl.Text.Length > 0) && mctrl.Modified && (!mctrl.MaskCompleted))
{
blnValidated = false;
if (errors.Length > 0)
errors = "Invalid entry in a masked text field";
else
errors = errors + Environment.NewLine + "Invalid entry in a masked text field";
}
}
//check link connections
if (m_curPanel == Splitter.Panel2)
{
//make sure that the relation is correct if it exists
XmlNodeList fields = m_curLink.SelectNodes("descendant::Field");
foreach (XmlElement field in fields)
{
//find the field with a type of "Relation"
if (field.GetAttribute("Type") == "Relation")
{
ESRI.ArcGIS.Geodatabase.IDataset pDataset1;
ESRI.ArcGIS.Geodatabase.IDataset pDataset2;
string FeatureClass1Name;
string FeatureClass2Name;
pDataset1 = (ESRI.ArcGIS.Geodatabase.IDataset)m_schematicFeature1.SchematicElementClass;
pDataset2 = (ESRI.ArcGIS.Geodatabase.IDataset)m_schematicFeature2.SchematicElementClass;
FeatureClass1Name = pDataset1.Name;
FeatureClass2Name = pDataset2.Name;
foreach (XmlElement rel in m_relations)
{
//loop through the xml relations to match based on the from node and to node types
if ((rel.GetAttribute("FromType") == FeatureClass1Name) && (rel.GetAttribute("ToType") == FeatureClass2Name))
{
//find the control with the pick list for relationships
Control[] ctrls = m_curPanel.Controls.Find(field.GetAttribute("DBColumnName"), true);
if (ctrls.Length > 0)
ctrl2 = ctrls[0];
XmlNodeList vals = rel.SelectNodes("descendant::Value");
string myString = rel.GetAttribute("FromType") + "-" + rel.GetAttribute("ToType");
string linkTypeClicking = myString;
//validate that the current control string is correct
//if there are values, use them
bool blnfound = false;
if (vals.Count > 0)
{
foreach (XmlElement val in vals)
{
linkTypeClicking = myString + "-" + val.InnerText.ToString();
if (myString + "-" + val.InnerText.ToString() == ctrl2.Text)
{
blnfound = true;
break;
}
else
{
blnfound = false;
if (firstime)
{
linkTypeChoice = ctrl2.Text;
firstime = false;
}
}
}
if (!blnfound)
{
blnValidated = false;
if (errors.Length > 0)
{
errors = "Invalid link connection because :";
errors = errors + Environment.NewLine + "Type's link clicked : " + linkTypeClicking;
errors = errors + Environment.NewLine + "Type's link chosen : " + linkTypeChoice;
}
else
{
errors = errors + Environment.NewLine + "Invalid link connection because :";
errors = errors + Environment.NewLine + "Type's link clicked : " + linkTypeClicking;
errors = errors + Environment.NewLine + "Type's link chosen : " + linkTypeChoice;
}
}
}
else
{
if (ctrl2.Text != myString)
{
if (firstime)
{
linkTypeChoice = ctrl2.Text;
firstime = false;
}
blnValidated = false;
if (errors.Length > 0)
{
errors = "Invalid link connection because :";
errors = errors + Environment.NewLine + "Type's link clicked : " + linkTypeClicking;
errors = errors + Environment.NewLine + "Type's link chosen : " + linkTypeChoice;
}
else
{
errors = errors + Environment.NewLine + "Invalid link connection because :";
errors = errors + Environment.NewLine + "Type's link clicked : " + linkTypeClicking;
errors = errors + Environment.NewLine + "Type's link chosen : " + linkTypeChoice;
}
}
else //// treatment case ctrl2.Text = myString
{
blnfound = true;
}
}
if (!blnfound) //fix connection list
{
XmlNodeList vlist = m_dom.SelectNodes("descendant::Relation");
XmlNodeList rellist = null;
System.Windows.Forms.ComboBox cboconn = (System.Windows.Forms.ComboBox)ctrl2;
cboconn.Items.Clear();
foreach (XmlElement v in vlist)
{
if ((v.GetAttribute("LinkType").ToString() == m_curLink.GetAttribute("FeatureClassName").ToString())
//make sure the node types are ok
&& (v.GetAttribute("FromType").ToString() == FeatureClass1Name || v.GetAttribute("ToType").ToString() == FeatureClass2Name))
{
rellist = v.SelectNodes("descendant::Value");
if (rellist.Count > 0)
{
foreach (XmlElement r in rellist)
{
myString = v.GetAttribute("FromType").ToString() + "-" + v.GetAttribute("ToType").ToString() + "-" + r.InnerText.ToString();
cboconn.Items.Add(myString);
}
}
else //assume they are not using subtypes
cboconn.Items.Add(v.GetAttribute("FromType").ToString() + "-" + v.GetAttribute("ToType").ToString());
}
}
}
}
}
}
}
}
}
}
if (errors.Length > 0)
{
if (m_curPanel == Splitter.Panel1)
{
btnOKPanel1.Visible = true;
ErrorProvider1.SetError(btnOKPanel1, errors);
}
else
{
btnOKPanel2.Visible = true;
ErrorProvider1.SetError(btnOKPanel2, errors);
}
}
return blnValidated;
}
public void SelectionChanged()
{
try
{
System.Windows.Forms.Control ctrl = null;
System.Windows.Forms.Control ctrl2 = null;
Control[] ctrls = null;
System.Collections.ArrayList ctrlstoremove = new System.Collections.ArrayList();
string labelName = "";
string featureClass = "";
System.Windows.Forms.ComboBox cbo = null;
System.Windows.Forms.Label lblMain = null;
if (m_digitCommand == null)
return;
//clear any current elements
if (m_schematicFeature1 != null)
{
m_schematicFeature1 = null;
m_digitCommand.SchematicFeature1(m_schematicFeature1);
}
if (m_schematicFeature2 != null)
{
m_schematicFeature2 = null;
m_digitCommand.SchematicFeature2(m_schematicFeature2);
}
if (m_curPanel == Splitter.Panel1)
{
labelName = "lblNodeLabel";
featureClass = "descendant::NodeFeature";
cbo = cboNodeType;
lblMain = lblNodeLabel;
}
else
{
labelName = "lblLinkLabel";
featureClass = "descendant::LinkFeature";
cbo = cboLinkType;
lblMain = lblLinkLabel;
}
foreach (System.Windows.Forms.Control ctrlfor in m_curPanel.Controls)
{
if (ctrlfor.Name.StartsWith("lbl") && (ctrlfor.Name.ToString() != labelName))
{
ctrls = m_curPanel.Controls.Find(ctrlfor.Name.Substring(3), true);
ctrl2 = ctrls[0];
ctrlstoremove.Add(ctrlfor);
ctrlstoremove.Add(ctrl2);
}
}
if (ctrlstoremove.Count > 0)
{
foreach (System.Windows.Forms.Control ctrol in ctrlstoremove)
{
m_curPanel.Controls.Remove(ctrol);
}
}
XmlNodeList elems = null;
m_curfrmWidth = m_curPanel.Width;
elems = m_dom.SelectNodes(featureClass);
bool blnFound = false;
XmlElement elem = null;
foreach (XmlElement elem0 in elems)
{
if (elem0.GetAttribute("FeatureClassName").ToString() == cbo.Text.ToString())
{
elem = elem0;
blnFound = true;
break;
}
}
if (blnFound == false)
{
// CR229717: If this is deactivate, lost the Schematic ElementClass and can not retrieve it
//m_schEltClass = null;
return;
}
if (m_curPanel == Splitter.Panel1)
m_curNode = elem;
else
m_curLink = elem;
//set grid
elems = elem.SelectNodes("descendant::Field");
int x = Splitter.Location.X;
int y = lblMain.Location.Y + lblMain.Height + 5;
System.Drawing.Point p = new System.Drawing.Point();
foreach (XmlElement f in elems)
{
System.Windows.Forms.Label lbl = new System.Windows.Forms.Label();
lbl.Name = "lbl" + f.GetAttribute("DBColumnName").ToString();
lbl.Text = f.GetAttribute("DisplayName").ToString();
lbl.AutoSize = true;
m_curPanel.Controls.Add(lbl);
p.X = 3;
p.Y = y;
lbl.Location = p;
y = y + lbl.Height + 10;
switch (f.GetAttribute("Type").ToString())
{
case "Text":
System.Windows.Forms.TextBox tx = new System.Windows.Forms.TextBox();
ctrl = tx;
tx.Name = f.GetAttribute("DBColumnName").ToString();
if (f.GetAttribute("Length").Length > 0)
tx.MaxLength = System.Convert.ToInt32(f.GetAttribute("Length"));
if (f.GetAttribute("Default").Length > 0)
tx.Text = f.GetAttribute("Default");
m_curPanel.Controls.Add(tx);
break;
case "Combo":
System.Windows.Forms.ComboBox cb = new System.Windows.Forms.ComboBox();
string defaulttext = "";
ctrl = cb;
cb.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
cb.Name = f.GetAttribute("DBColumnName").ToString();
XmlNodeList vlist = f.SelectNodes("descendant::Value");
foreach (XmlElement v in vlist)
{
cb.Items.Add(v.InnerText.ToString());
if (v.GetAttribute("Default").Length > 0)
defaulttext = v.InnerText;
}
if (defaulttext.Length > 0)
cb.Text = defaulttext;
m_curPanel.Controls.Add(cb);
break;
case "MaskText":
System.Windows.Forms.MaskedTextBox MaskControl = new System.Windows.Forms.MaskedTextBox();
ctrl = MaskControl;
string mask = "";
MaskControl.Name = f.GetAttribute("DBColumnName").ToString();
if (f.GetAttribute("Mask").Length > 0)
mask = f.GetAttribute("Mask");
else
mask = "";
MaskControl.Mask = mask;
if (f.GetAttribute("Default").Length > 0)
MaskControl.Text = f.GetAttribute("Default");
MaskControl.Modified = false;
m_curPanel.Controls.Add(MaskControl);
MaskControl.TextChanged += new System.EventHandler(MaskedTextBox);
break;
case "Number":
System.Windows.Forms.MaskedTextBox MaskControl2 = new System.Windows.Forms.MaskedTextBox();
ctrl = MaskControl2;
string mask2 = "";
MaskControl2.Name = f.GetAttribute("DBColumnName").ToString();
int i = 1;
if (f.GetAttribute("Length").Length > 0)
{
for (i = 1; i <= System.Convert.ToInt32(f.GetAttribute("Length")); i++)
mask = mask2 + "9";
}
else
{
if (f.GetAttribute("Mask").Length > 0)
mask2 = f.GetAttribute("Mask");
else
mask2 = "";
}
MaskControl2.Mask = mask2;
if (f.GetAttribute("Default").Length > 0)
MaskControl2.Text = f.GetAttribute("Default");
MaskControl2.Modified = false;
m_curPanel.Controls.Add(MaskControl2);
MaskControl2.TextChanged += new System.EventHandler(MaskedTextBox);
break;
case "Date":
System.Windows.Forms.DateTimePicker dt = new System.Windows.Forms.DateTimePicker();
ctrl = dt;
dt.Name = f.GetAttribute("DBColumnName").ToString();
dt.Value = DateTime.Now;
dt.Format = System.Windows.Forms.DateTimePickerFormat.Short;
m_curPanel.Controls.Add(dt);
break;
case "Relation":
System.Windows.Forms.ComboBox cb2 = new System.Windows.Forms.ComboBox();
ctrl = cb2;
cb2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
cb2.Name = f.GetAttribute("DBColumnName").ToString();
XmlNodeList vlist2 = m_dom.SelectNodes("descendant::Relation");
XmlNodeList rellist = null;
string str = null;
foreach (XmlElement v in vlist2)
{
if (v.GetAttribute("LinkType").ToString() == elem.GetAttribute("FeatureClassName").ToString())
{
rellist = v.SelectNodes("descendant::Value");
if (rellist.Count > 0)
foreach (XmlElement r in rellist)
{
str = v.GetAttribute("FromType").ToString() + "-" + v.GetAttribute("ToType").ToString() + "-" + r.InnerText.ToString();
cb2.Items.Add(str);
}
else //assume they are not using subtypes
cb2.Items.Add(v.GetAttribute("FromType").ToString() + "-" + v.GetAttribute("ToType").ToString());
}
}
//relations are always mandatory
ctrl.BackColor = m_MandatoryColor;
ctrl.Tag = "Mandatory";
m_curPanel.Controls.Add(cb2);
break;
}
if (f.GetAttribute("Mandatory").ToString() == "True")
{
ctrl.BackColor = m_MandatoryColor;
ctrl.Tag = "Mandatory";
}
}
ResizeForm();
// set m_schEltClass
XmlElement curElement = null;
if (m_curPanel == Splitter.Panel1)
curElement = m_curNode;
else
curElement = m_curLink;
if (m_schEltClass == null)
m_schEltClass = m_schEltClassCont.GetSchematicElementClass(curElement.GetAttribute("FeatureClassName"));
else
if (m_schEltClass.Name != curElement.GetAttribute("FeatureClassName"))
m_schEltClass = m_schEltClassCont.GetSchematicElementClass(curElement.GetAttribute("FeatureClassName"));
}
catch (System.Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
}
}
public bool CheckValidFeature(bool blnFromNode)
{
if (m_curLink == null)
return false;
// CR229717: check if relation finish with the good kind of node
string sRelation = "";
try // If ComboBox does not exist, return an error
{
sRelation = ((ComboBox)this.Splitter.Panel2.Controls["Type"]).Text;
if (sRelation == "")
return false;
if (blnFromNode)
sRelation = sRelation.Substring(0, sRelation.IndexOf("-"));
else
{
sRelation = sRelation.Substring(sRelation.IndexOf("-") + 1);
if (sRelation.IndexOf("-") > 0)
sRelation = sRelation.Substring(0, sRelation.IndexOf("-"));
}
}
catch { }
XmlNodeList fields = m_curLink.SelectNodes("descendant::Field");
foreach (XmlElement field in fields)
{
if (field.GetAttribute("Type") == "Relation")
{
foreach (XmlElement rel in m_relations)
{
// CR229717: check if relation is for this kind of link
if (rel.GetAttribute("LinkType") != this.cboLinkType.Text)
continue;
if (blnFromNode)
{
if (m_schematicFeature1 == null)
return false;
// CR229717: check if relation start with the good kind of node
if (sRelation != rel.GetAttribute("FromType"))
continue;
if (rel.GetAttribute("FromType") == m_schematicFeature1.SchematicElementClass.Name)
return true;
}
else
{
if (m_schematicFeature2 == null)
return false;
// CR229717: check if relation finish with the good kind of node
if (sRelation != rel.GetAttribute("ToType"))
continue;
if (rel.GetAttribute("ToType") == m_schematicFeature2.SchematicElementClass.Name)
return true;
}
}
return false;
}
}
return true;
}
public void FillValue(ref ISchematicFeature schFeature)
{
try
{
if (m_schEltClass == null)
throw new Exception("Error getting Feature Class");
int fldIndex;
foreach (System.Windows.Forms.Control ctrl in m_curPanel.Controls)
{
if (!((ctrl.GetType() == typeof(System.Windows.Forms.Label)) || (ctrl.Name == "cboNodeType")))
{
if ((ctrl.GetType() == typeof(System.Windows.Forms.TextBox)) || (ctrl.GetType() == typeof(System.Windows.Forms.ComboBox)))
{
if (ctrl.Text.Length > 0)
{
//insert in DB
fldIndex = schFeature.Fields.FindField(ctrl.Name);
if (fldIndex > -1)
{
schFeature.set_Value(fldIndex, ctrl.Text);
schFeature.Store();
}
}
}
else if (ctrl.GetType() == typeof(System.Windows.Forms.DateTimePicker))
{
fldIndex = schFeature.Fields.FindField(ctrl.Name);
if (fldIndex > -1)
{
schFeature.set_Value(fldIndex, ctrl.Text);
schFeature.Store();
}
}
else if (ctrl.GetType() == typeof(System.Windows.Forms.MaskedTextBox))
{
System.Windows.Forms.MaskedTextBox mctrl = (System.Windows.Forms.MaskedTextBox)ctrl;
if ((mctrl.Text.Length > 0) && (mctrl.Modified) && (mctrl.MaskCompleted))
{
fldIndex = schFeature.Fields.FindField(ctrl.Name);
if (fldIndex > -1)
{
schFeature.set_Value(fldIndex, ctrl.Text);
schFeature.Store();
}
}
}
}
}
return;
}
catch (System.Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
}
}
private void ResizeForm()
{
try
{
System.Windows.Forms.Control ctr2;
Control[] ctrls = null;
System.Drawing.Point p = new System.Drawing.Point();
//handle panel 1
foreach (System.Windows.Forms.Control ctr in Splitter.Panel1.Controls)
{
if ((ctr.Name.StartsWith("lbl")) && (ctr.Name.ToString() != "lblNodeLabel"))
{
ctrls = Splitter.Panel1.Controls.Find(ctr.Name.Substring(3), true);
if (ctrls.GetLength(0) > 0)
{
ctr2 = ctrls[0];
p.Y = ctr.Location.Y;
p.X = ctr.Width + 3;
ctr2.Location = p;
ctr2.Width = Splitter.Panel1.Width - ctr.Width - 8;
}
}
}
Splitter.Panel1.Refresh();
//handle panel 2
foreach (System.Windows.Forms.Control ctr in Splitter.Panel2.Controls)
{
if ((ctr.Name.StartsWith("lbl")) && (ctr.Name.ToString() != "lblLinkLabel"))
{
ctrls = Splitter.Panel2.Controls.Find(ctr.Name.Substring(3), true);
if (ctrls.GetLength(0) > 0)
{
ctr2 = ctrls[0];
p.Y = ctr.Location.Y;
p.X = ctr.Width + 3;
ctr2.Location = p;
ctr2.Width = Splitter.Panel2.Width - ctr.Width - 8;
}
}
}
Splitter.Panel2.Refresh();
}
catch (System.Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
}
}
private void cboType_SelectedIndexChanged(Object sender, System.EventArgs e)
{
SelectionChanged();
}
public void cboLinkType_SelectedIndexChanged(Object sender, System.EventArgs e)
{
SelectionChanged();
}
private void MaskedTextBox(Object sender, System.EventArgs e)
{
System.Windows.Forms.MaskedTextBox mctrl = (System.Windows.Forms.MaskedTextBox)sender;
mctrl.Modified = true;
}
/// <summary>
/// m_createNode is true when the active panel is the one that digitize nodes.
/// </summary>
/// <returns></returns>
public bool CreateNode()
{
return m_createNode;
}
public bool AutoClear()
{
return m_autoClear;
}
public bool IsClosed()
{
return m_isClosed;
}
public ISchematicElementClass FeatureClass()
{
return m_schEltClass;
}
public void x(int x)
{
m_x = x;
return;
}
public void y(int y)
{
m_y = y;
return;
}
public void SchematicFeature1(ISchematicFeature schematicFeature)
{
m_schematicFeature1 = schematicFeature;
return;
}
public void SchematicFeature2(ISchematicFeature schematicFeature)
{
m_schematicFeature2 = schematicFeature;
return;
}
public void FrmApplication(ESRI.ArcGIS.Framework.IApplication app)
{
m_app = app;
return;
}
private void Splitter_Panel2_Click(object sender, EventArgs e)
{
if (m_digitCommand == null)
m_digitCommand = CurrentDigitTool.CurrentTool.currentDigit;
if (m_digitCommand == null)
return;
m_createNode = false;
if (m_curPanel != Splitter.Panel2)
{
m_curPanel = Splitter.Panel2;
foreach (System.Windows.Forms.Control ctrl in Splitter.Panel1.Controls)
ctrl.Enabled = false;
foreach (System.Windows.Forms.Control ctrl in Splitter.Panel2.Controls)
ctrl.Enabled = true;
lblMode.Text = "Create Link";
if (m_schematicFeature1 != null)
{
m_schematicFeature1 = null;
m_digitCommand.SchematicFeature1(m_schematicFeature1);
}
if (m_schematicFeature2 != null)
{
m_schematicFeature2 = null;
m_digitCommand.SchematicFeature2(m_schematicFeature2);
}
if (m_curPanel == Splitter.Panel1)
{
btnOKPanel1.Visible = false;
ErrorProvider1.SetError(btnOKPanel1, "");
}
else
{
btnOKPanel2.Visible = false;
ErrorProvider1.SetError(btnOKPanel2, "");
}
System.EventArgs e2 = new System.EventArgs();
cboLinkType_SelectedIndexChanged(sender, e2);
}
}
private void Splitter_Panel1_Click(object sender, EventArgs e)
{
if (m_digitCommand == null)
m_digitCommand = CurrentDigitTool.CurrentTool.currentDigit;
if (m_digitCommand != null)
m_digitCommand.EndFeedBack();
m_createNode = true;
if (m_curPanel != Splitter.Panel1 || m_clickPanel == false)
{
m_clickPanel = true;
m_curPanel = Splitter.Panel1;
foreach (System.Windows.Forms.Control ctrl in Splitter.Panel2.Controls)
ctrl.Enabled = false;
foreach (System.Windows.Forms.Control ctrl in Splitter.Panel1.Controls)
ctrl.Enabled = true;
lblMode.Text = "Create Node";
if (m_curPanel == Splitter.Panel1)
{
btnOKPanel1.Visible = false;
ErrorProvider1.SetError(btnOKPanel1, "");
}
else
{
btnOKPanel2.Visible = false;
ErrorProvider1.SetError(btnOKPanel2, "");
}
System.EventArgs e2 = new System.EventArgs();
cboType_SelectedIndexChanged(sender, e2);
}
}
private void btnOKPanel1_Click(object sender, EventArgs e)
{
//try to create the node at the original point
if (m_digitCommand != null)
m_digitCommand.MyMouseUp(m_x, m_y);
ErrorProvider1.SetError(btnOKPanel1, "");
btnOKPanel1.Visible = false;
}
private void btnOKPanel2_Click(object sender, EventArgs e)
{
//try to create the link with the original points
if (m_digitCommand != null)
m_digitCommand.MyMouseUp(m_x, m_y);
ErrorProvider1.SetError(btnOKPanel1, "");
btnOKPanel1.Visible = false;
}
private void WindowVisibleChange(object sender, EventArgs e)
{
if (m_digitCommand == null)
m_digitCommand = CurrentDigitTool.CurrentTool.currentDigit;
if (m_digitCommand == null)
return;
if ((this.Visible) && !CurrentDigitTool.CurrentTool.currentDockableWindow.IsVisible())
{
if (!(m_digitCommand.FromDeactivate()))
{
m_digitCommand.DeactivatedFromDock(true);
ESRI.ArcGIS.Framework.IApplication app = (ESRI.ArcGIS.Framework.IApplication)this.Hook;
app.CurrentTool = null;
}
}
m_digitCommand.EndFeedBack();
m_digitCommand.FromDeactivate(false);
}
private void DigitWindow_Resize(object sender, EventArgs e)
{
if (!m_loading)
ResizeForm();
}
//IsRelative return true when the path start with "."
private bool IsRelative(string path)
{
bool startwith = path.StartsWith(".");
return startwith;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V10.Resources;
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>BiddingSeasonalityAdjustment</c> resource.</summary>
public sealed partial class BiddingSeasonalityAdjustmentName : gax::IResourceName, sys::IEquatable<BiddingSeasonalityAdjustmentName>
{
/// <summary>The possible contents of <see cref="BiddingSeasonalityAdjustmentName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}</c>.
/// </summary>
CustomerSeasonalityEvent = 1,
}
private static gax::PathTemplate s_customerSeasonalityEvent = new gax::PathTemplate("customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}");
/// <summary>
/// Creates a <see cref="BiddingSeasonalityAdjustmentName"/> containing an unparsed resource name.
/// </summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="BiddingSeasonalityAdjustmentName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static BiddingSeasonalityAdjustmentName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new BiddingSeasonalityAdjustmentName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="BiddingSeasonalityAdjustmentName"/> with the pattern
/// <c>customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="seasonalityEventId">The <c>SeasonalityEvent</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="BiddingSeasonalityAdjustmentName"/> constructed from the provided ids.
/// </returns>
public static BiddingSeasonalityAdjustmentName FromCustomerSeasonalityEvent(string customerId, string seasonalityEventId) =>
new BiddingSeasonalityAdjustmentName(ResourceNameType.CustomerSeasonalityEvent, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), seasonalityEventId: gax::GaxPreconditions.CheckNotNullOrEmpty(seasonalityEventId, nameof(seasonalityEventId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="BiddingSeasonalityAdjustmentName"/> with
/// pattern <c>customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="seasonalityEventId">The <c>SeasonalityEvent</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="BiddingSeasonalityAdjustmentName"/> with pattern
/// <c>customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}</c>.
/// </returns>
public static string Format(string customerId, string seasonalityEventId) =>
FormatCustomerSeasonalityEvent(customerId, seasonalityEventId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="BiddingSeasonalityAdjustmentName"/> with
/// pattern <c>customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="seasonalityEventId">The <c>SeasonalityEvent</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="BiddingSeasonalityAdjustmentName"/> with pattern
/// <c>customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}</c>.
/// </returns>
public static string FormatCustomerSeasonalityEvent(string customerId, string seasonalityEventId) =>
s_customerSeasonalityEvent.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(seasonalityEventId, nameof(seasonalityEventId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="BiddingSeasonalityAdjustmentName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="biddingSeasonalityAdjustmentName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <returns>The parsed <see cref="BiddingSeasonalityAdjustmentName"/> if successful.</returns>
public static BiddingSeasonalityAdjustmentName Parse(string biddingSeasonalityAdjustmentName) =>
Parse(biddingSeasonalityAdjustmentName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="BiddingSeasonalityAdjustmentName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="biddingSeasonalityAdjustmentName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="BiddingSeasonalityAdjustmentName"/> if successful.</returns>
public static BiddingSeasonalityAdjustmentName Parse(string biddingSeasonalityAdjustmentName, bool allowUnparsed) =>
TryParse(biddingSeasonalityAdjustmentName, allowUnparsed, out BiddingSeasonalityAdjustmentName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="BiddingSeasonalityAdjustmentName"/>
/// instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="biddingSeasonalityAdjustmentName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="BiddingSeasonalityAdjustmentName"/>, or <c>null</c> if
/// parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string biddingSeasonalityAdjustmentName, out BiddingSeasonalityAdjustmentName result) =>
TryParse(biddingSeasonalityAdjustmentName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="BiddingSeasonalityAdjustmentName"/>
/// instance; optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="biddingSeasonalityAdjustmentName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="BiddingSeasonalityAdjustmentName"/>, or <c>null</c> if
/// parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string biddingSeasonalityAdjustmentName, bool allowUnparsed, out BiddingSeasonalityAdjustmentName result)
{
gax::GaxPreconditions.CheckNotNull(biddingSeasonalityAdjustmentName, nameof(biddingSeasonalityAdjustmentName));
gax::TemplatedResourceName resourceName;
if (s_customerSeasonalityEvent.TryParseName(biddingSeasonalityAdjustmentName, out resourceName))
{
result = FromCustomerSeasonalityEvent(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(biddingSeasonalityAdjustmentName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private BiddingSeasonalityAdjustmentName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string seasonalityEventId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
SeasonalityEventId = seasonalityEventId;
}
/// <summary>
/// Constructs a new instance of a <see cref="BiddingSeasonalityAdjustmentName"/> class from the component parts
/// of pattern <c>customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="seasonalityEventId">The <c>SeasonalityEvent</c> ID. Must not be <c>null</c> or empty.</param>
public BiddingSeasonalityAdjustmentName(string customerId, string seasonalityEventId) : this(ResourceNameType.CustomerSeasonalityEvent, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), seasonalityEventId: gax::GaxPreconditions.CheckNotNullOrEmpty(seasonalityEventId, nameof(seasonalityEventId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>SeasonalityEvent</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string SeasonalityEventId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerSeasonalityEvent: return s_customerSeasonalityEvent.Expand(CustomerId, SeasonalityEventId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as BiddingSeasonalityAdjustmentName);
/// <inheritdoc/>
public bool Equals(BiddingSeasonalityAdjustmentName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(BiddingSeasonalityAdjustmentName a, BiddingSeasonalityAdjustmentName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(BiddingSeasonalityAdjustmentName a, BiddingSeasonalityAdjustmentName b) => !(a == b);
}
public partial class BiddingSeasonalityAdjustment
{
/// <summary>
/// <see cref="gagvr::BiddingSeasonalityAdjustmentName"/>-typed view over the <see cref="ResourceName"/>
/// resource name property.
/// </summary>
internal BiddingSeasonalityAdjustmentName ResourceNameAsBiddingSeasonalityAdjustmentName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::BiddingSeasonalityAdjustmentName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::BiddingSeasonalityAdjustmentName"/>-typed view over the <see cref="Name"/> resource name
/// property.
/// </summary>
internal BiddingSeasonalityAdjustmentName BiddingSeasonalityAdjustmentName
{
get => string.IsNullOrEmpty(Name) ? null : gagvr::BiddingSeasonalityAdjustmentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CampaignName"/>-typed view over the <see cref="Campaigns"/> resource name property.
/// </summary>
internal gax::ResourceNameList<CampaignName> CampaignsAsCampaignNames
{
get => new gax::ResourceNameList<CampaignName>(Campaigns, s => string.IsNullOrEmpty(s) ? null : CampaignName.Parse(s, allowUnparsed: true));
}
}
}
| |
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Orleans.SqlUtils;
namespace Orleans.Providers.SqlServer
{
/// <summary>
/// Plugin for publishing silos and client statistics to a SQL database.
/// </summary>
public class SqlStatisticsPublisher: IConfigurableStatisticsPublisher, IConfigurableSiloMetricsDataPublisher, IConfigurableClientMetricsDataPublisher, IProvider
{
private string deploymentId;
private IPAddress clientAddress;
private SiloAddress siloAddress;
private IPEndPoint gateway;
private string clientId;
private string siloName;
private string hostName;
private bool isSilo;
private long generation;
private RelationalOrleansQueries orleansQueries;
private Logger logger;
/// <summary>
/// Name of the provider
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Initializes publisher
/// </summary>
/// <param name="name">Provider name</param>
/// <param name="providerRuntime">Provider runtime API</param>
/// <param name="config">Provider configuration</param>
/// <returns></returns>
public async Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
{
Name = name;
logger = providerRuntime.GetLogger("SqlStatisticsPublisher");
string adoInvariant = AdoNetInvariants.InvariantNameSqlServer;
if (config.Properties.ContainsKey("AdoInvariant"))
adoInvariant = config.Properties["AdoInvariant"];
orleansQueries = await RelationalOrleansQueries.CreateInstance(adoInvariant, config.Properties["ConnectionString"]);
}
/// <summary>
/// Closes provider
/// </summary>
/// <returns>Resolved task</returns>
public Task Close()
{
return TaskDone.Done;
}
/// <summary>
/// Adds configuration parameters
/// </summary>
/// <param name="deployment">Deployment ID</param>
/// <param name="hostName">Host name</param>
/// <param name="client">Client ID</param>
/// <param name="address">IP address</param>
public void AddConfiguration(string deployment, string hostName, string client, IPAddress address)
{
deploymentId = deployment;
isSilo = false;
this.hostName = hostName;
clientId = client;
clientAddress = address;
generation = SiloAddress.AllocateNewGeneration();
}
/// <summary>
/// Adds configuration parameters
/// </summary>
/// <param name="deployment">Deployment ID</param>
/// <param name="silo">Silo name</param>
/// <param name="siloId">Silo ID</param>
/// <param name="address">Silo address</param>
/// <param name="gatewayAddress">Client gateway address</param>
/// <param name="hostName">Host name</param>
public void AddConfiguration(string deployment, bool silo, string siloId, SiloAddress address, IPEndPoint gatewayAddress, string hostName)
{
deploymentId = deployment;
isSilo = silo;
siloName = siloId;
siloAddress = address;
gateway = gatewayAddress;
this.hostName = hostName;
if(!isSilo)
{
generation = SiloAddress.AllocateNewGeneration();
}
}
async Task IClientMetricsDataPublisher.Init(ClientConfiguration config, IPAddress address, string clientId)
{
orleansQueries = await RelationalOrleansQueries.CreateInstance(config.AdoInvariant, config.DataConnectionString);
}
/// <summary>
/// Writes metrics to the database
/// </summary>
/// <param name="metricsData">Metrics data</param>
/// <returns>Task for database operation</returns>
public async Task ReportMetrics(IClientPerformanceMetrics metricsData)
{
if(logger != null && logger.IsVerbose3) logger.Verbose3("SqlStatisticsPublisher.ReportMetrics (client) called with data: {0}.", metricsData);
try
{
await orleansQueries.UpsertReportClientMetricsAsync(deploymentId, clientId, clientAddress, hostName, metricsData);
}
catch(Exception ex)
{
if (logger != null && logger.IsVerbose) logger.Verbose("SqlStatisticsPublisher.ReportMetrics (client) failed: {0}", ex);
throw;
}
}
Task ISiloMetricsDataPublisher.Init(string deploymentId, string storageConnectionString, SiloAddress siloAddress, string siloName, IPEndPoint gateway, string hostName)
{
return TaskDone.Done;
}
/// <summary>
/// Writes silo performance metrics to the database
/// </summary>
/// <param name="metricsData">Metrics data</param>
/// <returns>Task for database operation</returns>
public async Task ReportMetrics(ISiloPerformanceMetrics metricsData)
{
if (logger != null && logger.IsVerbose3) logger.Verbose3("SqlStatisticsPublisher.ReportMetrics (silo) called with data: {0}.", metricsData);
try
{
await orleansQueries.UpsertSiloMetricsAsync(deploymentId, siloName, gateway, siloAddress, hostName, metricsData);
}
catch(Exception ex)
{
if (logger != null && logger.IsVerbose) logger.Verbose("SqlStatisticsPublisher.ReportMetrics (silo) failed: {0}", ex);
throw;
}
}
Task IStatisticsPublisher.Init(bool isSilo, string storageConnectionString, string deploymentId, string address, string siloName, string hostName)
{
return TaskDone.Done;
}
/// <summary>
/// Writes statistics to the database
/// </summary>
/// <param name="statsCounters">Statistics counters to write</param>
/// <returns>Task for database opearation</returns>
public async Task ReportStats(List<ICounter> statsCounters)
{
var siloOrClientName = (isSilo) ? siloName : clientId;
var id = (isSilo) ? siloAddress.ToLongString() : string.Format("{0}:{1}", siloOrClientName, generation);
if (logger != null && logger.IsVerbose3) logger.Verbose3("ReportStats called with {0} counters, name: {1}, id: {2}", statsCounters.Count, siloOrClientName, id);
var insertTasks = new List<Task>();
try
{
//This batching is done for two reasons:
//1) For not to introduce a query large enough to be rejected.
//2) Performance, though using a fixed constants likely will not give the optimal performance in every situation.
const int maxBatchSizeInclusive = 200;
var counterBatches = BatchCounters(statsCounters, maxBatchSizeInclusive);
foreach(var counterBatch in counterBatches)
{
//The query template from which to retrieve the set of columns that are being inserted.
insertTasks.Add(orleansQueries.InsertStatisticsCountersAsync(deploymentId, hostName, siloOrClientName, id, counterBatch));
}
await Task.WhenAll(insertTasks);
}
catch(Exception ex)
{
if (logger != null && logger.IsVerbose) logger.Verbose("ReportStats faulted: {0}", ex.ToString());
foreach(var faultedTask in insertTasks.Where(t => t.IsFaulted))
{
if (logger != null && logger.IsVerbose) logger.Verbose("Faulted task exception: {0}", faultedTask.ToString());
}
throw;
}
if (logger != null && logger.IsVerbose) logger.Verbose("ReportStats SUCCESS");
}
/// <summary>
/// Batches the counters list to batches of given maximum size.
/// </summary>
/// <param name="counters">The counters to batch.</param>
/// <param name="maxBatchSizeInclusive">The maximum size of one batch.</param>
/// <returns>The counters batched.</returns>
private static List<List<ICounter>> BatchCounters(List<ICounter> counters, int maxBatchSizeInclusive)
{
var batches = new List<List<ICounter>>();
for(int i = 0; i < counters.Count; i += maxBatchSizeInclusive)
{
batches.Add(counters.GetRange(i, Math.Min(maxBatchSizeInclusive, counters.Count - i)));
}
return batches;
}
}
}
| |
/* ***************************************************************************
* This file is part of SharpNEAT - Evolution of Neural Networks.
*
* Copyright 2004-2016 Colin Green ([email protected])
*
* SharpNEAT is free software; you can redistribute it and/or modify
* it under the terms of The MIT License (MIT).
*
* You should have received a copy of the MIT License
* along with SharpNEAT; if not, see https://opensource.org/licenses/MIT.
*/
using System.Collections.Generic;
// Disables missing comment warnings for non-private variables.
#pragma warning disable 1591
namespace SharpNeat.Phenomes.NeuralNets
{
/// <summary>
/// This class is provided for debugging and educational purposes. FastCyclicNetwork is functionally
/// equivalent and is much faster and therefore should be used instead of CyclicNetwork in most
/// circumstances.
///
/// A neural network class that represents a network with recurrent (cyclic) connections. Recurrent
/// connections are handled by each neuron storing two values, a pre- and post-activation value
/// (InputValue and OutputValue). This allows us to calculate the output value for the current
/// iteration/timestep without modifying the output values from the previous iteration. That is, we
/// calculate all of this timestep's state based on state from the previous timestep.
///
/// When activating networks of this class the network's state is updated for a fixed number of
/// timesteps, the number of which is specified by the maxIterations parameter on the constructor.
/// See RelaxingCyclicNetwork for an alternative activation scheme.
/// </summary>
public class CyclicNetwork : IBlackBox
{
protected readonly List<Neuron> _neuronList;
protected readonly List<Connection> _connectionList;
// For efficiency we store the number of input and output neurons.
protected readonly int _inputNeuronCount;
protected readonly int _outputNeuronCount;
protected readonly int _inputAndBiasNeuronCount;
protected readonly int _timestepsPerActivation;
// The input and output arrays that the black box uses for IO with the outside world.
protected readonly double[] _inputSignalArray;
protected readonly double[] _outputSignalArray;
readonly SignalArray _inputSignalArrayWrapper;
readonly SignalArray _outputSignalArrayWrapper;
#region Constructor
/// <summary>
/// Constructs a CyclicNetwork with the provided pre-built neurons and connections.
/// </summary>
public CyclicNetwork(List<Neuron> neuronList,
List<Connection> connectionList,
int inputNeuronCount,
int outputNeuronCount,
int timestepsPerActivation)
{
_neuronList = neuronList;
_connectionList = connectionList;
_inputNeuronCount = inputNeuronCount;
_outputNeuronCount = outputNeuronCount;
_inputAndBiasNeuronCount = inputNeuronCount + 1;
_timestepsPerActivation = timestepsPerActivation;
_inputSignalArray = new double[_inputNeuronCount];
_outputSignalArray = new double[_outputNeuronCount];
_inputSignalArrayWrapper = new SignalArray(_inputSignalArray, 0, _inputNeuronCount);
_outputSignalArrayWrapper = new SignalArray(_outputSignalArray, 0, outputNeuronCount);
}
#endregion
#region IBlackBox Members
/// <summary>
/// Gets the number of inputs.
/// </summary>
public int InputCount
{
get { return _inputNeuronCount; }
}
/// <summary>
/// Gets the number of outputs.
/// </summary>
public int OutputCount
{
get { return _outputNeuronCount; }
}
/// <summary>
/// Gets an array for feeding input signals to the network.
/// </summary>
public ISignalArray InputSignalArray
{
get { return _inputSignalArrayWrapper; }
}
/// <summary>
/// Gets an array of output signals from the network.
/// </summary>
public ISignalArray OutputSignalArray
{
get { return _outputSignalArrayWrapper; }
}
/// <summary>
/// Gets a value indicating whether the internal state is valid. Always returns true for this class.
/// </summary>
public virtual bool IsStateValid
{
get { return true; }
}
/// <summary>
/// Activate the network for a fixed number of timesteps defined by maxTimesteps is reached.
/// </summary>
public virtual void Activate()
{
// Copy input signals into input neurons.
// Note. In fast implementations we can skip this step because the array is
// part of the working data of the network.
for(int i=0; i<_inputNeuronCount; i++)
{ // The +1 takes into account the bias neuron at index 0.
// Note. we set the output value of the input neurons, not the input value. This is because we
// don't want the signal to pass through the neuron's activation function.
_neuronList[i+1].OutputValue = _inputSignalArray[i];
}
// Activate the network for a fixed number of timesteps.
int connectionCount = _connectionList.Count;
int neuronCount = _neuronList.Count;
for(int i=0; i<_timestepsPerActivation; i++)
{
// Loop over all connections.
// Calculate each connection's output signal by multiplying its weight by the output value
// of its source neuron.
// Add the connection's output value to the target neuron's input value. Neurons therefore
// accumulate all input value from connections targeting them.
for(int j=0; j<connectionCount; j++)
{
Connection connection = _connectionList[j];
connection.OutputValue = connection.SourceNeuron.OutputValue * connection.Weight;
connection.TargetNeuron.InputValue += connection.OutputValue;
}
// Loop over all output and hidden neurons, passing their input signal through their activation
// function to produce an output value. Note we skip bias and input neurons because they have a
// fixed output value.
for(int j=_inputAndBiasNeuronCount; j<neuronCount; j++)
{
Neuron neuron = _neuronList[j];
neuron.OutputValue = neuron.ActivationFunction.Calculate(neuron.InputValue, neuron.AuxiliaryArguments);
// Reset input value, in preparation for the next timestep/iteration.
neuron.InputValue = 0.0;
}
}
// Copy the output neuron output values into the output signal array.
for(int i=_inputAndBiasNeuronCount, outputIdx=0; outputIdx<_outputNeuronCount; i++, outputIdx++)
{
_outputSignalArray[outputIdx] = _neuronList[i].OutputValue;
}
}
/// <summary>
/// Reset the network's internal state.
/// </summary>
public virtual void ResetState()
{
// Reset neuron state for all but the bias neuron.
// Input neurons - avoid setting InputValue. We only use the OutputValue of input neurons.
// TODO: Not strictly necessary; input node state is always overwritten at the initial stages of network activation.
for(int i=1; i<_inputAndBiasNeuronCount; i++) {
_neuronList[i].OutputValue = 0.0;
}
// Reset input and output value of all remaining neurons (output and hidden neurons).
int count = _neuronList.Count;
for(int i=_inputAndBiasNeuronCount; i<count; i++) {
_neuronList[i].InputValue = 0.0;
_neuronList[i].OutputValue = 0.0;
}
// Reset connection states.
count = _connectionList.Count;
for(int i=0; i<count; i++) {
_connectionList[i].OutputValue = 0.0;
}
}
#endregion
}
}
| |
//
// MonoMac.CFNetwork.Test.Views.LogViewerController
//
// Authors:
// Martin Baulig ([email protected])
//
// Copyright 2012 Xamarin Inc. (http://www.xamarin.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using MonoMac.Foundation;
using MonoMac.AppKit;
namespace MonoMac.CFNetwork.Test.Views {
public partial class LogViewerController : MonoMac.AppKit.NSWindowController {
#region Constructors
// Called when created from unmanaged code
public LogViewerController (IntPtr handle) : base (handle)
{
Initialize ();
}
// Called when created directly from a XIB file
[Export ("initWithCoder:")]
public LogViewerController (NSCoder coder) : base (coder)
{
Initialize ();
}
// Call to load from the XIB/NIB file
public LogViewerController () : base ("LogViewer")
{
Initialize ();
}
// Shared initialization code
void Initialize ()
{
writer = new OutputTextWriter (this);
listener = new Listener (this);
}
#endregion
NSFont font;
TraceListener listener;
OutputTextWriter writer;
public override void AwakeFromNib ()
{
base.AwakeFromNib ();
font = NSFont.SystemFontOfSize (16.0f);
}
//strongly typed window accessor
public new LogViewer Window {
get {
return (LogViewer)base.Window;
}
}
public NSTextStorage Storage {
get {
return Text.TextStorage;
}
}
public TextWriter TextWriter {
get {
return writer;
}
}
public override void ShowWindow (NSObject sender)
{
base.ShowWindow (sender);
Debug.Listeners.Add (listener);
}
partial void Clear (NSObject sender)
{
Storage.DeleteRange (new NSRange (0, Storage.Length));
}
partial void Quit (NSObject sender)
{
Debug.Listeners.Remove (listener);
Window.Close ();
}
#region Appending Text
public void Append (string text)
{
InvokeOnMainThread (() => DoAppend (text));
}
public void AppendLine (string message)
{
InvokeOnMainThread (() => DoAppend (message + Environment.NewLine));
}
public void AppendLine (NSColor color, string text)
{
InvokeOnMainThread (() => DoAppend (color, text + Environment.NewLine));
}
void DoAppend (string text)
{
var pos = Storage.Length;
Storage.Append (new NSAttributedString (text));
Text.SetFont (font, new NSRange (pos, text.Length));
}
void DoAppend (NSColor color, string text)
{
var pos = Storage.Length;
Storage.Append (new NSAttributedString (text));
var range = new NSRange (pos, text.Length);
Text.SetFont (font, range);
Text.SetTextColor (color, range);
}
#endregion
#region Text Writer
class OutputTextWriter : TextWriter {
LogViewerController controller;
public OutputTextWriter (LogViewerController controller)
{
this.controller = controller;
}
public override Encoding Encoding {
get { return Encoding.Default; }
}
public override void Write (char value)
{
controller.Append (value.ToString ());
}
public override void Write (string value)
{
controller.Append (value);
}
}
class Listener : TraceListener {
LogViewerController controller;
public Listener (LogViewerController controller)
{
this.controller = controller;
}
#region implemented abstract members of TraceListener
public override void Write (string message)
{
controller.Append (message);
}
public override void WriteLine (string message)
{
controller.AppendLine (message);
}
public override void Fail (string message)
{
Fail (message, "");
}
public override void Fail (string message, string detailMessage)
{
controller.AppendLine ("---- DEBUG ASSERTION FAILED ----");
controller.AppendLine ("---- Assert Short Message ----");
controller.AppendLine (NSColor.Red, message);
controller.AppendLine ("---- Assert Long Message ----");
controller.AppendLine (NSColor.Orange, detailMessage);
controller.AppendLine ("");
}
#endregion
}
#endregion
}
}
| |
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UMA.Integrations;
using UMA.CharacterSystem;
using UnityEngine.SceneManagement;
namespace UMA.Editors
{
/// <summary>
/// Recipe editor.
/// Class is marked partial so developers can add their own functionality to edit new properties added to
/// UMATextRecipe without changing code delivered with UMA.
/// </summary>
[CanEditMultipleObjects]
[CustomEditor(typeof(UMARecipeBase), true)]
public partial class RecipeEditor : CharacterBaseEditor
{
List<GameObject> draggedObjs;
GameObject generatedContext;
EditorWindow inspectorWindow;
//for showing a warning if any of the compatible races are missing or not assigned to bundles or the index
protected Texture warningIcon;
protected GUIStyle warningStyle;
private static List<IUMARecipePlugin> plugins;
public static List<Type> GetRecipeEditorPlugins() {
List<Type> theTypes = new List<Type>();
var Assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach(var asm in Assemblies) {
try {
var Types = asm.GetTypes();
foreach(var t in Types) {
if(typeof(IUMARecipePlugin).IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract) {
theTypes.Add(t);
}
}
} catch(Exception) {
// This apparently blows up on some assemblies.
}
}
return theTypes;
/* return AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes())
.Where(x => typeof(IUMAAddressablePlugin).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract)
.Select(x => x).ToList();*/
}
public virtual void OnSceneDrag(SceneView view)
{
if (Event.current.type == EventType.DragUpdated)
{
if (Event.current.mousePosition.x < 0 || Event.current.mousePosition.x >= view.position.width ||
Event.current.mousePosition.y < 0 || Event.current.mousePosition.y >= view.position.height) return;
DragAndDrop.visualMode = DragAndDropVisualMode.Copy; // show a drag-add icon on the mouse cursor
Event.current.Use();
return;
}
if (Event.current.type == EventType.DragPerform)
{
if (Event.current.mousePosition.x < 0 || Event.current.mousePosition.x >= view.position.width ||
Event.current.mousePosition.y < 0 || Event.current.mousePosition.y >= view.position.height) return;
Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
RaycastHit hit;
Vector3 position = Vector3.zero;
if (Physics.Raycast(ray, out hit))
{
position = hit.point;
}
var newSelection = new List<UnityEngine.Object>(DragAndDrop.objectReferences.Length);
foreach (var reference in DragAndDrop.objectReferences)
{
if (reference is UMARecipeBase)
{
var avatarGO = CreateAvatar(reference as UMARecipeBase);
avatarGO.GetComponent<Transform>().position = position;
position.x = position.x + 1;
newSelection.Add(avatarGO);
}
}
Selection.objects = newSelection.ToArray();
DragAndDrop.visualMode = DragAndDropVisualMode.Copy; // show a drag-add icon on the mouse cursor
Event.current.Use();
}
}
public virtual GameObject CreateAvatar(UMARecipeBase recipe)
{
var GO = new GameObject(recipe.name);
var avatar = GO.AddComponent<UMADynamicAvatar>();
avatar.umaRecipe = recipe;
avatar.loadOnStart = true;
return GO;
}
void AddPlugins() {
List<Type> PluginTypes = GetRecipeEditorPlugins();
plugins = new List<IUMARecipePlugin>();
foreach(Type t in PluginTypes) {
plugins.Add((IUMARecipePlugin)Activator.CreateInstance(t));
}
}
public override void OnEnable()
{
if(plugins == null) {
AddPlugins();
}
base.OnEnable();
foreach(IUMARecipePlugin plugin in plugins) {
plugin.OnEnable();
}
if (!NeedsReenable())
return;
_errorMessage = null;
_recipe = new UMAData.UMARecipe();
showBaseEditor = false;
try
{
var umaRecipeBase = target as UMARecipeBase;
if (umaRecipeBase != null)
{
var context = UMAContextBase.Instance;
//create a virtual UMAContextBase if we dont have one and we have DCS
if (context == null || context.gameObject.name == "UMAEditorContext")
{
context = umaRecipeBase.CreateEditorContext();//will create or update an UMAEditorContext to the latest version
generatedContext = context.gameObject.transform.parent.gameObject;//The UMAContextBase in a UMAEditorContext is that gameobject's child
}
//legacy checks for context
if (context == null)
{
_errorMessage = "Editing a recipe requires a loaded scene with a valid UMAContextBase.";
Debug.LogWarning(_errorMessage);
//_recipe = null;
//return;
}
umaRecipeBase.Load(_recipe, context);
_description = umaRecipeBase.GetInfo();
}
}
catch (UMAResourceNotFoundException e)
{
_errorMessage = e.Message;
}
dnaEditor = new DNAMasterEditor(_recipe);
slotEditor = new SlotMasterEditor(_recipe);
_rebuildOnLayout = true;
}
public void OnDestroy()
{
if (generatedContext != null)
{
//Ensure UMAContextBase.Instance is set to null
UMAContextBase.Instance = null;
DestroyImmediate(generatedContext);
}
foreach(IUMARecipePlugin plugin in plugins) {
plugin.OnDestroy();
}
}
public override void OnInspectorGUI()
{
if (warningIcon == null)
{
warningIcon = EditorGUIUtility.FindTexture("console.warnicon.sml");
warningStyle = new GUIStyle(EditorStyles.label);
warningStyle.fixedHeight = warningIcon.height + 4f;
warningStyle.contentOffset = new Vector2(0, -2f);
}
if (_recipe == null) return;
foreach(IUMARecipePlugin plugin in plugins)
{
string label = plugin.GetSectionLabel();
plugin.foldOut = GUIHelper.FoldoutBar(plugin.foldOut, label);
if(plugin.foldOut) {
GUIHelper.BeginVerticalPadded(10, new Color(0.65f, 0.675f, 1f));
plugin.OnInspectorGUI(serializedObject);
GUIHelper.EndVerticalPadded(10);
}
}
PowerToolsGUI();
base.OnInspectorGUI();
}
protected override void DoUpdate()
{
var recipeBase = (UMARecipeBase)target;
recipeBase.Save(_recipe, UMAContextBase.Instance);
EditorUtility.SetDirty(recipeBase);
AssetDatabase.SaveAssets();
_rebuildOnLayout = true;
_needsUpdate = false;
if (PowerToolsIntegration.HasPreview(recipeBase))
{
PowerToolsIntegration.Refresh(recipeBase);
}
if (target is UMATextRecipe)
{
UMAUpdateProcessor.UpdateRecipe(target as UMATextRecipe);
}
//else
//{
// PowerToolsIntegration.Show(recipeBase);
//}
}
protected override void Rebuild()
{
base.Rebuild();
var recipeBase = target as UMARecipeBase;
if (PowerToolsIntegration.HasPowerTools() && PowerToolsIntegration.HasPreview(recipeBase))
{
_needsUpdate = true;
}
}
private void PowerToolsGUI()
{
if (PowerToolsIntegration.HasPowerTools())
{
GUILayout.BeginHorizontal();
var recipeBase = target as UMARecipeBase;
if (PowerToolsIntegration.HasPreview(recipeBase))
{
if (GUILayout.Button("Hide"))
{
PowerToolsIntegration.Hide(recipeBase);
}
if (GUILayout.Button("Create Prefab"))
{
//PowerToolsIntegration.CreatePrefab(recipeBase);
}
if (GUILayout.Button("Hide All"))
{
PowerToolsIntegration.HideAll();
}
} else
{
if (GUILayout.Button("Show"))
{
PowerToolsIntegration.Show(recipeBase);
}
if (GUILayout.Button("Create Prefab"))
{
//PowerToolsIntegration.CreatePrefab(recipeBase);
}
if (GUILayout.Button("Hide All"))
{
PowerToolsIntegration.HideAll();
}
}
GUILayout.EndHorizontal();
}
}
/// <summary>
/// Checks if the given RaceData is in the globalLibrary or an assetBundle
/// </summary>
/// <param name="_raceData"></param>
/// <returns></returns>
protected bool RaceInIndex(RaceData _raceData)
{
if (UMAContextBase.Instance != null)
{
if (UMAContextBase.Instance.HasRace(_raceData.raceName) != null)
return true;
}
AssetItem ai = UMAAssetIndexer.Instance.GetAssetItem<RaceData>(_raceData.raceName);
if (ai != null)
{
return true;
}
return false;
}
}
/*public class ShowGatheringNotification : EditorWindow
{
string notification = "UMA is gathering Data";
void OnGUI() {
this.ShowNotification(new GUIContent(notification));
}
}*/
}
#endif
| |
//
// AddinInfo.cs
//
// Author:
// Lluis Sanchez Gual
//
// Copyright (C) 2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Collections;
using System.Xml;
using System.Xml.Serialization;
using Mono.Addins.Description;
namespace Mono.Addins.Setup
{
internal class AddinInfo: AddinHeader
{
string id = "";
string namspace = "";
string name = "";
string version = "";
string baseVersion = "";
string author = "";
string copyright = "";
string url = "";
string description = "";
string category = "";
DependencyCollection dependencies;
DependencyCollection optionalDependencies;
AddinPropertyCollectionImpl properties;
public AddinInfo ()
{
dependencies = new DependencyCollection ();
optionalDependencies = new DependencyCollection ();
properties = new AddinPropertyCollectionImpl ();
}
public string Id {
get { return Addin.GetFullId (namspace, id, version); }
}
[XmlElement ("Id")]
public string LocalId {
get { return id; }
set { id = value; }
}
public string Namespace {
get { return namspace; }
set { namspace = value; }
}
public string Name {
get {
string s = Properties.GetPropertyValue ("Name");
if (s.Length > 0)
return s;
if (name != null && name.Length > 0)
return name;
string sid = id;
if (sid.StartsWith ("__"))
sid = sid.Substring (2);
return Addin.GetFullId (namspace, sid, null);
}
set { name = value; }
}
public string Version {
get { return version; }
set { version = value; }
}
public string BaseVersion {
get { return baseVersion; }
set { baseVersion = value; }
}
public string Author {
get {
string s = Properties.GetPropertyValue ("Author");
if (s.Length > 0)
return s;
return author;
}
set { author = value; }
}
public string Copyright {
get {
string s = Properties.GetPropertyValue ("Copyright");
if (s.Length > 0)
return s;
return copyright;
}
set { copyright = value; }
}
public string Url {
get {
string s = Properties.GetPropertyValue ("Url");
if (s.Length > 0)
return s;
return url;
}
set { url = value; }
}
public string Description {
get {
string s = Properties.GetPropertyValue ("Description");
if (s.Length > 0)
return s;
return description;
}
set { description = value; }
}
public string Category {
get {
string s = Properties.GetPropertyValue ("Category");
if (s.Length > 0)
return s;
return category;
}
set { category = value; }
}
[XmlArrayItem ("AddinDependency", typeof(AddinDependency))]
[XmlArrayItem ("NativeDependency", typeof(NativeDependency))]
[XmlArrayItem ("AssemblyDependency", typeof(AssemblyDependency))]
public DependencyCollection Dependencies {
get { return dependencies; }
}
[XmlArrayItem ("AddinDependency", typeof(AddinDependency))]
[XmlArrayItem ("NativeDependency", typeof(NativeDependency))]
[XmlArrayItem ("AssemblyDependency", typeof(AssemblyDependency))]
public DependencyCollection OptionalDependencies {
get { return optionalDependencies; }
}
[XmlArrayItem ("Property", typeof(AddinProperty))]
public AddinPropertyCollectionImpl Properties {
get { return properties; }
}
AddinPropertyCollection AddinHeader.Properties {
get { return properties; }
}
public static AddinInfo ReadFromAddinFile (StreamReader r)
{
XmlDocument doc = new XmlDocument ();
doc.Load (r);
r.Close ();
AddinInfo info = new AddinInfo ();
info.id = doc.DocumentElement.GetAttribute ("id");
info.namspace = doc.DocumentElement.GetAttribute ("namespace");
info.name = doc.DocumentElement.GetAttribute ("name");
if (info.id == "") info.id = info.name;
info.version = doc.DocumentElement.GetAttribute ("version");
info.author = doc.DocumentElement.GetAttribute ("author");
info.copyright = doc.DocumentElement.GetAttribute ("copyright");
info.url = doc.DocumentElement.GetAttribute ("url");
info.description = doc.DocumentElement.GetAttribute ("description");
info.category = doc.DocumentElement.GetAttribute ("category");
info.baseVersion = doc.DocumentElement.GetAttribute ("compatVersion");
AddinPropertyCollectionImpl props = new AddinPropertyCollectionImpl ();
info.properties = props;
ReadHeader (info, props, doc.DocumentElement);
ReadDependencies (info.Dependencies, info.OptionalDependencies, doc.DocumentElement);
return info;
}
static void ReadDependencies (DependencyCollection deps, DependencyCollection opDeps, XmlElement elem)
{
foreach (XmlElement dep in elem.SelectNodes ("Dependencies/Addin")) {
AddinDependency adep = new AddinDependency ();
adep.AddinId = dep.GetAttribute ("id");
string v = dep.GetAttribute ("version");
if (v.Length != 0)
adep.Version = v;
deps.Add (adep);
}
foreach (XmlElement dep in elem.SelectNodes ("Dependencies/Assembly")) {
AssemblyDependency adep = new AssemblyDependency ();
adep.FullName = dep.GetAttribute ("name");
adep.Package = dep.GetAttribute ("package");
deps.Add (adep);
}
foreach (XmlElement mod in elem.SelectNodes ("Module"))
ReadDependencies (opDeps, opDeps, mod);
}
static void ReadHeader (AddinInfo info, AddinPropertyCollectionImpl properties, XmlElement elem)
{
elem = elem.SelectSingleNode ("Header") as XmlElement;
if (elem == null)
return;
foreach (XmlNode xprop in elem.ChildNodes) {
XmlElement prop = xprop as XmlElement;
if (prop != null) {
switch (prop.LocalName) {
case "Id": info.id = prop.InnerText; break;
case "Namespace": info.namspace = prop.InnerText; break;
case "Version": info.version = prop.InnerText; break;
case "CompatVersion": info.baseVersion = prop.InnerText; break;
default: {
AddinProperty aprop = new AddinProperty ();
aprop.Name = prop.LocalName;
if (prop.HasAttribute ("locale"))
aprop.Locale = prop.GetAttribute ("locale");
aprop.Value = prop.InnerText;
properties.Add (aprop);
break;
}}
}
}
}
internal static AddinInfo ReadFromDescription (AddinDescription description)
{
AddinInfo info = new AddinInfo ();
info.id = description.LocalId;
info.namspace = description.Namespace;
info.name = description.Name;
info.version = description.Version;
info.author = description.Author;
info.copyright = description.Copyright;
info.url = description.Url;
info.description = description.Description;
info.category = description.Category;
info.baseVersion = description.CompatVersion;
info.properties = new AddinPropertyCollectionImpl (description.Properties);
foreach (Dependency dep in description.MainModule.Dependencies)
info.Dependencies.Add (dep);
foreach (ModuleDescription mod in description.OptionalModules) {
foreach (Dependency dep in mod.Dependencies)
info.OptionalDependencies.Add (dep);
}
return info;
}
public bool SupportsVersion (string version)
{
if (Addin.CompareVersions (Version, version) > 0)
return false;
if (baseVersion == "")
return true;
return Addin.CompareVersions (BaseVersion, version) >= 0;
}
public int CompareVersionTo (AddinHeader other)
{
return Addin.CompareVersions (this.version, other.Version);
}
}
/// <summary>
/// Basic add-in information
/// </summary>
public interface AddinHeader
{
/// <summary>
/// Full identifier of the add-in
/// </summary>
string Id {
get;
}
/// <summary>
/// Display name of the add-in
/// </summary>
string Name {
get;
}
/// <summary>
/// Namespace of the add-in
/// </summary>
string Namespace {
get;
}
/// <summary>
/// Version of the add-in
/// </summary>
string Version {
get;
}
/// <summary>
/// Version with which this add-in is compatible
/// </summary>
string BaseVersion {
get;
}
/// <summary>
/// Add-in author
/// </summary>
string Author {
get;
}
/// <summary>
/// Add-in copyright
/// </summary>
string Copyright {
get;
}
/// <summary>
/// Web page URL with more information about the add-in
/// </summary>
string Url {
get;
}
/// <summary>
/// Description of the add-in
/// </summary>
string Description {
get;
}
/// <summary>
/// Category of the add-in
/// </summary>
string Category {
get;
}
/// <summary>
/// Dependencies of the add-in
/// </summary>
DependencyCollection Dependencies {
get;
}
/// <summary>
/// Optional dependencies of the add-in
/// </summary>
DependencyCollection OptionalDependencies {
get;
}
/// <summary>
/// Custom properties specified in the add-in header
/// </summary>
AddinPropertyCollection Properties {
get;
}
/// <summary>
/// Compares the versions of two add-ins
/// </summary>
/// <param name="other">
/// Another add-in
/// </param>
/// <returns>
/// Result of comparison
/// </returns>
int CompareVersionTo (AddinHeader other);
}
}
| |
// 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\General\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.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithElementByte0()
{
var test = new VectorGetAndWithElement__GetAndWithElementByte0();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
// Validates that invalid indices throws ArgumentOutOfRangeException
test.RunArgumentOutOfRangeScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithElement__GetAndWithElementByte0
{
private static readonly int LargestVectorSize = 8;
private static readonly int ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario(int imm = 0, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Byte[] values = new Byte[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetByte();
}
Vector64<Byte> value = Vector64.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
bool succeeded = !expectedOutOfRangeException;
try
{
Byte result = value.GetElement(imm);
ValidateGetResult(result, values);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<Byte.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
Byte insertedValue = TestLibrary.Generator.GetByte();
try
{
Vector64<Byte> result2 = value.WithElement(imm, insertedValue);
ValidateWithResult(result2, values, insertedValue);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<Byte.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunReflectionScenario(int imm = 0, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Byte[] values = new Byte[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetByte();
}
Vector64<Byte> value = Vector64.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
bool succeeded = !expectedOutOfRangeException;
try
{
object result = typeof(Vector64)
.GetMethod(nameof(Vector64.GetElement))
.MakeGenericMethod(typeof(Byte))
.Invoke(null, new object[] { value, imm });
ValidateGetResult((Byte)(result), values);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<Byte.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
Byte insertedValue = TestLibrary.Generator.GetByte();
try
{
object result2 = typeof(Vector64)
.GetMethod(nameof(Vector64.WithElement))
.MakeGenericMethod(typeof(Byte))
.Invoke(null, new object[] { value, imm, insertedValue });
ValidateWithResult((Vector64<Byte>)(result2), values, insertedValue);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<Byte.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunArgumentOutOfRangeScenario()
{
RunBasicScenario(0 - ElementCount, expectedOutOfRangeException: true);
RunBasicScenario(0 + ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(0 - ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(0 + ElementCount, expectedOutOfRangeException: true);
}
private void ValidateGetResult(Byte result, Byte[] values, [CallerMemberName] string method = "")
{
if (result != values[0])
{
Succeeded = false;
TestLibrary.TestFramework.LogInformation($"Vector64<Byte.GetElement(0): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
private void ValidateWithResult(Vector64<Byte> result, Byte[] values, Byte insertedValue, [CallerMemberName] string method = "")
{
Byte[] resultElements = new Byte[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, insertedValue, method);
}
private void ValidateWithResult(Byte[] result, Byte[] values, Byte insertedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if ((i != 0) && (result[i] != values[i]))
{
succeeded = false;
break;
}
}
if (result[0] != insertedValue)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<Byte.WithElement(0): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" insert: insertedValue");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Nuke.Common;
using Nuke.Common.Git;
using Nuke.Common.ProjectModel;
using Nuke.Common.Tooling;
using Nuke.Common.Tools.DotNet;
using Nuke.Common.Tools.MSBuild;
using Nuke.Common.Tools.Npm;
using Nuke.Common.Utilities;
using Nuke.Common.Utilities.Collections;
using static Nuke.Common.EnvironmentInfo;
using static Nuke.Common.IO.FileSystemTasks;
using static Nuke.Common.IO.PathConstruction;
using static Nuke.Common.Tools.MSBuild.MSBuildTasks;
using static Nuke.Common.Tools.DotNet.DotNetTasks;
using static Nuke.Common.Tools.Xunit.XunitTasks;
using static Nuke.Common.Tools.VSWhere.VSWhereTasks;
/*
Before editing this file, install support plugin for your IDE,
running and debugging a particular target (optionally without deps) would be way easier
ReSharper/Rider - https://plugins.jetbrains.com/plugin/10803-nuke-support
VSCode - https://marketplace.visualstudio.com/items?itemName=nuke.support
*/
partial class Build : NukeBuild
{
[Solution("Avalonia.sln")] readonly Solution Solution;
static Lazy<string> MsBuildExe = new Lazy<string>(() =>
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
return null;
var msBuildDirectory = VSWhere("-latest -nologo -property installationPath -format value -prerelease").FirstOrDefault().Text;
if (!string.IsNullOrWhiteSpace(msBuildDirectory))
{
string msBuildExe = Path.Combine(msBuildDirectory, @"MSBuild\Current\Bin\MSBuild.exe");
if (!System.IO.File.Exists(msBuildExe))
msBuildExe = Path.Combine(msBuildDirectory, @"MSBuild\15.0\Bin\MSBuild.exe");
return msBuildExe;
}
return null;
}, false);
BuildParameters Parameters { get; set; }
protected override void OnBuildInitialized()
{
Parameters = new BuildParameters(this);
Information("Building version {0} of Avalonia ({1}) using version {2} of Nuke.",
Parameters.Version,
Parameters.Configuration,
typeof(NukeBuild).Assembly.GetName().Version.ToString());
if (Parameters.IsLocalBuild)
{
Information("Repository Name: " + Parameters.RepositoryName);
Information("Repository Branch: " + Parameters.RepositoryBranch);
}
Information("Configuration: " + Parameters.Configuration);
Information("IsLocalBuild: " + Parameters.IsLocalBuild);
Information("IsRunningOnUnix: " + Parameters.IsRunningOnUnix);
Information("IsRunningOnWindows: " + Parameters.IsRunningOnWindows);
Information("IsRunningOnAzure:" + Parameters.IsRunningOnAzure);
Information("IsPullRequest: " + Parameters.IsPullRequest);
Information("IsMainRepo: " + Parameters.IsMainRepo);
Information("IsMasterBranch: " + Parameters.IsMasterBranch);
Information("IsReleaseBranch: " + Parameters.IsReleaseBranch);
Information("IsReleasable: " + Parameters.IsReleasable);
Information("IsMyGetRelease: " + Parameters.IsMyGetRelease);
Information("IsNuGetRelease: " + Parameters.IsNuGetRelease);
void ExecWait(string preamble, string command, string args)
{
Console.WriteLine(preamble);
Process.Start(new ProcessStartInfo(command, args) {UseShellExecute = false}).WaitForExit();
}
ExecWait("dotnet version:", "dotnet", "--version");
}
IReadOnlyCollection<Output> MsBuildCommon(
string projectFile,
Configure<MSBuildSettings> configurator = null)
{
return MSBuild(c => c
.SetProjectFile(projectFile)
// This is required for VS2019 image on Azure Pipelines
.When(Parameters.IsRunningOnWindows &&
Parameters.IsRunningOnAzure, _ => _
.AddProperty("JavaSdkDirectory", GetVariable<string>("JAVA_HOME_8_X64")))
.AddProperty("PackageVersion", Parameters.Version)
.AddProperty("iOSRoslynPathHackRequired", true)
.SetProcessToolPath(MsBuildExe.Value)
.SetConfiguration(Parameters.Configuration)
.SetVerbosity(MSBuildVerbosity.Minimal)
.Apply(configurator));
}
Target Clean => _ => _.Executes(() =>
{
Parameters.BuildDirs.ForEach(DeleteDirectory);
Parameters.BuildDirs.ForEach(EnsureCleanDirectory);
EnsureCleanDirectory(Parameters.ArtifactsDir);
EnsureCleanDirectory(Parameters.NugetIntermediateRoot);
EnsureCleanDirectory(Parameters.NugetRoot);
EnsureCleanDirectory(Parameters.ZipRoot);
EnsureCleanDirectory(Parameters.TestResultsRoot);
});
Target CompileHtmlPreviewer => _ => _
.DependsOn(Clean)
.OnlyWhenStatic(() => !Parameters.SkipPreviewer)
.Executes(() =>
{
var webappDir = RootDirectory / "src" / "Avalonia.DesignerSupport" / "Remote" / "HtmlTransport" / "webapp";
NpmTasks.NpmInstall(c => c
.SetProcessWorkingDirectory(webappDir)
.SetProcessArgumentConfigurator(a => a.Add("--silent")));
NpmTasks.NpmRun(c => c
.SetProcessWorkingDirectory(webappDir)
.SetCommand("dist"));
});
Target CompileNative => _ => _
.DependsOn(Clean)
.DependsOn(GenerateCppHeaders)
.OnlyWhenStatic(() => EnvironmentInfo.IsOsx)
.Executes(() =>
{
var project = $"{RootDirectory}/native/Avalonia.Native/src/OSX/Avalonia.Native.OSX.xcodeproj/";
var args = $"-project {project} -configuration {Parameters.Configuration} CONFIGURATION_BUILD_DIR={RootDirectory}/Build/Products/Release";
ProcessTasks.StartProcess("xcodebuild", args).AssertZeroExitCode();
});
Target Compile => _ => _
.DependsOn(Clean, CompileNative)
.DependsOn(CompileHtmlPreviewer)
.Executes(async () =>
{
if (Parameters.IsRunningOnWindows)
MsBuildCommon(Parameters.MSBuildSolution, c => c
.SetProcessArgumentConfigurator(a => a.Add("/r"))
.AddTargets("Build")
);
else
DotNetBuild(c => c
.SetProjectFile(Parameters.MSBuildSolution)
.AddProperty("PackageVersion", Parameters.Version)
.SetConfiguration(Parameters.Configuration)
);
});
void RunCoreTest(string projectName)
{
Information($"Running tests from {projectName}");
var project = Solution.GetProject(projectName).NotNull("project != null");
foreach (var fw in project.GetTargetFrameworks())
{
if (fw.StartsWith("net4")
&& RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
&& Environment.GetEnvironmentVariable("FORCE_LINUX_TESTS") != "1")
{
Information($"Skipping {projectName} ({fw}) tests on Linux - https://github.com/mono/mono/issues/13969");
continue;
}
Information($"Running for {projectName} ({fw}) ...");
DotNetTest(c => c
.SetProjectFile(project)
.SetConfiguration(Parameters.Configuration)
.SetFramework(fw)
.EnableNoBuild()
.EnableNoRestore()
.When(Parameters.PublishTestResults, _ => _
.SetLogger("trx")
.SetResultsDirectory(Parameters.TestResultsRoot)));
}
}
Target RunHtmlPreviewerTests => _ => _
.DependsOn(CompileHtmlPreviewer)
.OnlyWhenStatic(() => !(Parameters.SkipPreviewer || Parameters.SkipTests))
.Executes(() =>
{
var webappTestDir = RootDirectory / "tests" / "Avalonia.DesignerSupport.Tests" / "Remote" / "HtmlTransport" / "webapp";
NpmTasks.NpmInstall(c => c
.SetProcessWorkingDirectory(webappTestDir)
.SetProcessArgumentConfigurator(a => a.Add("--silent")));
NpmTasks.NpmRun(c => c
.SetProcessWorkingDirectory(webappTestDir)
.SetCommand("test"));
});
Target RunCoreLibsTests => _ => _
.OnlyWhenStatic(() => !Parameters.SkipTests)
.DependsOn(Compile)
.Executes(() =>
{
RunCoreTest("Avalonia.Animation.UnitTests");
RunCoreTest("Avalonia.Base.UnitTests");
RunCoreTest("Avalonia.Controls.UnitTests");
RunCoreTest("Avalonia.Controls.DataGrid.UnitTests");
RunCoreTest("Avalonia.Input.UnitTests");
RunCoreTest("Avalonia.Interactivity.UnitTests");
RunCoreTest("Avalonia.Layout.UnitTests");
RunCoreTest("Avalonia.Markup.UnitTests");
RunCoreTest("Avalonia.Markup.Xaml.UnitTests");
RunCoreTest("Avalonia.Styling.UnitTests");
RunCoreTest("Avalonia.Visuals.UnitTests");
RunCoreTest("Avalonia.Skia.UnitTests");
RunCoreTest("Avalonia.ReactiveUI.UnitTests");
});
Target RunRenderTests => _ => _
.OnlyWhenStatic(() => !Parameters.SkipTests)
.DependsOn(Compile)
.Executes(() =>
{
RunCoreTest("Avalonia.Skia.RenderTests");
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
RunCoreTest("Avalonia.Direct2D1.RenderTests");
});
Target RunDesignerTests => _ => _
.OnlyWhenStatic(() => !Parameters.SkipTests && Parameters.IsRunningOnWindows)
.DependsOn(Compile)
.Executes(() =>
{
RunCoreTest("Avalonia.DesignerSupport.Tests");
});
[PackageExecutable("JetBrains.dotMemoryUnit", "dotMemoryUnit.exe")] readonly Tool DotMemoryUnit;
Target RunLeakTests => _ => _
.OnlyWhenStatic(() => !Parameters.SkipTests && Parameters.IsRunningOnWindows)
.DependsOn(Compile)
.Executes(() =>
{
void DoMemoryTest()
{
var testAssembly = "tests\\Avalonia.LeakTests\\bin\\Release\\net461\\Avalonia.LeakTests.dll";
DotMemoryUnit(
$"{XunitPath.DoubleQuoteIfNeeded()} --propagate-exit-code -- {testAssembly}",
timeout: 120_000);
}
ControlFlow.ExecuteWithRetry(DoMemoryTest, waitInSeconds: 3);
});
Target ZipFiles => _ => _
.After(CreateNugetPackages, Compile, RunCoreLibsTests, Package)
.Executes(() =>
{
var data = Parameters;
var pathToProjectSource = RootDirectory / "samples" / "ControlCatalog.NetCore";
var pathToPublish = pathToProjectSource / "bin" / data.Configuration / "publish";
DotNetPublish(c => c
.SetProject(pathToProjectSource / "ControlCatalog.NetCore.csproj")
.EnableNoBuild()
.SetConfiguration(data.Configuration)
.AddProperty("PackageVersion", data.Version)
.AddProperty("PublishDir", pathToPublish));
Zip(data.ZipCoreArtifacts, data.BinRoot);
Zip(data.ZipNuGetArtifacts, data.NugetRoot);
Zip(data.ZipTargetControlCatalogNetCoreDir, pathToPublish);
});
Target CreateIntermediateNugetPackages => _ => _
.DependsOn(Compile)
.After(RunTests)
.Executes(() =>
{
if (Parameters.IsRunningOnWindows)
MsBuildCommon(Parameters.MSBuildSolution, c => c
.AddTargets("Pack"));
else
DotNetPack(c => c
.SetProject(Parameters.MSBuildSolution)
.SetConfiguration(Parameters.Configuration)
.AddProperty("PackageVersion", Parameters.Version));
});
Target CreateNugetPackages => _ => _
.DependsOn(CreateIntermediateNugetPackages)
.Executes(() =>
{
BuildTasksPatcher.PatchBuildTasksInPackage(Parameters.NugetIntermediateRoot / "Avalonia.Build.Tasks." +
Parameters.Version + ".nupkg");
var config = Numerge.MergeConfiguration.LoadFile(RootDirectory / "nukebuild" / "numerge.config");
EnsureCleanDirectory(Parameters.NugetRoot);
if(!Numerge.NugetPackageMerger.Merge(Parameters.NugetIntermediateRoot, Parameters.NugetRoot, config,
new NumergeNukeLogger()))
throw new Exception("Package merge failed");
});
Target RunTests => _ => _
.DependsOn(RunCoreLibsTests)
.DependsOn(RunRenderTests)
.DependsOn(RunDesignerTests)
.DependsOn(RunHtmlPreviewerTests)
.DependsOn(RunLeakTests);
Target Package => _ => _
.DependsOn(RunTests)
.DependsOn(CreateNugetPackages);
Target CiAzureLinux => _ => _
.DependsOn(RunTests);
Target CiAzureOSX => _ => _
.DependsOn(Package)
.DependsOn(ZipFiles);
Target CiAzureWindows => _ => _
.DependsOn(Package)
.DependsOn(ZipFiles);
public static int Main() =>
RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? Execute<Build>(x => x.Package)
: Execute<Build>(x => x.RunTests);
}
public static class ToolSettingsExtensions
{
public static T Apply<T>(this T settings, Configure<T> configurator)
{
return configurator != null ? configurator(settings) : settings;
}
}
| |
// Copyright (C) 2014 - 2016 Stephan Bouchard - All Rights Reserved
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace TMPro
{
/// <summary>
/// Contains the font asset for the specified font weight styles.
/// </summary>
[Serializable]
public struct TMP_FontWeights
{
public TMP_FontAsset regularTypeface;
public TMP_FontAsset italicTypeface;
}
[Serializable]
public class TMP_FontAsset : TMP_Asset
{
/// <summary>
/// Default Font Asset used as last resort when glyphs are missing.
/// </summary>
public static TMP_FontAsset defaultFontAsset
{
get
{
if (s_defaultFontAsset == null)
{
s_defaultFontAsset = Resources.Load<TMP_FontAsset>("Fonts & Materials/ARIAL SDF");
}
return s_defaultFontAsset;
}
}
private static TMP_FontAsset s_defaultFontAsset;
public enum FontAssetTypes { None = 0, SDF = 1, Bitmap = 2 };
public FontAssetTypes fontAssetType;
/// <summary>
/// The general information about the font.
/// </summary>
public FaceInfo fontInfo
{ get { return m_fontInfo; } }
[SerializeField]
private FaceInfo m_fontInfo;
[SerializeField]
public Texture2D atlas; // Should add a property to make this read-only.
// Glyph Info
[SerializeField]
private List<TMP_Glyph> m_glyphInfoList;
public Dictionary<int, TMP_Glyph> characterDictionary
{
get
{
if (m_characterDictionary == null)
ReadFontDefinition();
return m_characterDictionary;
}
}
private Dictionary<int, TMP_Glyph> m_characterDictionary;
// Kerning
public Dictionary<int, KerningPair> kerningDictionary
{ get { return m_kerningDictionary; } }
private Dictionary<int, KerningPair> m_kerningDictionary;
public KerningTable kerningInfo
{ get { return m_kerningInfo; } }
[SerializeField]
private KerningTable m_kerningInfo;
[SerializeField]
#pragma warning disable 0169 // Property is used to create an empty Kerning Pair in the editor.
private KerningPair m_kerningPair; // Used for creating a new kerning pair in Editor Panel.
/// <summary>
/// List which contains the Fallback font assets for this font.
/// </summary>
[SerializeField]
public List<TMP_FontAsset> fallbackFontAssets;
// TODO : Not implemented yet.
[SerializeField]
public FontCreationSetting fontCreationSettings;
// FONT WEIGHTS
[SerializeField]
public TMP_FontWeights[] fontWeights = new TMP_FontWeights[10];
private int[] m_characterSet; // Array containing all the characters in this font asset.
public float normalStyle = 0;
public float normalSpacingOffset = 0;
public float boldStyle = 0.75f;
public float boldSpacing = 7f;
public byte italicStyle = 35;
public byte tabSize = 10;
private byte m_oldTabSize;
void OnEnable()
{
//Debug.Log("OnEnable has been called on " + this.name);
}
void OnDisable()
{
//Debug.Log("TextMeshPro Font Asset [" + this.name + "] has been disabled!");
}
#if UNITY_EDITOR
/// <summary>
///
/// </summary>
void OnValidate()
{
if (m_oldTabSize != tabSize)
{
m_oldTabSize = tabSize;
ReadFontDefinition();
}
}
#endif
/// <summary>
///
/// </summary>
/// <param name="faceInfo"></param>
public void AddFaceInfo(FaceInfo faceInfo)
{
m_fontInfo = faceInfo;
}
/// <summary>
///
/// </summary>
/// <param name="glyphInfo"></param>
public void AddGlyphInfo(TMP_Glyph[] glyphInfo)
{
m_glyphInfoList = new List<TMP_Glyph>();
int characterCount = glyphInfo.Length;
m_fontInfo.CharacterCount = characterCount;
m_characterSet = new int[characterCount];
for (int i = 0; i < characterCount; i++)
{
TMP_Glyph g = new TMP_Glyph();
g.id = glyphInfo[i].id;
g.x = glyphInfo[i].x;
g.y = glyphInfo[i].y;
g.width = glyphInfo[i].width;
g.height = glyphInfo[i].height;
g.xOffset = glyphInfo[i].xOffset;
g.yOffset = (glyphInfo[i].yOffset);
g.xAdvance = glyphInfo[i].xAdvance;
g.scale = 1;
m_glyphInfoList.Add(g);
// While iterating through list of glyphs, find the Descender & Ascender for this GlyphSet.
//m_fontInfo.Ascender = Mathf.Max(m_fontInfo.Ascender, glyphInfo[i].yOffset);
//m_fontInfo.Descender = Mathf.Min(m_fontInfo.Descender, glyphInfo[i].yOffset - glyphInfo[i].height);
//Debug.Log(m_fontInfo.Ascender + " " + m_fontInfo.Descender);
m_characterSet[i] = g.id; // Add Character ID to Array to make it easier to get the kerning pairs.
}
// Sort List by ID.
m_glyphInfoList = m_glyphInfoList.OrderBy(s => s.id).ToList();
}
/// <summary>
///
/// </summary>
/// <param name="kerningTable"></param>
public void AddKerningInfo(KerningTable kerningTable)
{
m_kerningInfo = kerningTable;
}
/// <summary>
///
/// </summary>
public void ReadFontDefinition()
{
//Debug.Log("Reading Font Definition for " + this.name + ".");
// Make sure that we have a Font Asset file assigned.
if (m_fontInfo == null)
{
return;
}
// Check Font Asset type
//Debug.Log(name + " " + fontAssetType);
// Create new instance of GlyphInfo Dictionary for fast access to glyph info.
m_characterDictionary = new Dictionary<int, TMP_Glyph>();
for (int i = 0; i < m_glyphInfoList.Count; i++)
{
TMP_Glyph glyph = m_glyphInfoList[i];
if (!m_characterDictionary.ContainsKey(glyph.id))
m_characterDictionary.Add(glyph.id, glyph);
// Compatibility
if (glyph.scale == 0) glyph.scale = 1;
}
//Debug.Log("PRE: BaseLine:" + m_fontInfo.Baseline + " Ascender:" + m_fontInfo.Ascender + " Descender:" + m_fontInfo.Descender); // + " Centerline:" + m_fontInfo.CenterLine);
TMP_Glyph temp_charInfo = new TMP_Glyph();
// Add Character (10) LineFeed, (13) Carriage Return & Space (32) to Dictionary if they don't exists.
if (m_characterDictionary.ContainsKey(32))
{
m_characterDictionary[32].width = m_characterDictionary[32].xAdvance; // m_fontInfo.Ascender / 5;
m_characterDictionary[32].height = m_fontInfo.Ascender - m_fontInfo.Descender;
m_characterDictionary[32].yOffset= m_fontInfo.Ascender;
m_characterDictionary[32].scale = 1;
}
else
{
//Debug.Log("Adding Character 32 (Space) to Dictionary for Font (" + m_fontInfo.Name + ").");
temp_charInfo = new TMP_Glyph();
temp_charInfo.id = 32;
temp_charInfo.x = 0;
temp_charInfo.y = 0;
temp_charInfo.width = m_fontInfo.Ascender / 5;
temp_charInfo.height = m_fontInfo.Ascender - m_fontInfo.Descender;
temp_charInfo.xOffset = 0;
temp_charInfo.yOffset = m_fontInfo.Ascender;
temp_charInfo.xAdvance = m_fontInfo.PointSize / 4;
temp_charInfo.scale = 1;
m_characterDictionary.Add(32, temp_charInfo);
}
// Add Non-Breaking Space (160)
if (!m_characterDictionary.ContainsKey(160))
{
temp_charInfo = TMP_Glyph.Clone(m_characterDictionary[32]);
m_characterDictionary.Add(160, temp_charInfo);
}
// Add Zero Width Space (8203)
if (!m_characterDictionary.ContainsKey(8203))
{
temp_charInfo = TMP_Glyph.Clone(m_characterDictionary[32]);
temp_charInfo.width = 0;
temp_charInfo.xAdvance = 0;
m_characterDictionary.Add(8203, temp_charInfo);
}
//Add Zero Width no-break space (8288)
if (!m_characterDictionary.ContainsKey(8288))
{
temp_charInfo = TMP_Glyph.Clone(m_characterDictionary[32]);
temp_charInfo.width = 0;
temp_charInfo.xAdvance = 0;
m_characterDictionary.Add(8288, temp_charInfo);
}
// Add Linefeed (10)
if (m_characterDictionary.ContainsKey(10) == false)
{
//Debug.Log("Adding Character 10 (Linefeed) to Dictionary for Font (" + m_fontInfo.Name + ").");
temp_charInfo = new TMP_Glyph();
temp_charInfo.id = 10;
temp_charInfo.x = 0; // m_characterDictionary[32].x;
temp_charInfo.y = 0; // m_characterDictionary[32].y;
temp_charInfo.width = 10; // m_characterDictionary[32].width;
temp_charInfo.height = m_characterDictionary[32].height;
temp_charInfo.xOffset = 0; // m_characterDictionary[32].xOffset;
temp_charInfo.yOffset = m_characterDictionary[32].yOffset;
temp_charInfo.xAdvance = 0;
temp_charInfo.scale = 1;
m_characterDictionary.Add(10, temp_charInfo);
if (!m_characterDictionary.ContainsKey(13))
m_characterDictionary.Add(13, temp_charInfo);
}
// Add Tab Character to Dictionary. Tab is Tab Size * Space Character Width.
if (m_characterDictionary.ContainsKey(9) == false)
{
//Debug.Log("Adding Character 9 (Tab) to Dictionary for Font (" + m_fontInfo.Name + ").");
temp_charInfo = new TMP_Glyph();
temp_charInfo.id = 9;
temp_charInfo.x = m_characterDictionary[32].x;
temp_charInfo.y = m_characterDictionary[32].y;
temp_charInfo.width = m_characterDictionary[32].width * tabSize + (m_characterDictionary[32].xAdvance - m_characterDictionary[32].width) * (tabSize - 1);
temp_charInfo.height = m_characterDictionary[32].height;
temp_charInfo.xOffset = m_characterDictionary[32].xOffset;
temp_charInfo.yOffset = m_characterDictionary[32].yOffset;
temp_charInfo.xAdvance = m_characterDictionary[32].xAdvance * tabSize;
temp_charInfo.scale = 1;
m_characterDictionary.Add(9, temp_charInfo);
}
// Centerline is located at the center of character like { or in the middle of the lowercase o.
//m_fontInfo.CenterLine = m_characterDictionary[111].yOffset - m_characterDictionary[111].height * 0.5f;
// Tab Width is using the same xAdvance as space (32).
m_fontInfo.TabWidth = m_characterDictionary[9].xAdvance;
// Set Cap Height
if (m_fontInfo.CapHeight == 0 && m_characterDictionary.ContainsKey(65))
m_fontInfo.CapHeight = m_characterDictionary[65].yOffset;
// Adjust Font Scale for compatibility reasons
if (m_fontInfo.Scale == 0)
m_fontInfo.Scale = 1.0f;
// Populate Dictionary with Kerning Information
m_kerningDictionary = new Dictionary<int, KerningPair>();
List<KerningPair> pairs = m_kerningInfo.kerningPairs;
//Debug.Log(m_fontInfo.Name + " has " + pairs.Count + " Kerning Pairs.");
for (int i = 0; i < pairs.Count; i++)
{
KerningPair pair = pairs[i];
KerningPairKey uniqueKey = new KerningPairKey(pair.AscII_Left, pair.AscII_Right);
if (m_kerningDictionary.ContainsKey(uniqueKey.key) == false)
m_kerningDictionary.Add(uniqueKey.key, pair);
else
{
if (!TMP_Settings.warningsDisabled)
Debug.LogWarning("Kerning Key for [" + uniqueKey.ascii_Left + "] and [" + uniqueKey.ascii_Right + "] already exists.");
}
}
// Compute Hashcode for the font asset name
hashCode = TMP_TextUtilities.GetSimpleHashCode(this.name);
// Compute Hashcode for the material name
materialHashCode = TMP_TextUtilities.GetSimpleHashCode(material.name);
// Initialize Font Weights if needed
//InitializeFontWeights();
}
/// <summary>
/// Function to check if a certain character exists in the font asset.
/// </summary>
/// <param name="character"></param>
/// <returns></returns>
public bool HasCharacter(int character)
{
if (m_characterDictionary == null)
return false;
if (m_characterDictionary.ContainsKey(character))
return true;
return false;
}
/// <summary>
/// Function to check if a certain character exists in the font asset.
/// </summary>
/// <param name="character"></param>
/// <returns></returns>
public bool HasCharacter(char character)
{
if (m_characterDictionary == null)
return false;
if (m_characterDictionary.ContainsKey(character))
return true;
return false;
}
/// <summary>
/// Function to check if a character is contained in a font asset with the option to also check through fallback font assets.
/// </summary>
/// <param name="character"></param>
/// <param name="searchFallbacks"></param>
/// <returns></returns>
public bool HasCharacter(char character, bool searchFallbacks)
{
if (m_characterDictionary == null)
return false;
// Check font asset
if (m_characterDictionary.ContainsKey(character))
return true;
if (searchFallbacks)
{
// Check Font Asset Fallback fonts.
if (fallbackFontAssets != null && fallbackFontAssets.Count > 0)
{
for (int i = 0; i < fallbackFontAssets.Count; i++)
{
if (fallbackFontAssets[i].characterDictionary != null && fallbackFontAssets[i].characterDictionary.ContainsKey(character))
return true;
}
}
// Check general fallback font assets.
if (TMP_Settings.fallbackFontAssets != null && TMP_Settings.fallbackFontAssets.Count > 0)
{
for (int i = 0; i < TMP_Settings.fallbackFontAssets.Count; i++)
{
if (TMP_Settings.fallbackFontAssets[i].characterDictionary != null && TMP_Settings.fallbackFontAssets[i].characterDictionary.ContainsKey(character))
return true;
}
}
}
return false;
}
/// <summary>
/// Function to check if certain characters exists in the font asset. Function returns a list of missing characters.
/// </summary>
/// <param name="character"></param>
/// <returns></returns>
public bool HasCharacters(string text, out List<char> missingCharacters)
{
if (m_characterDictionary == null)
{
missingCharacters = null;
return false;
}
missingCharacters = new List<char>();
for (int i = 0; i < text.Length; i++)
{
if (!m_characterDictionary.ContainsKey(text[i]))
missingCharacters.Add(text[i]);
}
if (missingCharacters.Count == 0)
return true;
return false;
}
/// <summary>
/// Function to extract all the characters from a font asset.
/// </summary>
/// <param name="fontAsset"></param>
/// <returns></returns>
public static string GetCharacters(TMP_FontAsset fontAsset)
{
string characters = string.Empty;
for (int i = 0; i < fontAsset.m_glyphInfoList.Count; i++)
{
characters += (char)fontAsset.m_glyphInfoList[i].id;
}
return characters;
}
/// <summary>
/// Function which returns an array that contains all the characters from a font asset.
/// </summary>
/// <param name="fontAsset"></param>
/// <returns></returns>
public static int[] GetCharactersArray(TMP_FontAsset fontAsset)
{
int[] characters = new int[fontAsset.m_glyphInfoList.Count];
for (int i = 0; i < fontAsset.m_glyphInfoList.Count; i++)
{
characters[i] = fontAsset.m_glyphInfoList[i].id;
}
return characters;
}
}
}
| |
using System;
using System.Threading.Tasks;
using FakeItEasy;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace M.Executables.Executors.NetCore.UnitTests
{
public class NetCoreExecutorAsyncTests
{
[Fact]
public async Task ExecuteAsync_IsCalledOnVoidExecutable()
{
var executable = A.Fake<IExecutableVoidAsync>();
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutorAsync>();
await executor.ExecuteAsync<IExecutableVoidAsync>().ConfigureAwait(false);
A.CallTo(() => executable.ExecuteAsync()).MustHaveHappenedOnceExactly();
}
[Fact]
public async Task ExecuteAsync_IsCalledOnVoidExecutableWithParameter()
{
var executable = A.Fake<IExecutableVoidAsync<string>>();
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutorAsync>();
await executor.ExecuteAsync<IExecutableVoidAsync<string>, string>("parameter hello").ConfigureAwait(false);
A.CallTo(() => executable.ExecuteAsync("parameter hello")).MustHaveHappenedOnceExactly();
}
[Fact]
public async Task ExecuteAsync_IsCalledOnExecutable()
{
var executable = A.Fake<IExecutableAsync<string>>();
A.CallTo(() => executable.ExecuteAsync()).Returns("return value hello");
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutorAsync>();
var result = await executor.ExecuteAsync<IExecutableAsync<string>, string>().ConfigureAwait(false);
A.CallTo(() => executable.ExecuteAsync()).MustHaveHappenedOnceExactly();
Assert.Equal("return value hello", result);
}
[Fact]
public async Task ExecuteAsync_IsCalledOnExecutableWithParameter()
{
var executable = A.Fake<IExecutableAsync<string, string>>();
A.CallTo(() => executable.ExecuteAsync("parameter hello")).Returns("return value hello");
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutorAsync>();
var result = await executor.ExecuteAsync<IExecutableAsync<string, string>, string, string>("parameter hello").ConfigureAwait(false);
A.CallTo(() => executable.ExecuteAsync("parameter hello")).MustHaveHappenedOnceExactly();
Assert.Equal("return value hello", result);
}
[Fact]
public async Task ExecuteAsync_InterceptorsAreCalledInOrder()
{
var executable = A.Fake<IExecutableAsync<string, string>>();
A.CallTo(() => executable.ExecuteAsync("parameter hello")).Returns("return value hello");
var generalInterceptor1 = A.Fake<IExecutionInterceptorAsync>();
A.CallTo(() => generalInterceptor1.OrderingIndex).Returns(1);
var generalInterceptor2 = A.Fake<IExecutionInterceptorAsync>();
A.CallTo(() => generalInterceptor2.OrderingIndex).Returns(3);
var specificInterceptor = A.Fake<IExecutionInterceptorAsync<IExecutableAsync<string, string>, string, string>>();
A.CallTo(() => specificInterceptor.OrderingIndex).Returns(2);
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).AddSpecificInterceptors(specificInterceptor).AddGeneralInterceptors(generalInterceptor1, generalInterceptor2).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutorAsync>();
var result = await executor.ExecuteAsync<IExecutableAsync<string, string>, string, string>("parameter hello").ConfigureAwait(false);
Assert.Equal("return value hello", result);
// interceptors called in ascending OrderIndex order
A.CallTo(() => generalInterceptor1.BeforeAsync(executable, "parameter hello")).MustHaveHappenedOnceExactly()
.Then(A.CallTo(() => specificInterceptor.BeforeAsync(executable, "parameter hello")).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => generalInterceptor2.BeforeAsync(executable, "parameter hello")).MustHaveHappenedOnceExactly())
// executable called
.Then(A.CallTo(() => executable.ExecuteAsync("parameter hello")).MustHaveHappenedOnceExactly())
// interceptors called in descending OrderIndex order
.Then(A.CallTo(() => generalInterceptor2.AfterAsync(executable, "parameter hello", "return value hello", null)).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => specificInterceptor.AfterAsync(executable, "parameter hello", "return value hello", null)).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => generalInterceptor1.AfterAsync(executable, "parameter hello", "return value hello", null)).MustHaveHappenedOnceExactly());
}
[Fact]
public async Task ExecuteAsync_ExceptionIsPassedToInterceptors()
{
var executable = A.Fake<IExecutableAsync<string, string>>();
var exception = new InvalidOperationException();
A.CallTo(() => executable.ExecuteAsync("parameter hello")).ThrowsAsync(exception);
var generalInterceptor1 = A.Fake<IExecutionInterceptorAsync>();
A.CallTo(() => generalInterceptor1.OrderingIndex).Returns(1);
var generalInterceptor2 = A.Fake<IExecutionInterceptorAsync>();
A.CallTo(() => generalInterceptor2.OrderingIndex).Returns(3);
var specificInterceptor = A.Fake<IExecutionInterceptorAsync<IExecutableAsync<string, string>, string, string>>();
A.CallTo(() => specificInterceptor.OrderingIndex).Returns(2);
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).AddSpecificInterceptors(specificInterceptor).AddGeneralInterceptors(generalInterceptor1, generalInterceptor2).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutorAsync>();
_ = await Assert.ThrowsAsync(exception.GetType(), () => executor.ExecuteAsync<IExecutableAsync<string, string>, string, string>("parameter hello")).ConfigureAwait(false);
// interceptors called in ascending OrderIndex order
_ = A.CallTo(() => generalInterceptor1.BeforeAsync(executable, "parameter hello")).MustHaveHappenedOnceExactly()
.Then(A.CallTo(() => specificInterceptor.BeforeAsync(executable, "parameter hello")).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => generalInterceptor2.BeforeAsync(executable, "parameter hello")).MustHaveHappenedOnceExactly())
// executable called
.Then(A.CallTo(() => executable.ExecuteAsync("parameter hello")).MustHaveHappenedOnceExactly())
// interceptors called in descending OrderIndex order
.Then(A.CallTo(() => generalInterceptor2.AfterAsync(executable, "parameter hello", default(string), exception)).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => specificInterceptor.AfterAsync(executable, "parameter hello", default(string), exception)).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => generalInterceptor1.AfterAsync(executable, "parameter hello", default(string), exception)).MustHaveHappenedOnceExactly());
}
[Fact]
public async Task ExecuteAsync_InterceptorsGetIEmptyWhenNoParameterOrReturnValue()
{
var executable = A.Fake<IExecutableVoidAsync>();
var generalInterceptor1 = A.Fake<IExecutionInterceptorAsync>();
A.CallTo(() => generalInterceptor1.OrderingIndex).Returns(1);
var generalInterceptor2 = A.Fake<IExecutionInterceptorAsync>();
A.CallTo(() => generalInterceptor2.OrderingIndex).Returns(3);
var specificInterceptor = A.Fake<IExecutionInterceptorAsync<IExecutableVoidAsync, IEmpty, IEmpty>>();
A.CallTo(() => specificInterceptor.OrderingIndex).Returns(2);
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).AddSpecificInterceptors(specificInterceptor).AddGeneralInterceptors(generalInterceptor1, generalInterceptor2).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutorAsync>();
await executor.ExecuteAsync<IExecutableVoidAsync>().ConfigureAwait(false);
// interceptors called in ascending OrderIndex order
_ = A.CallTo(() => generalInterceptor1.BeforeAsync(executable, default(IEmpty))).MustHaveHappenedOnceExactly()
.Then(A.CallTo(() => specificInterceptor.BeforeAsync(executable, default(IEmpty))).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => generalInterceptor2.BeforeAsync(executable, default(IEmpty))).MustHaveHappenedOnceExactly())
// executable called
.Then(A.CallTo(() => executable.ExecuteAsync()).MustHaveHappenedOnceExactly())
// interceptors called in descending OrderIndex order
.Then(A.CallTo(() => generalInterceptor2.AfterAsync(executable, default(IEmpty), default(IEmpty), null)).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => specificInterceptor.AfterAsync(executable, default(IEmpty), default(IEmpty), null)).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => generalInterceptor1.AfterAsync(executable, default(IEmpty), default(IEmpty), null)).MustHaveHappenedOnceExactly());
}
[Fact]
public async Task ExecuteAsync_InterceptorsImplementIDiscardOtherInteceptors_TheOneWithSmallestOrderIndexIsCalled()
{
var executable = A.Fake<IExecutableVoidAsync>();
var generalInterceptor1 = A.Fake<IExecutionInterceptorAsync>(x => x.Implements<IDiscardOtherInterceptors>());
A.CallTo(() => generalInterceptor1.OrderingIndex).Returns(1);
var generalInterceptor2 = A.Fake<IExecutionInterceptorAsync>(x => x.Implements<IDiscardOtherInterceptors>());
A.CallTo(() => generalInterceptor2.OrderingIndex).Returns(3);
var specificInterceptor = A.Fake<IExecutionInterceptorAsync<IExecutableVoidAsync, IEmpty, IEmpty>>(x => x.Implements<IDiscardOtherInterceptors>());
A.CallTo(() => specificInterceptor.OrderingIndex).Returns(2);
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).AddSpecificInterceptors(specificInterceptor).AddGeneralInterceptors(generalInterceptor1, generalInterceptor2).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutorAsync>();
await executor.ExecuteAsync<IExecutableVoidAsync>().ConfigureAwait(false);
_ = A.CallTo(() => generalInterceptor1.BeforeAsync(executable, default(IEmpty))).MustHaveHappenedOnceExactly()
.Then(A.CallTo(() => executable.ExecuteAsync()).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => generalInterceptor1.AfterAsync(executable, default(IEmpty), default(IEmpty), null)).MustHaveHappenedOnceExactly());
A.CallTo(() => specificInterceptor.BeforeAsync(executable, default(IEmpty))).MustNotHaveHappened();
A.CallTo(() => generalInterceptor2.BeforeAsync(executable, default(IEmpty))).MustNotHaveHappened();
A.CallTo(() => generalInterceptor2.AfterAsync(executable, default(IEmpty), default(IEmpty), null)).MustNotHaveHappened();
A.CallTo(() => specificInterceptor.AfterAsync(executable, default(IEmpty), default(IEmpty), null)).MustNotHaveHappened();
}
[Fact]
public async Task ExecuteAsync_InterceptorsImplementIDiscardOtherInteceptorsAndIDiscardNonGenericInterceptors_TheIDiscardNonGenericInterceptorsIsCalled()
{
var executable = A.Fake<IExecutableVoidAsync>();
var generalInterceptor1 = A.Fake<IExecutionInterceptorAsync>(x => x.Implements<IDiscardOtherInterceptors>());
A.CallTo(() => generalInterceptor1.OrderingIndex).Returns(1);
var generalInterceptor2 = A.Fake<IExecutionInterceptorAsync>(x => x.Implements<IDiscardOtherInterceptors>());
A.CallTo(() => generalInterceptor2.OrderingIndex).Returns(3);
var specificInterceptor = A.Fake<IExecutionInterceptorAsync<IExecutableVoidAsync, IEmpty, IEmpty>>(x => x.Implements<IDiscardOtherInterceptors>().Implements<IDiscardNonGenericInterceptors>());
A.CallTo(() => specificInterceptor.OrderingIndex).Returns(2);
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).AddSpecificInterceptors(specificInterceptor).AddGeneralInterceptors(generalInterceptor1, generalInterceptor2).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutorAsync>();
await executor.ExecuteAsync<IExecutableVoidAsync>().ConfigureAwait(false);
_ = A.CallTo(() => specificInterceptor.BeforeAsync(executable, default(IEmpty))).MustHaveHappenedOnceExactly()
.Then(A.CallTo(() => executable.ExecuteAsync()).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => specificInterceptor.AfterAsync(executable, default(IEmpty), default(IEmpty), null)).MustHaveHappenedOnceExactly());
A.CallTo(() => generalInterceptor1.BeforeAsync(executable, default(IEmpty))).MustNotHaveHappened();
A.CallTo(() => generalInterceptor2.BeforeAsync(executable, default(IEmpty))).MustNotHaveHappened();
A.CallTo(() => generalInterceptor1.AfterAsync(executable, default(IEmpty), default(IEmpty), null)).MustNotHaveHappened();
A.CallTo(() => generalInterceptor2.AfterAsync(executable, default(IEmpty), default(IEmpty), null)).MustNotHaveHappened();
}
[Fact]
public async Task ExecuteAsync_SpecificInterceptorImplementIDiscardOtherInteceptors_TheSpecificInterceptorsIsCalled()
{
var executable = A.Fake<IExecutableVoidAsync>();
var generalInterceptor1 = A.Fake<IExecutionInterceptorAsync>();
A.CallTo(() => generalInterceptor1.OrderingIndex).Returns(1);
var generalInterceptor2 = A.Fake<IExecutionInterceptorAsync>();
A.CallTo(() => generalInterceptor2.OrderingIndex).Returns(3);
var specificInterceptor = A.Fake<IExecutionInterceptorAsync<IExecutableVoidAsync, IEmpty, IEmpty>>(x => x.Implements<IDiscardOtherInterceptors>());
A.CallTo(() => specificInterceptor.OrderingIndex).Returns(2);
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).AddSpecificInterceptors(specificInterceptor).AddGeneralInterceptors(generalInterceptor1, generalInterceptor2).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutorAsync>();
await executor.ExecuteAsync<IExecutableVoidAsync>().ConfigureAwait(false);
_ = A.CallTo(() => specificInterceptor.BeforeAsync(executable, default(IEmpty))).MustHaveHappenedOnceExactly()
.Then(A.CallTo(() => executable.ExecuteAsync()).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => specificInterceptor.AfterAsync(executable, default(IEmpty), default(IEmpty), null)).MustHaveHappenedOnceExactly());
A.CallTo(() => generalInterceptor1.BeforeAsync(executable, default(IEmpty))).MustNotHaveHappened();
A.CallTo(() => generalInterceptor2.BeforeAsync(executable, default(IEmpty))).MustNotHaveHappened();
A.CallTo(() => generalInterceptor1.AfterAsync(executable, default(IEmpty), default(IEmpty), null)).MustNotHaveHappened();
A.CallTo(() => generalInterceptor2.AfterAsync(executable, default(IEmpty), default(IEmpty), null)).MustNotHaveHappened();
}
[Fact]
public async Task ExecuteAsync_GeneralInterceptorImplementIDiscardOtherInteceptors_TheGeneralInterceptorsIsCalled()
{
var executable = A.Fake<IExecutableVoidAsync>();
var generalInterceptor1 = A.Fake<IExecutionInterceptorAsync>();
A.CallTo(() => generalInterceptor1.OrderingIndex).Returns(1);
var generalInterceptor2 = A.Fake<IExecutionInterceptorAsync>(x => x.Implements<IDiscardOtherInterceptors>());
A.CallTo(() => generalInterceptor2.OrderingIndex).Returns(3);
var specificInterceptor = A.Fake<IExecutionInterceptorAsync<IExecutableVoidAsync, IEmpty, IEmpty>>();
A.CallTo(() => specificInterceptor.OrderingIndex).Returns(2);
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).AddSpecificInterceptors(specificInterceptor).AddGeneralInterceptors(generalInterceptor1, generalInterceptor2).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutorAsync>();
await executor.ExecuteAsync<IExecutableVoidAsync>().ConfigureAwait(false);
_ = A.CallTo(() => generalInterceptor2.BeforeAsync(executable, default(IEmpty))).MustHaveHappenedOnceExactly()
.Then(A.CallTo(() => executable.ExecuteAsync()).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => generalInterceptor2.AfterAsync(executable, default(IEmpty), default(IEmpty), null)).MustHaveHappenedOnceExactly());
A.CallTo(() => specificInterceptor.BeforeAsync(executable, default(IEmpty))).MustNotHaveHappened();
A.CallTo(() => generalInterceptor1.BeforeAsync(executable, default(IEmpty))).MustNotHaveHappened();
A.CallTo(() => generalInterceptor1.AfterAsync(executable, default(IEmpty), default(IEmpty), null)).MustNotHaveHappened();
A.CallTo(() => specificInterceptor.AfterAsync(executable, default(IEmpty), default(IEmpty), null)).MustNotHaveHappened();
}
[Fact]
public async Task ExecuteAsync_SpecificInterceptorImplementsIDiscardNonGenericInterceptors_NonGenericInterceptorsAreNorCalled()
{
var executable = A.Fake<IExecutableVoidAsync>();
var generalInterceptor1 = A.Fake<IExecutionInterceptorAsync>();
A.CallTo(() => generalInterceptor1.OrderingIndex).Returns(1);
var generalInterceptor2 = A.Fake<IExecutionInterceptorAsync>();
A.CallTo(() => generalInterceptor2.OrderingIndex).Returns(3);
var specificInterceptor = A.Fake<IExecutionInterceptorAsync<IExecutableVoidAsync, IEmpty, IEmpty>>(x => x.Implements<IDiscardNonGenericInterceptors>());
A.CallTo(() => specificInterceptor.OrderingIndex).Returns(2);
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).AddSpecificInterceptors(specificInterceptor).AddGeneralInterceptors(generalInterceptor1, generalInterceptor2).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutorAsync>();
await executor.ExecuteAsync<IExecutableVoidAsync>().ConfigureAwait(false);
_ = A.CallTo(() => specificInterceptor.BeforeAsync(executable, default(IEmpty))).MustHaveHappenedOnceExactly()
.Then(A.CallTo(() => executable.ExecuteAsync()).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => specificInterceptor.AfterAsync(executable, default(IEmpty), default(IEmpty), null)).MustHaveHappenedOnceExactly());
A.CallTo(() => generalInterceptor1.BeforeAsync(executable, default(IEmpty))).MustNotHaveHappened();
A.CallTo(() => generalInterceptor2.BeforeAsync(executable, default(IEmpty))).MustNotHaveHappened();
A.CallTo(() => generalInterceptor1.AfterAsync(executable, default(IEmpty), default(IEmpty), null)).MustNotHaveHappened();
A.CallTo(() => generalInterceptor2.AfterAsync(executable, default(IEmpty), default(IEmpty), null)).MustNotHaveHappened();
}
[Fact]
public async Task ExecuteAsync_GeneralInterceptorImplementsIDiscardNonGenericInterceptors_DoesNotAffectGeneralInterceptors()
{
var executable = A.Fake<IExecutableVoidAsync>();
var generalInterceptor1 = A.Fake<IExecutionInterceptorAsync>(x => x.Implements<IDiscardNonGenericInterceptors>());
A.CallTo(() => generalInterceptor1.OrderingIndex).Returns(1);
var generalInterceptor2 = A.Fake<IExecutionInterceptorAsync>(x => x.Implements<IDiscardNonGenericInterceptors>());
A.CallTo(() => generalInterceptor2.OrderingIndex).Returns(3);
var specificInterceptor = A.Fake<IExecutionInterceptorAsync<IExecutableVoidAsync, IEmpty, IEmpty>>();
A.CallTo(() => specificInterceptor.OrderingIndex).Returns(2);
ServiceProvider serviceProvider = new ServiceCollection().AddExecutor().AddExecutable(executable).AddSpecificInterceptors(specificInterceptor).AddGeneralInterceptors(generalInterceptor1, generalInterceptor2).BuildServiceProvider();
var executor = serviceProvider.GetRequiredService<IExecutorAsync>();
await executor.ExecuteAsync<IExecutableVoidAsync>().ConfigureAwait(false);
// interceptors called in ascending OrderIndex order
_ = A.CallTo(() => generalInterceptor1.BeforeAsync(executable, default(IEmpty))).MustHaveHappenedOnceExactly()
.Then(A.CallTo(() => specificInterceptor.BeforeAsync(executable, default(IEmpty))).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => generalInterceptor2.BeforeAsync(executable, default(IEmpty))).MustHaveHappenedOnceExactly())
// executable called
.Then(A.CallTo(() => executable.ExecuteAsync()).MustHaveHappenedOnceExactly())
// interceptors called in descending OrderIndex order
.Then(A.CallTo(() => generalInterceptor2.AfterAsync(executable, default(IEmpty), default(IEmpty), null)).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => specificInterceptor.AfterAsync(executable, default(IEmpty), default(IEmpty), null)).MustHaveHappenedOnceExactly())
.Then(A.CallTo(() => generalInterceptor1.AfterAsync(executable, default(IEmpty), default(IEmpty), null)).MustHaveHappenedOnceExactly());
}
}
}
| |
// 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.Globalization {
using System;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
// This abstract class represents a calendar. A calendar reckons time in
// divisions such as weeks, months and years. The number, length and start of
// the divisions vary in each calendar.
//
// Any instant in time can be represented as an n-tuple of numeric values using
// a particular calendar. For example, the next vernal equinox occurs at (0.0, 0
// , 46, 8, 20, 3, 1999) in the Gregorian calendar. An implementation of
// Calendar can map any DateTime value to such an n-tuple and vice versa. The
// DateTimeFormat class can map between such n-tuples and a textual
// representation such as "8:46 AM March 20th 1999 AD".
//
// Most calendars identify a year which begins the current era. There may be any
// number of previous eras. The Calendar class identifies the eras as enumerated
// integers where the current era (CurrentEra) has the value zero.
//
// For consistency, the first unit in each interval, e.g. the first month, is
// assigned the value one.
// The calculation of hour/minute/second is moved to Calendar from GregorianCalendar,
// since most of the calendars (or all?) have the same way of calcuating hour/minute/second.
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class Calendar : ICloneable
{
// Number of 100ns (10E-7 second) ticks per time unit
internal const long TicksPerMillisecond = 10000;
internal const long TicksPerSecond = TicksPerMillisecond * 1000;
internal const long TicksPerMinute = TicksPerSecond * 60;
internal const long TicksPerHour = TicksPerMinute * 60;
internal const long TicksPerDay = TicksPerHour * 24;
// Number of milliseconds per time unit
internal const int MillisPerSecond = 1000;
internal const int MillisPerMinute = MillisPerSecond * 60;
internal const int MillisPerHour = MillisPerMinute * 60;
internal const int MillisPerDay = MillisPerHour * 24;
// Number of days in a non-leap year
internal const int DaysPerYear = 365;
// Number of days in 4 years
internal const int DaysPer4Years = DaysPerYear * 4 + 1;
// Number of days in 100 years
internal const int DaysPer100Years = DaysPer4Years * 25 - 1;
// Number of days in 400 years
internal const int DaysPer400Years = DaysPer100Years * 4 + 1;
// Number of days from 1/1/0001 to 1/1/10000
internal const int DaysTo10000 = DaysPer400Years * 25 - 366;
internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay;
//
// Calendar ID Values. This is used to get data from calendar.nlp.
// The order of calendar ID means the order of data items in the table.
//
internal const int CAL_GREGORIAN = 1 ; // Gregorian (localized) calendar
internal const int CAL_GREGORIAN_US = 2 ; // Gregorian (U.S.) calendar
internal const int CAL_JAPAN = 3 ; // Japanese Emperor Era calendar
internal const int CAL_TAIWAN = 4 ; // Taiwan Era calendar
internal const int CAL_KOREA = 5 ; // Korean Tangun Era calendar
internal const int CAL_HIJRI = 6 ; // Hijri (Arabic Lunar) calendar
internal const int CAL_THAI = 7 ; // Thai calendar
internal const int CAL_HEBREW = 8 ; // Hebrew (Lunar) calendar
internal const int CAL_GREGORIAN_ME_FRENCH = 9 ; // Gregorian Middle East French calendar
internal const int CAL_GREGORIAN_ARABIC = 10; // Gregorian Arabic calendar
internal const int CAL_GREGORIAN_XLIT_ENGLISH = 11; // Gregorian Transliterated English calendar
internal const int CAL_GREGORIAN_XLIT_FRENCH = 12;
internal const int CAL_JULIAN = 13;
internal const int CAL_JAPANESELUNISOLAR = 14;
internal const int CAL_CHINESELUNISOLAR = 15;
internal const int CAL_SAKA = 16; // reserved to match Office but not implemented in our code
internal const int CAL_LUNAR_ETO_CHN = 17; // reserved to match Office but not implemented in our code
internal const int CAL_LUNAR_ETO_KOR = 18; // reserved to match Office but not implemented in our code
internal const int CAL_LUNAR_ETO_ROKUYOU = 19; // reserved to match Office but not implemented in our code
internal const int CAL_KOREANLUNISOLAR = 20;
internal const int CAL_TAIWANLUNISOLAR = 21;
internal const int CAL_PERSIAN = 22;
internal const int CAL_UMALQURA = 23;
internal int m_currentEraValue = -1;
[System.Runtime.Serialization.OptionalField(VersionAdded = 2)]
private bool m_isReadOnly = false;
// The minimum supported DateTime range for the calendar.
[System.Runtime.InteropServices.ComVisible(false)]
public virtual DateTime MinSupportedDateTime
{
get
{
return (DateTime.MinValue);
}
}
// The maximum supported DateTime range for the calendar.
[System.Runtime.InteropServices.ComVisible(false)]
public virtual DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
protected Calendar() {
//Do-nothing constructor.
}
///
// This can not be abstract, otherwise no one can create a subclass of Calendar.
//
internal virtual int ID {
get {
return (-1);
}
}
///
// Return the Base calendar ID for calendars that didn't have defined data in calendarData
//
internal virtual int BaseCalendarID
{
get { return ID; }
}
// Returns the type of the calendar.
//
[System.Runtime.InteropServices.ComVisible(false)]
public virtual CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.Unknown;
}
}
////////////////////////////////////////////////////////////////////////
//
// IsReadOnly
//
// Detect if the object is readonly.
//
////////////////////////////////////////////////////////////////////////
[System.Runtime.InteropServices.ComVisible(false)]
public bool IsReadOnly
{
get { return (m_isReadOnly); }
}
////////////////////////////////////////////////////////////////////////
//
// Clone
//
// Is the implementation of IColnable.
//
////////////////////////////////////////////////////////////////////////
[System.Runtime.InteropServices.ComVisible(false)]
public virtual Object Clone()
{
object o = MemberwiseClone();
((Calendar) o).SetReadOnlyState(false);
return (o);
}
////////////////////////////////////////////////////////////////////////
//
// ReadOnly
//
// Create a cloned readonly instance or return the input one if it is
// readonly.
//
////////////////////////////////////////////////////////////////////////
[System.Runtime.InteropServices.ComVisible(false)]
public static Calendar ReadOnly(Calendar calendar)
{
if (calendar == null) { throw new ArgumentNullException("calendar"); }
Contract.EndContractBlock();
if (calendar.IsReadOnly) { return (calendar); }
Calendar clonedCalendar = (Calendar)(calendar.MemberwiseClone());
clonedCalendar.SetReadOnlyState(true);
return (clonedCalendar);
}
internal void VerifyWritable()
{
if (m_isReadOnly)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
}
}
internal void SetReadOnlyState(bool readOnly)
{
m_isReadOnly = readOnly;
}
/*=================================CurrentEraValue==========================
**Action: This is used to convert CurretEra(0) to an appropriate era value.
**Returns:
**Arguments:
**Exceptions:
**Notes:
** The value is from calendar.nlp.
============================================================================*/
internal virtual int CurrentEraValue {
get {
// The following code assumes that the current era value can not be -1.
if (m_currentEraValue == -1) {
Contract.Assert(BaseCalendarID > 0, "[Calendar.CurrentEraValue] Expected ID > 0");
m_currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra;
}
return (m_currentEraValue);
}
}
// The current era for a calendar.
public const int CurrentEra = 0;
internal int twoDigitYearMax = -1;
internal static void CheckAddResult(long ticks, DateTime minValue, DateTime maxValue) {
if (ticks < minValue.Ticks || ticks > maxValue.Ticks) {
throw new ArgumentException(
String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Argument_ResultCalendarRange"),
minValue, maxValue));
}
Contract.EndContractBlock();
}
internal DateTime Add(DateTime time, double value, int scale) {
// From ECMA CLI spec, Partition III, section 3.27:
//
// If overflow occurs converting a floating-point type to an integer, or if the floating-point value
// being converted to an integer is a NaN, the value returned is unspecified.
//
// Based upon this, this method should be performing the comparison against the double
// before attempting a cast. Otherwise, the result is undefined.
double tempMillis = (value * scale + (value >= 0 ? 0.5 : -0.5));
if (!((tempMillis > -(double)MaxMillis) && (tempMillis < (double)MaxMillis)))
{
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_AddValue"));
}
long millis = (long)tempMillis;
long ticks = time.Ticks + millis * TicksPerMillisecond;
CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
// Returns the DateTime resulting from adding the given number of
// milliseconds to the specified DateTime. The result is computed by rounding
// the number of milliseconds given by value to the nearest integer,
// and adding that interval to the specified DateTime. The value
// argument is permitted to be negative.
//
public virtual DateTime AddMilliseconds(DateTime time, double milliseconds) {
return (Add(time, milliseconds, 1));
}
// Returns the DateTime resulting from adding a fractional number of
// days to the specified DateTime. The result is computed by rounding the
// fractional number of days given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddDays(DateTime time, int days) {
return (Add(time, days, MillisPerDay));
}
// Returns the DateTime resulting from adding a fractional number of
// hours to the specified DateTime. The result is computed by rounding the
// fractional number of hours given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddHours(DateTime time, int hours) {
return (Add(time, hours, MillisPerHour));
}
// Returns the DateTime resulting from adding a fractional number of
// minutes to the specified DateTime. The result is computed by rounding the
// fractional number of minutes given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddMinutes(DateTime time, int minutes) {
return (Add(time, minutes, MillisPerMinute));
}
// Returns the DateTime resulting from adding the given number of
// months to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of the specified DateTime by
// value months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of the specified DateTime.
//
// In more precise terms, considering the specified DateTime to be of the
// form y / m / d + t, where y is the
// year, m is the month, d is the day, and t is the
// time-of-day, the result is y1 / m1 / d1 + t,
// where y1 and m1 are computed by adding value months
// to y and m, and d1 is the largest value less than
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
public abstract DateTime AddMonths(DateTime time, int months);
// Returns the DateTime resulting from adding a number of
// seconds to the specified DateTime. The result is computed by rounding the
// fractional number of seconds given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddSeconds(DateTime time, int seconds) {
return Add(time, seconds, MillisPerSecond);
}
// Returns the DateTime resulting from adding a number of
// weeks to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddWeeks(DateTime time, int weeks) {
return (AddDays(time, weeks * 7));
}
// Returns the DateTime resulting from adding the given number of
// years to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year part of the specified DateTime by value
// years. If the month and day of the specified DateTime is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of the specified DateTime.
//
public abstract DateTime AddYears(DateTime time, int years);
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
public abstract int GetDayOfMonth(DateTime time);
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public abstract DayOfWeek GetDayOfWeek(DateTime time);
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
public abstract int GetDayOfYear(DateTime time);
// Returns the number of days in the month given by the year and
// month arguments.
//
public virtual int GetDaysInMonth(int year, int month)
{
return (GetDaysInMonth(year, month, CurrentEra));
}
// Returns the number of days in the month given by the year and
// month arguments for the specified era.
//
public abstract int GetDaysInMonth(int year, int month, int era);
// Returns the number of days in the year given by the year argument for the current era.
//
public virtual int GetDaysInYear(int year)
{
return (GetDaysInYear(year, CurrentEra));
}
// Returns the number of days in the year given by the year argument for the current era.
//
public abstract int GetDaysInYear(int year, int era);
// Returns the era for the specified DateTime value.
public abstract int GetEra(DateTime time);
/*=================================Eras==========================
**Action: Get the list of era values.
**Returns: The int array of the era names supported in this calendar.
** null if era is not used.
**Arguments: None.
**Exceptions: None.
============================================================================*/
public abstract int[] Eras {
get;
}
// Returns the hour part of the specified DateTime. The returned value is an
// integer between 0 and 23.
//
public virtual int GetHour(DateTime time) {
return ((int)((time.Ticks / TicksPerHour) % 24));
}
// Returns the millisecond part of the specified DateTime. The returned value
// is an integer between 0 and 999.
//
public virtual double GetMilliseconds(DateTime time) {
return (double)((time.Ticks / TicksPerMillisecond) % 1000);
}
// Returns the minute part of the specified DateTime. The returned value is
// an integer between 0 and 59.
//
public virtual int GetMinute(DateTime time) {
return ((int)((time.Ticks / TicksPerMinute) % 60));
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
public abstract int GetMonth(DateTime time);
// Returns the number of months in the specified year in the current era.
public virtual int GetMonthsInYear(int year)
{
return (GetMonthsInYear(year, CurrentEra));
}
// Returns the number of months in the specified year and era.
public abstract int GetMonthsInYear(int year, int era);
// Returns the second part of the specified DateTime. The returned value is
// an integer between 0 and 59.
//
public virtual int GetSecond(DateTime time) {
return ((int)((time.Ticks / TicksPerSecond) % 60));
}
/*=================================GetFirstDayWeekOfYear==========================
**Action: Get the week of year using the FirstDay rule.
**Returns: the week of year.
**Arguments:
** time
** firstDayOfWeek the first day of week (0=Sunday, 1=Monday, ... 6=Saturday)
**Notes:
** The CalendarWeekRule.FirstDay rule: Week 1 begins on the first day of the year.
** Assume f is the specifed firstDayOfWeek,
** and n is the day of week for January 1 of the specified year.
** Assign offset = n - f;
** Case 1: offset = 0
** E.g.
** f=1
** weekday 0 1 2 3 4 5 6 0 1
** date 1/1
** week# 1 2
** then week of year = (GetDayOfYear(time) - 1) / 7 + 1
**
** Case 2: offset < 0
** e.g.
** n=1 f=3
** weekday 0 1 2 3 4 5 6 0
** date 1/1
** week# 1 2
** This means that the first week actually starts 5 days before 1/1.
** So week of year = (GetDayOfYear(time) + (7 + offset) - 1) / 7 + 1
** Case 3: offset > 0
** e.g.
** f=0 n=2
** weekday 0 1 2 3 4 5 6 0 1 2
** date 1/1
** week# 1 2
** This means that the first week actually starts 2 days before 1/1.
** So Week of year = (GetDayOfYear(time) + offset - 1) / 7 + 1
============================================================================*/
internal int GetFirstDayWeekOfYear(DateTime time, int firstDayOfWeek) {
int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
// Calculate the day of week for the first day of the year.
// dayOfWeek - (dayOfYear % 7) is the day of week for the first day of this year. Note that
// this value can be less than 0. It's fine since we are making it positive again in calculating offset.
int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
int offset = (dayForJan1 - firstDayOfWeek + 14) % 7;
Contract.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0");
return ((dayOfYear + offset) / 7 + 1);
}
private int GetWeekOfYearFullDays(DateTime time, int firstDayOfWeek, int fullDays) {
int dayForJan1;
int offset;
int day;
int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
//
// Calculate the number of days between the first day of year (1/1) and the first day of the week.
// This value will be a positive value from 0 ~ 6. We call this value as "offset".
//
// If offset is 0, it means that the 1/1 is the start of the first week.
// Assume the first day of the week is Monday, it will look like this:
// Sun Mon Tue Wed Thu Fri Sat
// 12/31 1/1 1/2 1/3 1/4 1/5 1/6
// +--> First week starts here.
//
// If offset is 1, it means that the first day of the week is 1 day ahead of 1/1.
// Assume the first day of the week is Monday, it will look like this:
// Sun Mon Tue Wed Thu Fri Sat
// 1/1 1/2 1/3 1/4 1/5 1/6 1/7
// +--> First week starts here.
//
// If offset is 2, it means that the first day of the week is 2 days ahead of 1/1.
// Assume the first day of the week is Monday, it will look like this:
// Sat Sun Mon Tue Wed Thu Fri Sat
// 1/1 1/2 1/3 1/4 1/5 1/6 1/7 1/8
// +--> First week starts here.
// Day of week is 0-based.
// Get the day of week for 1/1. This can be derived from the day of week of the target day.
// Note that we can get a negative value. It's ok since we are going to make it a positive value when calculating the offset.
dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
// Now, calculate the offset. Subtract the first day of week from the dayForJan1. And make it a positive value.
offset = (firstDayOfWeek - dayForJan1 + 14) % 7;
if (offset != 0 && offset >= fullDays)
{
//
// If the offset is greater than the value of fullDays, it means that
// the first week of the year starts on the week where Jan/1 falls on.
//
offset -= 7;
}
//
// Calculate the day of year for specified time by taking offset into account.
//
day = dayOfYear - offset;
if (day >= 0) {
//
// If the day of year value is greater than zero, get the week of year.
//
return (day/7 + 1);
}
//
// Otherwise, the specified time falls on the week of previous year.
// Call this method again by passing the last day of previous year.
//
// the last day of the previous year may "underflow" to no longer be a valid date time for
// this calendar if we just subtract so we need the subclass to provide us with
// that information
if (time <= MinSupportedDateTime.AddDays(dayOfYear))
{
return GetWeekOfYearOfMinSupportedDateTime(firstDayOfWeek, fullDays);
}
return (GetWeekOfYearFullDays(time.AddDays(-(dayOfYear + 1)), firstDayOfWeek, fullDays));
}
private int GetWeekOfYearOfMinSupportedDateTime(int firstDayOfWeek, int minimumDaysInFirstWeek)
{
int dayOfYear = GetDayOfYear(MinSupportedDateTime) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
int dayOfWeekOfFirstOfYear = (int)GetDayOfWeek(MinSupportedDateTime) - dayOfYear % 7;
// Calculate the offset (how many days from the start of the year to the start of the week)
int offset = (firstDayOfWeek + 7 - dayOfWeekOfFirstOfYear) % 7;
if (offset == 0 || offset >= minimumDaysInFirstWeek)
{
// First of year falls in the first week of the year
return 1;
}
int daysInYearBeforeMinSupportedYear = DaysInYearBeforeMinSupportedYear - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
int dayOfWeekOfFirstOfPreviousYear = dayOfWeekOfFirstOfYear - 1 - (daysInYearBeforeMinSupportedYear % 7);
// starting from first day of the year, how many days do you have to go forward
// before getting to the first day of the week?
int daysInInitialPartialWeek = (firstDayOfWeek - dayOfWeekOfFirstOfPreviousYear + 14) % 7;
int day = daysInYearBeforeMinSupportedYear - daysInInitialPartialWeek;
if (daysInInitialPartialWeek >= minimumDaysInFirstWeek)
{
// If the offset is greater than the minimum Days in the first week, it means that
// First of year is part of the first week of the year even though it is only a partial week
// add another week
day += 7;
}
return (day / 7 + 1);
}
// it would be nice to make this abstract but we can't since that would break previous implementations
protected virtual int DaysInYearBeforeMinSupportedYear
{
get
{
return 365;
}
}
// Returns the week of year for the specified DateTime. The returned value is an
// integer between 1 and 53.
//
public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
if ((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6) {
throw new ArgumentOutOfRangeException(
"firstDayOfWeek", Environment.GetResourceString("ArgumentOutOfRange_Range",
DayOfWeek.Sunday, DayOfWeek.Saturday));
}
Contract.EndContractBlock();
switch (rule) {
case CalendarWeekRule.FirstDay:
return (GetFirstDayWeekOfYear(time, (int)firstDayOfWeek));
case CalendarWeekRule.FirstFullWeek:
return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 7));
case CalendarWeekRule.FirstFourDayWeek:
return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 4));
}
throw new ArgumentOutOfRangeException(
"rule", Environment.GetResourceString("ArgumentOutOfRange_Range",
CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek));
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and 9999.
//
public abstract int GetYear(DateTime time);
// Checks whether a given day in the current era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public virtual bool IsLeapDay(int year, int month, int day)
{
return (IsLeapDay(year, month, day, CurrentEra));
}
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public abstract bool IsLeapDay(int year, int month, int day, int era);
// Checks whether a given month in the current era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public virtual bool IsLeapMonth(int year, int month) {
return (IsLeapMonth(year, month, CurrentEra));
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public abstract bool IsLeapMonth(int year, int month, int era);
// Returns the leap month in a calendar year of the current era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
[System.Runtime.InteropServices.ComVisible(false)]
public virtual int GetLeapMonth(int year)
{
return (GetLeapMonth(year, CurrentEra));
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
[System.Runtime.InteropServices.ComVisible(false)]
public virtual int GetLeapMonth(int year, int era)
{
if (!IsLeapYear(year, era))
return 0;
int monthsCount = GetMonthsInYear(year, era);
for (int month=1; month<=monthsCount; month++)
{
if (IsLeapMonth(year, month, era))
return month;
}
return 0;
}
// Checks whether a given year in the current era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public virtual bool IsLeapYear(int year)
{
return (IsLeapYear(year, CurrentEra));
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public abstract bool IsLeapYear(int year, int era);
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public virtual DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond)
{
return (ToDateTime(year, month, day, hour, minute, second, millisecond, CurrentEra));
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public abstract DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era);
internal virtual Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) {
result = DateTime.MinValue;
try {
result = ToDateTime(year, month, day, hour, minute, second, millisecond, era);
return true;
}
catch (ArgumentException) {
return false;
}
}
internal virtual bool IsValidYear(int year, int era) {
return (year >= GetYear(MinSupportedDateTime) && year <= GetYear(MaxSupportedDateTime));
}
internal virtual bool IsValidMonth(int year, int month, int era) {
return (IsValidYear(year, era) && month >= 1 && month <= GetMonthsInYear(year, era));
}
internal virtual bool IsValidDay(int year, int month, int day, int era)
{
return (IsValidMonth(year, month, era) && day >= 1 && day <= GetDaysInMonth(year, month, era));
}
// Returns and assigns the maximum value to represent a two digit year. This
// value is the upper boundary of a 100 year range that allows a two digit year
// to be properly translated to a four digit year. For example, if 2029 is the
// upper boundary, then a two digit value of 30 should be interpreted as 1930
// while a two digit value of 29 should be interpreted as 2029. In this example
// , the 100 year range would be from 1930-2029. See ToFourDigitYear().
public virtual int TwoDigitYearMax
{
get
{
return (twoDigitYearMax);
}
set
{
VerifyWritable();
twoDigitYearMax = value;
}
}
// Converts the year value to the appropriate century by using the
// TwoDigitYearMax property. For example, if the TwoDigitYearMax value is 2029,
// then a two digit value of 30 will get converted to 1930 while a two digit
// value of 29 will get converted to 2029.
public virtual int ToFourDigitYear(int year) {
if (year < 0) {
throw new ArgumentOutOfRangeException("year",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
if (year < 100) {
return ((TwoDigitYearMax/100 - ( year > TwoDigitYearMax % 100 ? 1 : 0))*100 + year);
}
// If the year value is above 100, just return the year value. Don't have to do
// the TwoDigitYearMax comparison.
return (year);
}
// Return the tick count corresponding to the given hour, minute, second.
// Will check the if the parameters are valid.
internal static long TimeToTicks(int hour, int minute, int second, int millisecond)
{
if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >=0 && second < 60)
{
if (millisecond < 0 || millisecond >= MillisPerSecond) {
throw new ArgumentOutOfRangeException(
"millisecond",
String.Format(
CultureInfo.InvariantCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, MillisPerSecond - 1));
}
return TimeSpan.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond;
}
throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond"));
}
[System.Security.SecuritySafeCritical] // auto-generated
internal static int GetSystemTwoDigitYearSetting(int CalID, int defaultYearValue)
{
// Call nativeGetTwoDigitYearMax
int twoDigitYearMax = CalendarData.nativeGetTwoDigitYearMax(CalID);
if (twoDigitYearMax < 0)
{
twoDigitYearMax = defaultYearValue;
}
return (twoDigitYearMax);
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Management.Automation.Tracing;
namespace System.Management.Automation.PerformanceData
{
/// <summary>
/// Powershell Performance Counters Manager class shall provide a mechanism
/// for components using SYstem.Management.Automation assembly to register
/// performance counters with Performance Counters subsystem.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public class PSPerfCountersMgr
{
#region Private Members
private static PSPerfCountersMgr s_PSPerfCountersMgrInstance;
private ConcurrentDictionary<Guid, CounterSetInstanceBase> _CounterSetIdToInstanceMapping;
private ConcurrentDictionary<string, Guid> _CounterSetNameToIdMapping;
private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource();
#region Constructors
private PSPerfCountersMgr()
{
_CounterSetIdToInstanceMapping = new ConcurrentDictionary<Guid, CounterSetInstanceBase>();
_CounterSetNameToIdMapping = new ConcurrentDictionary<string, Guid>();
}
#endregion
#endregion
#region Destructor
/// <summary>
/// Destructor which will trigger the cleanup of internal data structures and
/// disposal of counter set instances.
/// </summary>
~PSPerfCountersMgr()
{
RemoveAllCounterSets();
}
#endregion
#region Public Methods
/// <summary>
/// Getter method to retrieve the singleton instance of the PSPerfCountersMgr.
/// </summary>
public static PSPerfCountersMgr Instance
{
get { return s_PSPerfCountersMgrInstance ?? (s_PSPerfCountersMgrInstance = new PSPerfCountersMgr()); }
}
/// <summary>
/// Helper method to generate an instance name for a counter set.
/// </summary>
public string GetCounterSetInstanceName()
{
Process currentProcess = Process.GetCurrentProcess();
string pid = string.Format(CultureInfo.InvariantCulture, "{0}", currentProcess.Id);
return pid;
}
/// <summary>
/// Method to determine whether the counter set given by 'counterSetName' is
/// registered with the system. If true, then counterSetId is populated.
/// </summary>
public bool IsCounterSetRegistered(string counterSetName, out Guid counterSetId)
{
counterSetId = new Guid();
if (counterSetName == null)
{
ArgumentNullException argNullException = new ArgumentNullException("counterSetName");
_tracer.TraceException(argNullException);
return false;
}
return _CounterSetNameToIdMapping.TryGetValue(counterSetName, out counterSetId);
}
/// <summary>
/// Method to determine whether the counter set given by 'counterSetId' is
/// registered with the system. If true, then CounterSetInstance is populated.
/// </summary>
public bool IsCounterSetRegistered(Guid counterSetId, out CounterSetInstanceBase counterSetInst)
{
return _CounterSetIdToInstanceMapping.TryGetValue(counterSetId, out counterSetInst);
}
/// <summary>
/// Method to register a counter set with the Performance Counters Manager.
/// </summary>
public bool AddCounterSetInstance(CounterSetRegistrarBase counterSetRegistrarInstance)
{
if (counterSetRegistrarInstance == null)
{
ArgumentNullException argNullException = new ArgumentNullException("counterSetRegistrarInstance");
_tracer.TraceException(argNullException);
return false;
}
Guid counterSetId = counterSetRegistrarInstance.CounterSetId;
string counterSetName = counterSetRegistrarInstance.CounterSetName;
CounterSetInstanceBase counterSetInst = null;
if (this.IsCounterSetRegistered(counterSetId, out counterSetInst))
{
InvalidOperationException invalidOperationException = new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"A Counter Set Instance with id '{0}' is already registered",
counterSetId));
_tracer.TraceException(invalidOperationException);
return false;
}
try
{
if (!string.IsNullOrWhiteSpace(counterSetName))
{
Guid retrievedCounterSetId;
// verify that there doesn't exist another counter set with the same name
if (this.IsCounterSetRegistered(counterSetName, out retrievedCounterSetId))
{
InvalidOperationException invalidOperationException =
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"A Counter Set Instance with name '{0}' is already registered",
counterSetName));
_tracer.TraceException(invalidOperationException);
return false;
}
_CounterSetNameToIdMapping.TryAdd(counterSetName, counterSetId);
}
_CounterSetIdToInstanceMapping.TryAdd(
counterSetId,
counterSetRegistrarInstance.CounterSetInstance);
}
catch (OverflowException overflowException)
{
_tracer.TraceException(overflowException);
return false;
}
return true;
}
/// <summary>
/// If IsNumerator is true, then updates the numerator component
/// of target counter 'counterId' in Counter Set 'counterSetId'
/// by 'stepAmount'.
/// Otherwise, updates the denominator component by 'stepAmount'.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")]
public bool UpdateCounterByValue(
Guid counterSetId,
int counterId,
long stepAmount = 1,
bool isNumerator = true)
{
CounterSetInstanceBase counterSetInst = null;
if (this.IsCounterSetRegistered(counterSetId, out counterSetInst))
{
return counterSetInst.UpdateCounterByValue(counterId, stepAmount, isNumerator);
}
else
{
InvalidOperationException invalidOperationException =
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"No Counter Set Instance with id '{0}' is registered",
counterSetId));
_tracer.TraceException(invalidOperationException);
return false;
}
}
/// <summary>
/// If IsNumerator is true, then updates the numerator component
/// of target counter 'counterName' in Counter Set 'counterSetId'
/// by 'stepAmount'.
/// Otherwise, updates the denominator component by 'stepAmount'.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")]
public bool UpdateCounterByValue(
Guid counterSetId,
string counterName,
long stepAmount = 1,
bool isNumerator = true)
{
CounterSetInstanceBase counterSetInst = null;
if (this.IsCounterSetRegistered(counterSetId, out counterSetInst))
{
return counterSetInst.UpdateCounterByValue(counterName, stepAmount, isNumerator);
}
else
{
InvalidOperationException invalidOperationException =
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"No Counter Set Instance with id '{0}' is registered",
counterSetId));
_tracer.TraceException(invalidOperationException);
return false;
}
}
/// <summary>
/// If IsNumerator is true, then updates the numerator component
/// of target counter 'counterId' in Counter Set 'counterSetName'
/// by 'stepAmount'.
/// Otherwise, updates the denominator component by 'stepAmount'.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")]
public bool UpdateCounterByValue(
string counterSetName,
int counterId,
long stepAmount = 1,
bool isNumerator = true)
{
if (counterSetName == null)
{
ArgumentNullException argNullException =
new ArgumentNullException("counterSetName");
_tracer.TraceException(argNullException);
return false;
}
Guid counterSetId;
if (this.IsCounterSetRegistered(counterSetName, out counterSetId))
{
CounterSetInstanceBase counterSetInst = _CounterSetIdToInstanceMapping[counterSetId];
return counterSetInst.UpdateCounterByValue(counterId, stepAmount, isNumerator);
}
else
{
InvalidOperationException invalidOperationException =
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"No Counter Set Instance with id '{0}' is registered",
counterSetId));
_tracer.TraceException(invalidOperationException);
return false;
}
}
/// <summary>
/// If IsNumerator is true, then updates the numerator component
/// of target counter 'counterName' in Counter Set 'counterSetName'
/// by 'stepAmount'.
/// Otherwise, updates the denominator component by 'stepAmount'.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")]
public bool UpdateCounterByValue(
string counterSetName,
string counterName,
long stepAmount = 1,
bool isNumerator = true)
{
Guid counterSetId;
if (counterSetName == null)
{
ArgumentNullException argNullException =
new ArgumentNullException("counterSetName");
_tracer.TraceException(argNullException);
return false;
}
if (this.IsCounterSetRegistered(counterSetName, out counterSetId))
{
CounterSetInstanceBase counterSetInst = _CounterSetIdToInstanceMapping[counterSetId];
return counterSetInst.UpdateCounterByValue(counterName, stepAmount, isNumerator);
}
else
{
InvalidOperationException invalidOperationException =
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"No Counter Set Instance with name {0} is registered",
counterSetName));
_tracer.TraceException(invalidOperationException);
return false;
}
}
/// <summary>
/// If IsNumerator is true, then sets the numerator component
/// of target counter 'counterId' in Counter Set 'counterSetId'
/// to 'counterValue'.
/// Otherwise, updates the denominator component to 'counterValue'.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")]
public bool SetCounterValue(
Guid counterSetId,
int counterId,
long counterValue = 1,
bool isNumerator = true)
{
CounterSetInstanceBase counterSetInst = null;
if (this.IsCounterSetRegistered(counterSetId, out counterSetInst))
{
return counterSetInst.SetCounterValue(counterId, counterValue, isNumerator);
}
else
{
InvalidOperationException invalidOperationException =
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"No Counter Set Instance with id '{0}' is registered",
counterSetId));
_tracer.TraceException(invalidOperationException);
return false;
}
}
/// <summary>
/// If IsNumerator is true, then sets the numerator component
/// of target counter 'counterName' in Counter Set 'counterSetId'
/// to 'counterValue'.
/// Otherwise, updates the denominator component to 'counterValue'.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")]
public bool SetCounterValue(
Guid counterSetId,
string counterName,
long counterValue = 1,
bool isNumerator = true)
{
CounterSetInstanceBase counterSetInst = null;
if (this.IsCounterSetRegistered(counterSetId, out counterSetInst))
{
return counterSetInst.SetCounterValue(counterName, counterValue, isNumerator);
}
else
{
InvalidOperationException invalidOperationException =
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"No Counter Set Instance with id '{0}' is registered",
counterSetId));
_tracer.TraceException(invalidOperationException);
return false;
}
}
/// <summary>
/// If IsNumerator is true, then sets the numerator component
/// of target counter 'counterId' in Counter Set 'counterSetName'
/// to 'counterValue'.
/// Otherwise, updates the denominator component to 'counterValue'.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")]
public bool SetCounterValue(
string counterSetName,
int counterId,
long counterValue = 1,
bool isNumerator = true)
{
if (counterSetName == null)
{
ArgumentNullException argNullException =
new ArgumentNullException("counterSetName");
_tracer.TraceException(argNullException);
return false;
}
Guid counterSetId;
if (this.IsCounterSetRegistered(counterSetName, out counterSetId))
{
CounterSetInstanceBase counterSetInst = _CounterSetIdToInstanceMapping[counterSetId];
return counterSetInst.SetCounterValue(counterId, counterValue, isNumerator);
}
else
{
InvalidOperationException invalidOperationException =
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"No Counter Set Instance with name '{0}' is registered",
counterSetName));
_tracer.TraceException(invalidOperationException);
return false;
}
}
/// <summary>
/// If IsNumerator is true, then sets the numerator component
/// of target counter 'counterName' in Counter Set 'counterSetName'
/// to 'counterValue'.
/// Otherwise, updates the denominator component to 'counterValue'.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")]
public bool SetCounterValue(
string counterSetName,
string counterName,
long counterValue = 1,
bool isNumerator = true)
{
if (counterSetName == null)
{
ArgumentNullException argNullException =
new ArgumentNullException("counterSetName");
_tracer.TraceException(argNullException);
return false;
}
Guid counterSetId;
if (this.IsCounterSetRegistered(counterSetName, out counterSetId))
{
CounterSetInstanceBase counterSetInst = _CounterSetIdToInstanceMapping[counterSetId];
return counterSetInst.SetCounterValue(counterName, counterValue, isNumerator);
}
else
{
InvalidOperationException invalidOperationException =
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"No Counter Set Instance with name '{0}' is registered",
counterSetName));
_tracer.TraceException(invalidOperationException);
return false;
}
}
#endregion
#region Internal Methods
/// <summary>
/// NOTE: This method is provided solely for testing purposes.
/// </summary>
internal void RemoveAllCounterSets()
{
ICollection<Guid> counterSetIdKeys = _CounterSetIdToInstanceMapping.Keys;
foreach (Guid counterSetId in counterSetIdKeys)
{
CounterSetInstanceBase currentCounterSetInstance = _CounterSetIdToInstanceMapping[counterSetId];
currentCounterSetInstance.Dispose();
}
_CounterSetIdToInstanceMapping.Clear();
_CounterSetNameToIdMapping.Clear();
}
#endregion
}
}
| |
using System;
using System.Runtime.CompilerServices;
namespace Frostfire.Math
{
public static class FMath
{
public const float PI = 3.1415926535f;
public const float HALF_PI = 1.570796326794f;
public const float EPSILON = 1.192092896e-07f; // or 1e-6f
const float RAD_TO_DEG = (float)(180.0 / System.Math.PI);
const float DEG_TO_RAD = (float)(System.Math.PI / 180.0);
static readonly Random _randomizer = new Random();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Abs(float value)
{
return System.Math.Abs(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Acos(float value)
{
return (float)System.Math.Acos(value);
}
public static int AddBool(params bool[] boolean)
{
int value = 0;
for (int i = 0; i < boolean.Length; i++)
if (boolean[i])
value++;
return value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Asin(float value)
{
return (float)System.Math.Asin(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Atan(float value)
{
return (float)System.Math.Atan(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Atan2(float x, float y)
{
return (float)System.Math.Atan2(x, y);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Ceil(float value)
{
return (float)System.Math.Ceiling(value);
}
/// <summary>
/// Rounds a floating point value upwards to the next higher integer.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static int CeilToInt(float value)
{
int newValue = (int)value;
if (value < 0.0f || System.Math.Abs(newValue - value) < EPSILON)
return newValue;
return ++newValue;
}
public static float CeilToPow2(float value, uint min = 1)
{
uint x;
if (value < min)
x = min - 1;
else
{
x = (uint)value;
if (System.Math.Abs(x - value) < EPSILON)
--x;
}
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return (float)++x;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int ClampMin(int value, int min)
{
return value < min ? min : value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int ClampMax(int value, int max)
{
return value > max ? max : value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Clamp(int value, int min, int max)
{
if (value < min) return min;
if (value > max) return max;
return value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float ClampMin(float value, float min)
{
return value < min ? min : value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float ClampMax(float value, float max)
{
return value > max ? max : value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Clamp(float value, float min, float max)
{
if (value < min) return min;
if (value > max) return max;
return value;
}
public static byte ClampByteMin(byte value, byte min)
{
return value < min ? min : value;
}
public static byte ClampByteMax(byte value, byte max)
{
return value > max ? max : value;
}
public static byte ClampByte(byte value, byte min, byte max)
{
if (value < min) return min;
if (value > max) return max;
return value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Cos(float value)
{
return (float)System.Math.Cos(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Cosh(float value)
{
return (float)System.Math.Cosh(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float DegToRad(float angle)
{
return angle * DEG_TO_RAD;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float RadToDeg(float angle)
{
return angle * RAD_TO_DEG;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 DegToRad(Vector3 angle)
{
return new Vector3(angle.X * DEG_TO_RAD, angle.Y * DEG_TO_RAD, angle.Z * DEG_TO_RAD);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 RadToDeg(Vector3 angle)
{
return new Vector3(angle.X * RAD_TO_DEG, angle.Y * RAD_TO_DEG, angle.Z * RAD_TO_DEG);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Exp(float value)
{
return (float)System.Math.Exp(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Floor(float value)
{
return (float)System.Math.Floor(value);
}
/// <summary>
/// Rounds a floating point value down to the next lower integer.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static int FloorToInt(float value)
{
int retValue = (int)value;
if (value > 0.0f || System.Math.Abs(value - retValue) < EPSILON)
return retValue;
return --retValue;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsEqual(float value1, float value2)
{
return System.Math.Abs(value1 - value2) < EPSILON;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsPow2(int value)
{
return (value > 0) && ((value & (value - 1)) == 0);
}
/// <summary>
/// Interpolates between 2 values.
/// </summary>
/// <param name="start">Starting value.</param>
/// <param name="end">Ending value.</param>
/// <param name="factor">Interpolation factor.</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Lerp(float start, float end, float factor)
{
return start + ((end - start) * factor);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Log(float value)
{
return (float)System.Math.Log(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Log(float value, float newBase)
{
return (float)System.Math.Log(value, newBase);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Log10(float value)
{
return (float)System.Math.Log10(value);
}
/// <summary>
/// Gets the largest of two values.
/// </summary>
/// <param name="value1">The first value.</param>
/// <param name="value2">The second value.</param>
/// <returns>Returns the largest value.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Max(float value1, float value2)
{
return (value1 > value2) ? value1 : value2;
}
/// <summary>
/// Gets the smallest of two values.
/// </summary>
/// <param name="value1">The first value.</param>
/// <param name="value2">The second value.</param>
/// <returns>Returns the smallest value.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Min(float value1, float value2)
{
return (value1 < value2) ? value1 : value2;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Pow(float value, float power)
{
return (float)System.Math.Pow(value, power);
}
/// <summary>
/// Calculates a random floating point value between 0.0 and 1.0.
/// </summary>
public static float Rnd()
{
return (float)_randomizer.NextDouble();
}
/// <summary>
/// Calculates a random floating point value between 2 values.
/// </summary>
/// <returns></returns>
public static float Rnd(float min, float max)
{
return min + (float)_randomizer.NextDouble() * (max - min);
}
public static int RndInt(int startInclusive = 0, int endExclusive = 100)
{
return _randomizer.Next(startInclusive, endExclusive);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Round(float value, int digits = 0)
{
return (float)System.Math.Round(value, digits);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int RoundToInt(float value)
{
return (int)System.Math.Round(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Sign(float value)
{
return System.Math.Sign(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Sin(float value)
{
return (float)System.Math.Sin(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Sinh(float value)
{
return (float)System.Math.Sinh(value);
}
/// <summary>
/// Gets the square root.
/// </summary>
/// <param name="value">The value to calculate the square root from.</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Sqrt(float value)
{
// Still the fastest way to calculate the square root for a single precision floating point value in C#
return (float)System.Math.Sqrt(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Tan(float value)
{
return (float)System.Math.Tan(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Tanh(float value)
{
return (float)System.Math.Tanh(value);
}
/// <summary>
/// Wraps a value between Min and Max.
/// </summary>
/// <param name="value"></param>
/// <param name="minInclusive">The minimum value.</param>
/// <param name="maxExclusive">The Maximum value.</param>
/// <returns></returns>
public static float Wrap(float value, float minInclusive, float maxExclusive)
{
if (value < minInclusive)
return (maxExclusive - (minInclusive - value));
if (value >= maxExclusive)
return value - (maxExclusive - minInclusive);
return value;
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// H07_RegionColl (editable child list).<br/>
/// This is a generated base class of <see cref="H07_RegionColl"/> business object.
/// </summary>
/// <remarks>
/// This class is child of <see cref="H06_Country"/> editable child object.<br/>
/// The items of the collection are <see cref="H08_Region"/> objects.
/// </remarks>
[Serializable]
public partial class H07_RegionColl : BusinessListBase<H07_RegionColl, H08_Region>
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="H08_Region"/> item from the collection.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to be removed.</param>
public void Remove(int region_ID)
{
foreach (var h08_Region in this)
{
if (h08_Region.Region_ID == region_ID)
{
Remove(h08_Region);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="H08_Region"/> item is in the collection.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to search for.</param>
/// <returns><c>true</c> if the H08_Region is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int region_ID)
{
foreach (var h08_Region in this)
{
if (h08_Region.Region_ID == region_ID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="H08_Region"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to search for.</param>
/// <returns><c>true</c> if the H08_Region is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int region_ID)
{
foreach (var h08_Region in DeletedList)
{
if (h08_Region.Region_ID == region_ID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="H08_Region"/> item of the <see cref="H07_RegionColl"/> collection, based on a given Region_ID.
/// </summary>
/// <param name="region_ID">The Region_ID.</param>
/// <returns>A <see cref="H08_Region"/> object.</returns>
public H08_Region FindH08_RegionByRegion_ID(int region_ID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].Region_ID.Equals(region_ID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="H07_RegionColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="H07_RegionColl"/> collection.</returns>
internal static H07_RegionColl NewH07_RegionColl()
{
return DataPortal.CreateChild<H07_RegionColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="H07_RegionColl"/> collection, based on given parameters.
/// </summary>
/// <param name="parent_Country_ID">The Parent_Country_ID parameter of the H07_RegionColl to fetch.</param>
/// <returns>A reference to the fetched <see cref="H07_RegionColl"/> collection.</returns>
internal static H07_RegionColl GetH07_RegionColl(int parent_Country_ID)
{
return DataPortal.FetchChild<H07_RegionColl>(parent_Country_ID);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="H07_RegionColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public H07_RegionColl()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="H07_RegionColl"/> collection from the database, based on given criteria.
/// </summary>
/// <param name="parent_Country_ID">The Parent Country ID.</param>
protected void Child_Fetch(int parent_Country_ID)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetH07_RegionColl", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Parent_Country_ID", parent_Country_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, parent_Country_ID);
OnFetchPre(args);
LoadCollection(cmd);
OnFetchPost(args);
}
}
foreach (var item in this)
{
item.FetchChildren();
}
}
private void LoadCollection(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
Fetch(dr);
}
}
/// <summary>
/// Loads all <see cref="H07_RegionColl"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
while (dr.Read())
{
Add(H08_Region.GetH08_Region(dr));
}
RaiseListChangedEvents = rlce;
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using Dks.SimpleToken.Core;
using Dks.SimpleToken.Validation.MVC5;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Dks.SimpleToken.MVC5.Tests
{
[TestClass]
public class MVCValidationFilterTest
{
private const string MatchingParameter = "testParam";
private ISecureTokenProvider _secureTokenProvider;
[TestInitialize]
public void Initialize()
{
_secureTokenProvider = new DummyTokenProvider();
MvcSimpleTokenValidator.ConfigureFilter(_secureTokenProvider);
}
[TestMethod]
public void ShouldDetectValidToken_InMVC5Filter()
{
//Token generation
var token = _secureTokenProvider.GenerateToken(new Dictionary<string, string> { { MatchingParameter, "value" } }, 60);
//Filter creation
var filter = new ValidateTokenAttribute(MatchingParameter);
//Filter context initialization
var filterContext = CraftFakeFilterContext(token);
filterContext.ActionParameters.Add(MatchingParameter, "value");
//Executing filter action
filter.OnActionExecuting(filterContext);
Assert.IsNull(filterContext.Result);
}
[TestMethod]
public void ShouldDetectMissingToken_InMVC5Filter()
{
//Filter creation
var filter = new ValidateTokenAttribute(MatchingParameter);
//Filter context initialization
var filterContext = CraftFakeFilterContext();
filterContext.ActionParameters.Add(MatchingParameter, "value");
//Executing filter action
filter.OnActionExecuting(filterContext);
Assert.IsInstanceOfType(filterContext.Result, typeof(HttpUnauthorizedResult));
}
[TestMethod]
public void ShouldDetectEmptyToken_InMVC5Filter()
{
//Filter creation
var filter = new ValidateTokenAttribute(MatchingParameter);
//Filter context initialization
var filterContext = CraftFakeFilterContext(" ");
filterContext.ActionParameters.Add(MatchingParameter, "value");
//Executing filter action
filter.OnActionExecuting(filterContext);
Assert.IsInstanceOfType(filterContext.Result, typeof(HttpUnauthorizedResult));
}
[TestMethod]
public void ShouldDetectInvalidToken_InMVC5Filter()
{
//Filter creation
var filter = new ValidateTokenAttribute(MatchingParameter);
//Filter context initialization
var filterContext = CraftFakeFilterContext("RANDOMSTRING");
filterContext.ActionParameters.Add(MatchingParameter, "value");
//Executing filter action
filter.OnActionExecuting(filterContext);
Assert.IsInstanceOfType(filterContext.Result, typeof(HttpUnauthorizedResult));
}
[TestMethod]
public void ShouldDetectExpiredToken_InMVC5Filter()
{
//Token generation
var token = _secureTokenProvider.GenerateToken(new Dictionary<string, string> { { MatchingParameter, "value" } }, 1);
//Waiting for token to expire
Thread.Sleep(1500);
//Filter creation
var filter = new ValidateTokenAttribute(MatchingParameter);
//Filter context initialization
var filterContext = CraftFakeFilterContext(token);
filterContext.ActionParameters.Add(MatchingParameter, "value");
//Executing filter action
filter.OnActionExecuting(filterContext);
Assert.IsInstanceOfType(filterContext.Result, typeof(HttpUnauthorizedResult));
}
[TestMethod]
public void ShouldDetectMismatchingParametersToken_InMVC5Filter()
{
//Token generation
var token = _secureTokenProvider.GenerateToken(new Dictionary<string, string> { { MatchingParameter, "value" } }, 60);
//Filter creation
var filter = new ValidateTokenAttribute(MatchingParameter);
//Filter context initialization
var filterContext = CraftFakeFilterContext(token);
filterContext.ActionParameters.Add(MatchingParameter, "anothervalue");
//Executing filter action
filter.OnActionExecuting(filterContext);
Assert.IsInstanceOfType(filterContext.Result, typeof(HttpStatusCodeResult));
Assert.AreEqual((int)HttpStatusCode.Forbidden, (filterContext.Result as HttpStatusCodeResult).StatusCode);
}
private static ActionExecutingContext CraftFakeFilterContext(string token = null)
{
return new ActionExecutingContext
{
ActionParameters = new Dictionary<string, object>(),
HttpContext = new HttpContextWrapper(
new HttpContext(
new HttpRequest(
"test",
"http://test",
token == null ? null : "token=" + token),
new HttpResponse(null)))
};
}
private class DummyTokenProvider : DefaultSecureTokenProvider
{
public DummyTokenProvider() : base(new DummyTokenSerializer(), new DummyTokenProtector())
{ }
private class DummyTokenProtector : ISecureTokenProtector
{
private static readonly byte[] DummyPreamble = Encoding.UTF8.GetBytes("DUMMY::__");
public byte[] ProtectData(byte[] unprotectedData)
{
return DummyPreamble.Concat(unprotectedData).ToArray();
}
public byte[] UnprotectData(byte[] protectedData)
{
if (protectedData.Length >= DummyPreamble.Length)
{
if (protectedData.Take(DummyPreamble.Length).SequenceEqual(DummyPreamble))
{
return protectedData.Skip(DummyPreamble.Length).ToArray();
}
}
throw new ApplicationException();
}
}
private class DummyTokenSerializer : ISecureTokenSerializer
{
public byte[] SerializeToken(SecureToken token)
{
return
Encoding.UTF8.GetBytes(
$"{token.Issued:O}:::{token.Expire:O}:::{string.Join("&&&", token.Data.Select(kvp => $"{kvp.Key}==={kvp.Value}"))}"
);
}
public SecureToken DeserializeToken(byte[] serialized)
{
var str = Encoding.UTF8.GetString(serialized).Split(new[] { ":::" }, StringSplitOptions.None);
var issued = DateTimeOffset.Parse(str[0]);
var expire = DateTimeOffset.Parse(str[1]);
var dict = str[2]
.Split(new[] { "&&&" }, StringSplitOptions.None)
.Select(p => p.Split(new[] { "===" }, StringSplitOptions.None))
.ToDictionary(pa => pa[0], pa => pa[1]);
return SecureToken.Create(issued, expire, dict);
}
}
}
}
}
| |
namespace EIDSS.Reports.Parameterized.Human.GG.Report
{
partial class InfectiousDiseasesMonthV6
{
#region 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(InfectiousDiseasesMonthV6));
DevExpress.XtraReports.UI.XRSummary xrSummary1 = new DevExpress.XtraReports.UI.XRSummary();
this.tableCustomHeader = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.EnTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell38 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell75 = new DevExpress.XtraReports.UI.XRTableCell();
this.m_HeaderDataSet = new EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthHeaderV6DataSet();
this.xrTableCell85 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell86 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell87 = new DevExpress.XtraReports.UI.XRTableCell();
this.EnTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell81 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell82 = new DevExpress.XtraReports.UI.XRTableCell();
this.GgTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.GgTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell89 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell92 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell93 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell95 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell97 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell90 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow23 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell70 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow21 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellNameOfrespondent = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow9 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellActualAddress = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow11 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow12 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow14 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell26 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellTelephone = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow15 = new DevExpress.XtraReports.UI.XRTableRow();
this.cellReportedPeriod = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell30 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell112 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell132 = new DevExpress.XtraReports.UI.XRTableCell();
this.m_DataSet = new EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthV6DataSet();
this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand();
this.tableCustomFooter = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow18 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell35 = new DevExpress.XtraReports.UI.XRTableCell();
this.DayFooterCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell34 = new DevExpress.XtraReports.UI.XRTableCell();
this.MonthFooterCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell331 = new DevExpress.XtraReports.UI.XRTableCell();
this.YearFooterCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell361 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell32 = new DevExpress.XtraReports.UI.XRTableCell();
this.ChiefFooterCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.CustomHeaderTable = new DevExpress.XtraReports.UI.XRTable();
this.CustomHeaderFirstRow = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell71 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell43 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell47 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell40 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell46 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell44 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell48 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell41 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell49 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell52 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell66 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell45 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell67 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell51 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell50 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell42 = new DevExpress.XtraReports.UI.XRTableCell();
this.CustomHeaderSecondRow = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell72 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell53 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell54 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell55 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell56 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell57 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell58 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell59 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell60 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell61 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell68 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell62 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell69 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell63 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell64 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell65 = new DevExpress.XtraReports.UI.XRTableCell();
this.DetailReport = new DevExpress.XtraReports.UI.DetailReportBand();
this.CustomDetail = new DevExpress.XtraReports.UI.DetailBand();
this.PageBreakAtLine36 = new DevExpress.XtraReports.UI.XRPageBreak();
this.formattingRule2 = new DevExpress.XtraReports.UI.FormattingRule();
this.DetailTable = new DevExpress.XtraReports.UI.XRTable();
this.formattingRule3 = new DevExpress.XtraReports.UI.FormattingRule();
this.DetailRow = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell73 = new DevExpress.XtraReports.UI.XRTableCell();
this.strDiseaseName = new DevExpress.XtraReports.UI.XRTableCell();
this.cellICD10 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellAge_0_1 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellAge_1_4 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellAge_5_14 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellAge_15_19 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellAge_20_29 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellAge_30_59 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellAge_60_more = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell94 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellTotal = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell96 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellLabTested = new DevExpress.XtraReports.UI.XRTableCell();
this.cellLabConfirmed = new DevExpress.XtraReports.UI.XRTableCell();
this.cellTotalConfirmed = new DevExpress.XtraReports.UI.XRTableCell();
this.CustomReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.m_Adapter = new EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthV6DataSetTableAdapters.MonthlyV6Adapter();
this.m_HeaderAdapter = new EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthHeaderV6DataSetTableAdapters.MonthlyHeaderV6Adapter();
this.cellLocation = new DevExpress.XtraReports.UI.XRLabel();
this.formattingRule1 = new DevExpress.XtraReports.UI.FormattingRule();
this.PrintDateTimeLabel = new DevExpress.XtraReports.UI.XRLabel();
this.GroupFooter = new DevExpress.XtraReports.UI.GroupFooterBand();
this.SignatureTable = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell36 = new DevExpress.XtraReports.UI.XRTableCell();
((System.ComponentModel.ISupportInitialize)(this.tableInterval)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableCustomHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.m_HeaderDataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableCustomFooter)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CustomHeaderTable)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.DetailTable)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.SignatureTable)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// tableInterval
//
resources.ApplyResources(this.tableInterval, "tableInterval");
this.tableInterval.StylePriority.UseBorders = false;
this.tableInterval.StylePriority.UseFont = false;
this.tableInterval.StylePriority.UsePadding = false;
//
// cellInputStartDate
//
this.cellInputStartDate.StylePriority.UseFont = false;
this.cellInputStartDate.StylePriority.UseTextAlignment = false;
//
// cellInputEndDate
//
this.cellInputEndDate.StylePriority.UseFont = false;
this.cellInputEndDate.StylePriority.UseTextAlignment = false;
//
// cellDefis
//
this.cellDefis.StylePriority.UseFont = false;
this.cellDefis.StylePriority.UseTextAlignment = false;
//
// cellLanguage
//
this.cellLanguage.StylePriority.UseTextAlignment = false;
//
// lblReportName
//
resources.ApplyResources(this.lblReportName, "lblReportName");
this.lblReportName.Multiline = true;
this.lblReportName.StylePriority.UseBorders = false;
this.lblReportName.StylePriority.UseBorderWidth = false;
this.lblReportName.StylePriority.UseFont = false;
this.lblReportName.StylePriority.UseTextAlignment = false;
//
// Detail
//
this.Detail.Expanded = false;
resources.ApplyResources(this.Detail, "Detail");
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
this.Detail.StylePriority.UseTextAlignment = false;
//
// PageHeader
//
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UsePadding = false;
this.PageHeader.StylePriority.UseTextAlignment = false;
//
// PageFooter
//
resources.ApplyResources(this.PageFooter, "PageFooter");
this.PageFooter.StylePriority.UseBorders = false;
//
// ReportHeader
//
this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.tableCustomHeader});
resources.ApplyResources(this.ReportHeader, "ReportHeader");
this.ReportHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.ReportHeader.StylePriority.UseFont = false;
this.ReportHeader.StylePriority.UsePadding = false;
this.ReportHeader.Controls.SetChildIndex(this.tableCustomHeader, 0);
this.ReportHeader.Controls.SetChildIndex(this.tableBaseHeader, 0);
//
// xrPageInfo1
//
resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1");
this.xrPageInfo1.StylePriority.UseBorders = false;
//
// cellReportHeader
//
this.cellReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.cellLocation});
this.cellReportHeader.StylePriority.UseBorders = false;
this.cellReportHeader.StylePriority.UseFont = false;
this.cellReportHeader.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.cellReportHeader, "cellReportHeader");
this.cellReportHeader.Controls.SetChildIndex(this.tableInterval, 0);
this.cellReportHeader.Controls.SetChildIndex(this.lblReportName, 0);
this.cellReportHeader.Controls.SetChildIndex(this.cellLocation, 0);
//
// cellBaseSite
//
this.cellBaseSite.StylePriority.UseBorders = false;
this.cellBaseSite.StylePriority.UseFont = false;
this.cellBaseSite.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.cellBaseSite, "cellBaseSite");
//
// cellBaseCountry
//
this.cellBaseCountry.StylePriority.UseFont = false;
//
// tableBaseHeader
//
resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader");
this.tableBaseHeader.StylePriority.UseBorders = false;
this.tableBaseHeader.StylePriority.UseBorderWidth = false;
this.tableBaseHeader.StylePriority.UseFont = false;
this.tableBaseHeader.StylePriority.UsePadding = false;
this.tableBaseHeader.StylePriority.UseTextAlignment = false;
//
// tableCustomHeader
//
resources.ApplyResources(this.tableCustomHeader, "tableCustomHeader");
this.tableCustomHeader.Name = "tableCustomHeader";
this.tableCustomHeader.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1,
this.xrTableRow2,
this.xrTableRow3,
this.xrTableRow4,
this.EnTableRow1,
this.EnTableRow2,
this.GgTableRow1,
this.GgTableRow2,
this.xrTableRow23,
this.xrTableRow21,
this.xrTableRow8,
this.xrTableRow9,
this.xrTableRow11,
this.xrTableRow12,
this.xrTableRow13,
this.xrTableRow14,
this.xrTableRow15,
this.xrTableRow5});
this.tableCustomHeader.StylePriority.UseFont = false;
this.tableCustomHeader.StylePriority.UseTextAlignment = false;
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell1});
this.xrTableRow1.Name = "xrTableRow1";
resources.ApplyResources(this.xrTableRow1, "xrTableRow1");
//
// xrTableCell1
//
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.Name = "xrTableCell1";
this.xrTableCell1.StylePriority.UseFont = false;
this.xrTableCell1.StylePriority.UseTextAlignment = false;
//
// xrTableRow2
//
this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell2});
this.xrTableRow2.Name = "xrTableRow2";
resources.ApplyResources(this.xrTableRow2, "xrTableRow2");
//
// xrTableCell2
//
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
this.xrTableCell2.Multiline = true;
this.xrTableCell2.Name = "xrTableCell2";
this.xrTableCell2.StylePriority.UseFont = false;
this.xrTableCell2.StylePriority.UseTextAlignment = false;
//
// xrTableRow3
//
this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell5,
this.xrTableCell6});
resources.ApplyResources(this.xrTableRow3, "xrTableRow3");
this.xrTableRow3.Name = "xrTableRow3";
this.xrTableRow3.StylePriority.UseFont = false;
this.xrTableRow3.StylePriority.UseTextAlignment = false;
//
// xrTableCell5
//
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
this.xrTableCell5.Multiline = true;
this.xrTableCell5.Name = "xrTableCell5";
this.xrTableCell5.Padding = new DevExpress.XtraPrinting.PaddingInfo(44, 2, 2, 2, 100F);
this.xrTableCell5.StylePriority.UseFont = false;
this.xrTableCell5.StylePriority.UsePadding = false;
this.xrTableCell5.StylePriority.UseTextAlignment = false;
//
// xrTableCell6
//
this.xrTableCell6.Name = "xrTableCell6";
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
//
// xrTableRow4
//
this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell9,
this.xrTableCell14});
resources.ApplyResources(this.xrTableRow4, "xrTableRow4");
this.xrTableRow4.Name = "xrTableRow4";
this.xrTableRow4.StylePriority.UseFont = false;
this.xrTableRow4.StylePriority.UseTextAlignment = false;
//
// xrTableCell9
//
this.xrTableCell9.Name = "xrTableCell9";
resources.ApplyResources(this.xrTableCell9, "xrTableCell9");
//
// xrTableCell14
//
this.xrTableCell14.Name = "xrTableCell14";
this.xrTableCell14.StylePriority.UseFont = false;
this.xrTableCell14.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell14, "xrTableCell14");
//
// EnTableRow1
//
this.EnTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell38,
this.xrTableCell3,
this.xrTableCell75,
this.xrTableCell85,
this.xrTableCell86,
this.xrTableCell87});
resources.ApplyResources(this.EnTableRow1, "EnTableRow1");
this.EnTableRow1.Name = "EnTableRow1";
this.EnTableRow1.StylePriority.UseFont = false;
this.EnTableRow1.StylePriority.UsePadding = false;
this.EnTableRow1.StylePriority.UseTextAlignment = false;
//
// xrTableCell38
//
this.xrTableCell38.Name = "xrTableCell38";
resources.ApplyResources(this.xrTableCell38, "xrTableCell38");
//
// xrTableCell3
//
this.xrTableCell3.Name = "xrTableCell3";
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
//
// xrTableCell75
//
this.xrTableCell75.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell75.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.m_HeaderDataSet, "MonthlyHeaderV6.strOrderNumber")});
this.xrTableCell75.Name = "xrTableCell75";
this.xrTableCell75.StylePriority.UseBorders = false;
this.xrTableCell75.StylePriority.UseFont = false;
this.xrTableCell75.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell75, "xrTableCell75");
//
// m_HeaderDataSet
//
this.m_HeaderDataSet.DataSetName = "InfectiousDiseaseMonthNewHeaderDataSet";
this.m_HeaderDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// xrTableCell85
//
this.xrTableCell85.Name = "xrTableCell85";
resources.ApplyResources(this.xrTableCell85, "xrTableCell85");
//
// xrTableCell86
//
this.xrTableCell86.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell86.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.m_HeaderDataSet, "MonthlyHeaderV6.strOrderDate")});
this.xrTableCell86.Name = "xrTableCell86";
this.xrTableCell86.StylePriority.UseBorders = false;
this.xrTableCell86.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell86, "xrTableCell86");
//
// xrTableCell87
//
this.xrTableCell87.Name = "xrTableCell87";
resources.ApplyResources(this.xrTableCell87, "xrTableCell87");
//
// EnTableRow2
//
this.EnTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell81,
this.xrTableCell82});
resources.ApplyResources(this.EnTableRow2, "EnTableRow2");
this.EnTableRow2.Name = "EnTableRow2";
this.EnTableRow2.StylePriority.UseFont = false;
this.EnTableRow2.StylePriority.UsePadding = false;
this.EnTableRow2.StylePriority.UseTextAlignment = false;
//
// xrTableCell81
//
this.xrTableCell81.Name = "xrTableCell81";
resources.ApplyResources(this.xrTableCell81, "xrTableCell81");
//
// xrTableCell82
//
this.xrTableCell82.Name = "xrTableCell82";
this.xrTableCell82.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell82, "xrTableCell82");
//
// GgTableRow1
//
this.GgTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell7,
this.xrTableCell8});
resources.ApplyResources(this.GgTableRow1, "GgTableRow1");
this.GgTableRow1.Name = "GgTableRow1";
this.GgTableRow1.StylePriority.UseFont = false;
this.GgTableRow1.StylePriority.UsePadding = false;
this.GgTableRow1.StylePriority.UseTextAlignment = false;
//
// xrTableCell7
//
this.xrTableCell7.Name = "xrTableCell7";
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
//
// xrTableCell8
//
resources.ApplyResources(this.xrTableCell8, "xrTableCell8");
this.xrTableCell8.Name = "xrTableCell8";
this.xrTableCell8.StylePriority.UseFont = false;
this.xrTableCell8.Tag = "UnchangedFont";
//
// GgTableRow2
//
this.GgTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell89,
this.xrTableCell92,
this.xrTableCell93,
this.xrTableCell95,
this.xrTableCell97,
this.xrTableCell90});
resources.ApplyResources(this.GgTableRow2, "GgTableRow2");
this.GgTableRow2.Name = "GgTableRow2";
this.GgTableRow2.StylePriority.UseFont = false;
this.GgTableRow2.StylePriority.UsePadding = false;
this.GgTableRow2.StylePriority.UseTextAlignment = false;
//
// xrTableCell89
//
this.xrTableCell89.Name = "xrTableCell89";
resources.ApplyResources(this.xrTableCell89, "xrTableCell89");
//
// xrTableCell92
//
resources.ApplyResources(this.xrTableCell92, "xrTableCell92");
this.xrTableCell92.Name = "xrTableCell92";
this.xrTableCell92.StylePriority.UseFont = false;
this.xrTableCell92.Tag = "UnchangedFont";
//
// xrTableCell93
//
this.xrTableCell93.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell93.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.m_HeaderDataSet, "MonthlyHeaderV6.strOrderDate")});
resources.ApplyResources(this.xrTableCell93, "xrTableCell93");
this.xrTableCell93.Name = "xrTableCell93";
this.xrTableCell93.StylePriority.UseBorders = false;
this.xrTableCell93.StylePriority.UseFont = false;
this.xrTableCell93.StylePriority.UseTextAlignment = false;
this.xrTableCell93.Tag = "UnchangedFont";
//
// xrTableCell95
//
resources.ApplyResources(this.xrTableCell95, "xrTableCell95");
this.xrTableCell95.Name = "xrTableCell95";
this.xrTableCell95.StylePriority.UseFont = false;
this.xrTableCell95.Tag = "UnchangedFont";
//
// xrTableCell97
//
this.xrTableCell97.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell97.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.m_HeaderDataSet, "MonthlyHeaderV6.strOrderNumber")});
resources.ApplyResources(this.xrTableCell97, "xrTableCell97");
this.xrTableCell97.Name = "xrTableCell97";
this.xrTableCell97.StylePriority.UseBorders = false;
this.xrTableCell97.StylePriority.UseFont = false;
this.xrTableCell97.StylePriority.UseTextAlignment = false;
this.xrTableCell97.Tag = "UnchangedFont";
//
// xrTableCell90
//
resources.ApplyResources(this.xrTableCell90, "xrTableCell90");
this.xrTableCell90.Name = "xrTableCell90";
this.xrTableCell90.StylePriority.UseFont = false;
this.xrTableCell90.Tag = "UnchangedFont";
//
// xrTableRow23
//
this.xrTableRow23.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell70});
this.xrTableRow23.Name = "xrTableRow23";
this.xrTableRow23.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableRow23, "xrTableRow23");
//
// xrTableCell70
//
resources.ApplyResources(this.xrTableCell70, "xrTableCell70");
this.xrTableCell70.Multiline = true;
this.xrTableCell70.Name = "xrTableCell70";
this.xrTableCell70.StylePriority.UseFont = false;
this.xrTableCell70.StylePriority.UseTextAlignment = false;
//
// xrTableRow21
//
this.xrTableRow21.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell16,
this.xrTableCell27});
this.xrTableRow21.Name = "xrTableRow21";
resources.ApplyResources(this.xrTableRow21, "xrTableRow21");
//
// xrTableCell16
//
this.xrTableCell16.Name = "xrTableCell16";
resources.ApplyResources(this.xrTableCell16, "xrTableCell16");
//
// xrTableCell27
//
resources.ApplyResources(this.xrTableCell27, "xrTableCell27");
this.xrTableCell27.Multiline = true;
this.xrTableCell27.Name = "xrTableCell27";
this.xrTableCell27.StylePriority.UseFont = false;
//
// xrTableRow8
//
this.xrTableRow8.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell10,
this.cellNameOfrespondent});
this.xrTableRow8.Name = "xrTableRow8";
resources.ApplyResources(this.xrTableRow8, "xrTableRow8");
//
// xrTableCell10
//
this.xrTableCell10.Name = "xrTableCell10";
this.xrTableCell10.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell10, "xrTableCell10");
//
// cellNameOfrespondent
//
resources.ApplyResources(this.cellNameOfrespondent, "cellNameOfrespondent");
this.cellNameOfrespondent.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
this.cellNameOfrespondent.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.m_HeaderDataSet, "MonthlyHeaderV6.strNameOfRespondent")});
this.cellNameOfrespondent.Name = "cellNameOfrespondent";
this.cellNameOfrespondent.StylePriority.UseBackColor = false;
this.cellNameOfrespondent.StylePriority.UseBorders = false;
this.cellNameOfrespondent.StylePriority.UseFont = false;
//
// xrTableRow9
//
this.xrTableRow9.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell12,
this.cellActualAddress});
this.xrTableRow9.Name = "xrTableRow9";
resources.ApplyResources(this.xrTableRow9, "xrTableRow9");
//
// xrTableCell12
//
this.xrTableCell12.Name = "xrTableCell12";
this.xrTableCell12.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell12, "xrTableCell12");
//
// cellActualAddress
//
resources.ApplyResources(this.cellActualAddress, "cellActualAddress");
this.cellActualAddress.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
this.cellActualAddress.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.m_HeaderDataSet, "MonthlyHeaderV6.strActualAddress")});
this.cellActualAddress.Name = "cellActualAddress";
this.cellActualAddress.StylePriority.UseBackColor = false;
this.cellActualAddress.StylePriority.UseBorders = false;
this.cellActualAddress.StylePriority.UseFont = false;
//
// xrTableRow11
//
this.xrTableRow11.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell17,
this.xrTableCell18});
this.xrTableRow11.Name = "xrTableRow11";
resources.ApplyResources(this.xrTableRow11, "xrTableRow11");
//
// xrTableCell17
//
this.xrTableCell17.Name = "xrTableCell17";
this.xrTableCell17.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell17, "xrTableCell17");
//
// xrTableCell18
//
resources.ApplyResources(this.xrTableCell18, "xrTableCell18");
this.xrTableCell18.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
this.xrTableCell18.Name = "xrTableCell18";
this.xrTableCell18.StylePriority.UseBackColor = false;
this.xrTableCell18.StylePriority.UseBorders = false;
this.xrTableCell18.StylePriority.UseFont = false;
//
// xrTableRow12
//
this.xrTableRow12.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell20,
this.xrTableCell21});
this.xrTableRow12.Name = "xrTableRow12";
resources.ApplyResources(this.xrTableRow12, "xrTableRow12");
//
// xrTableCell20
//
this.xrTableCell20.Name = "xrTableCell20";
this.xrTableCell20.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell20, "xrTableCell20");
//
// xrTableCell21
//
resources.ApplyResources(this.xrTableCell21, "xrTableCell21");
this.xrTableCell21.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
this.xrTableCell21.Name = "xrTableCell21";
this.xrTableCell21.StylePriority.UseBackColor = false;
this.xrTableCell21.StylePriority.UseBorders = false;
this.xrTableCell21.StylePriority.UseFont = false;
//
// xrTableRow13
//
this.xrTableRow13.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell23,
this.xrTableCell24});
this.xrTableRow13.Name = "xrTableRow13";
resources.ApplyResources(this.xrTableRow13, "xrTableRow13");
//
// xrTableCell23
//
this.xrTableCell23.Name = "xrTableCell23";
this.xrTableCell23.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell23, "xrTableCell23");
//
// xrTableCell24
//
resources.ApplyResources(this.xrTableCell24, "xrTableCell24");
this.xrTableCell24.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
this.xrTableCell24.Name = "xrTableCell24";
this.xrTableCell24.StylePriority.UseBackColor = false;
this.xrTableCell24.StylePriority.UseBorders = false;
this.xrTableCell24.StylePriority.UseFont = false;
//
// xrTableRow14
//
this.xrTableRow14.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell26,
this.cellTelephone});
this.xrTableRow14.Name = "xrTableRow14";
resources.ApplyResources(this.xrTableRow14, "xrTableRow14");
//
// xrTableCell26
//
this.xrTableCell26.Name = "xrTableCell26";
this.xrTableCell26.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell26, "xrTableCell26");
//
// cellTelephone
//
resources.ApplyResources(this.cellTelephone, "cellTelephone");
this.cellTelephone.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.cellTelephone.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.m_HeaderDataSet, "MonthlyHeaderV6.strTelephone")});
this.cellTelephone.Name = "cellTelephone";
this.cellTelephone.StylePriority.UseBackColor = false;
this.cellTelephone.StylePriority.UseBorders = false;
this.cellTelephone.StylePriority.UseFont = false;
//
// xrTableRow15
//
this.xrTableRow15.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.cellReportedPeriod,
this.xrTableCell30});
this.xrTableRow15.Name = "xrTableRow15";
resources.ApplyResources(this.xrTableRow15, "xrTableRow15");
//
// cellReportedPeriod
//
this.cellReportedPeriod.Name = "cellReportedPeriod";
this.cellReportedPeriod.StylePriority.UseFont = false;
resources.ApplyResources(this.cellReportedPeriod, "cellReportedPeriod");
//
// xrTableCell30
//
this.xrTableCell30.Name = "xrTableCell30";
this.xrTableCell30.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 2, 2, 100F);
this.xrTableCell30.StylePriority.UseFont = false;
this.xrTableCell30.StylePriority.UsePadding = false;
resources.ApplyResources(this.xrTableCell30, "xrTableCell30");
//
// xrTableRow5
//
this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell112,
this.xrTableCell132});
this.xrTableRow5.Name = "xrTableRow5";
resources.ApplyResources(this.xrTableRow5, "xrTableRow5");
//
// xrTableCell112
//
resources.ApplyResources(this.xrTableCell112, "xrTableCell112");
this.xrTableCell112.Name = "xrTableCell112";
this.xrTableCell112.StylePriority.UseFont = false;
//
// xrTableCell132
//
this.xrTableCell132.Name = "xrTableCell132";
this.xrTableCell132.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 2, 2, 100F);
this.xrTableCell132.StylePriority.UsePadding = false;
resources.ApplyResources(this.xrTableCell132, "xrTableCell132");
//
// m_DataSet
//
this.m_DataSet.DataSetName = "MonthDataSet";
this.m_DataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// ReportFooter
//
this.ReportFooter.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.tableCustomFooter,
this.PrintDateTimeLabel});
resources.ApplyResources(this.ReportFooter, "ReportFooter");
this.ReportFooter.Name = "ReportFooter";
this.ReportFooter.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
this.ReportFooter.StylePriority.UseFont = false;
this.ReportFooter.StylePriority.UsePadding = false;
this.ReportFooter.StylePriority.UseTextAlignment = false;
//
// tableCustomFooter
//
resources.ApplyResources(this.tableCustomFooter, "tableCustomFooter");
this.tableCustomFooter.Name = "tableCustomFooter";
this.tableCustomFooter.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow18});
this.tableCustomFooter.StylePriority.UseFont = false;
//
// xrTableRow18
//
this.xrTableRow18.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell35,
this.DayFooterCell,
this.xrTableCell34,
this.MonthFooterCell,
this.xrTableCell331,
this.YearFooterCell,
this.xrTableCell361,
this.xrTableCell32,
this.ChiefFooterCell,
this.xrTableCell4});
this.xrTableRow18.Name = "xrTableRow18";
resources.ApplyResources(this.xrTableRow18, "xrTableRow18");
//
// xrTableCell35
//
resources.ApplyResources(this.xrTableCell35, "xrTableCell35");
this.xrTableCell35.Name = "xrTableCell35";
this.xrTableCell35.StylePriority.UseFont = false;
//
// DayFooterCell
//
this.DayFooterCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.DayFooterCell.Name = "DayFooterCell";
this.DayFooterCell.StylePriority.UseBorders = false;
this.DayFooterCell.StylePriority.UseFont = false;
this.DayFooterCell.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.DayFooterCell, "DayFooterCell");
//
// xrTableCell34
//
resources.ApplyResources(this.xrTableCell34, "xrTableCell34");
this.xrTableCell34.Name = "xrTableCell34";
this.xrTableCell34.StylePriority.UseFont = false;
//
// MonthFooterCell
//
this.MonthFooterCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.MonthFooterCell.Name = "MonthFooterCell";
this.MonthFooterCell.StylePriority.UseBorders = false;
this.MonthFooterCell.StylePriority.UseFont = false;
this.MonthFooterCell.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.MonthFooterCell, "MonthFooterCell");
//
// xrTableCell331
//
this.xrTableCell331.Borders = DevExpress.XtraPrinting.BorderSide.None;
this.xrTableCell331.Name = "xrTableCell331";
this.xrTableCell331.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell331, "xrTableCell331");
//
// YearFooterCell
//
this.YearFooterCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.YearFooterCell.Name = "YearFooterCell";
this.YearFooterCell.StylePriority.UseBorders = false;
this.YearFooterCell.StylePriority.UseFont = false;
this.YearFooterCell.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.YearFooterCell, "YearFooterCell");
//
// xrTableCell361
//
this.xrTableCell361.Name = "xrTableCell361";
this.xrTableCell361.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell361, "xrTableCell361");
//
// xrTableCell32
//
this.xrTableCell32.Name = "xrTableCell32";
this.xrTableCell32.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell32, "xrTableCell32");
//
// ChiefFooterCell
//
this.ChiefFooterCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.ChiefFooterCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.m_HeaderDataSet, "MonthlyHeaderV6.strChief")});
this.ChiefFooterCell.Name = "ChiefFooterCell";
this.ChiefFooterCell.StylePriority.UseBorders = false;
this.ChiefFooterCell.StylePriority.UseFont = false;
resources.ApplyResources(this.ChiefFooterCell, "ChiefFooterCell");
//
// xrTableCell4
//
this.xrTableCell4.Name = "xrTableCell4";
this.xrTableCell4.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
//
// CustomHeaderTable
//
this.CustomHeaderTable.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.CustomHeaderTable, "CustomHeaderTable");
this.CustomHeaderTable.Name = "CustomHeaderTable";
this.CustomHeaderTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.CustomHeaderFirstRow,
this.CustomHeaderSecondRow});
this.CustomHeaderTable.StylePriority.UseBorders = false;
//
// CustomHeaderFirstRow
//
this.CustomHeaderFirstRow.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell71,
this.xrTableCell43,
this.xrTableCell47,
this.xrTableCell40,
this.xrTableCell46,
this.xrTableCell44,
this.xrTableCell48,
this.xrTableCell41,
this.xrTableCell49,
this.xrTableCell52,
this.xrTableCell66,
this.xrTableCell45,
this.xrTableCell67,
this.xrTableCell51,
this.xrTableCell50,
this.xrTableCell42});
this.CustomHeaderFirstRow.Name = "CustomHeaderFirstRow";
resources.ApplyResources(this.CustomHeaderFirstRow, "CustomHeaderFirstRow");
//
// xrTableCell71
//
this.xrTableCell71.Name = "xrTableCell71";
this.xrTableCell71.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell71, "xrTableCell71");
//
// xrTableCell43
//
this.xrTableCell43.Name = "xrTableCell43";
this.xrTableCell43.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell43, "xrTableCell43");
//
// xrTableCell47
//
this.xrTableCell47.Name = "xrTableCell47";
this.xrTableCell47.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell47, "xrTableCell47");
//
// xrTableCell40
//
this.xrTableCell40.Name = "xrTableCell40";
this.xrTableCell40.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell40, "xrTableCell40");
//
// xrTableCell46
//
this.xrTableCell46.Name = "xrTableCell46";
this.xrTableCell46.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell46, "xrTableCell46");
//
// xrTableCell44
//
this.xrTableCell44.Name = "xrTableCell44";
this.xrTableCell44.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell44, "xrTableCell44");
//
// xrTableCell48
//
this.xrTableCell48.Name = "xrTableCell48";
this.xrTableCell48.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell48, "xrTableCell48");
//
// xrTableCell41
//
this.xrTableCell41.Name = "xrTableCell41";
this.xrTableCell41.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell41, "xrTableCell41");
//
// xrTableCell49
//
this.xrTableCell49.Name = "xrTableCell49";
this.xrTableCell49.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell49, "xrTableCell49");
//
// xrTableCell52
//
this.xrTableCell52.Name = "xrTableCell52";
this.xrTableCell52.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell52, "xrTableCell52");
//
// xrTableCell66
//
this.xrTableCell66.Name = "xrTableCell66";
resources.ApplyResources(this.xrTableCell66, "xrTableCell66");
//
// xrTableCell45
//
this.xrTableCell45.Name = "xrTableCell45";
this.xrTableCell45.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell45, "xrTableCell45");
//
// xrTableCell67
//
this.xrTableCell67.Name = "xrTableCell67";
resources.ApplyResources(this.xrTableCell67, "xrTableCell67");
//
// xrTableCell51
//
this.xrTableCell51.Angle = 90F;
this.xrTableCell51.Name = "xrTableCell51";
this.xrTableCell51.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell51, "xrTableCell51");
//
// xrTableCell50
//
this.xrTableCell50.Angle = 90F;
this.xrTableCell50.Name = "xrTableCell50";
this.xrTableCell50.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell50, "xrTableCell50");
//
// xrTableCell42
//
this.xrTableCell42.Angle = 90F;
this.xrTableCell42.Name = "xrTableCell42";
this.xrTableCell42.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell42, "xrTableCell42");
//
// CustomHeaderSecondRow
//
this.CustomHeaderSecondRow.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell72,
this.xrTableCell53,
this.xrTableCell54,
this.xrTableCell55,
this.xrTableCell56,
this.xrTableCell57,
this.xrTableCell58,
this.xrTableCell59,
this.xrTableCell60,
this.xrTableCell61,
this.xrTableCell68,
this.xrTableCell62,
this.xrTableCell69,
this.xrTableCell63,
this.xrTableCell64,
this.xrTableCell65});
this.CustomHeaderSecondRow.Name = "CustomHeaderSecondRow";
this.CustomHeaderSecondRow.StylePriority.UseBorders = false;
this.CustomHeaderSecondRow.StylePriority.UsePadding = false;
resources.ApplyResources(this.CustomHeaderSecondRow, "CustomHeaderSecondRow");
//
// xrTableCell72
//
this.xrTableCell72.Name = "xrTableCell72";
resources.ApplyResources(this.xrTableCell72, "xrTableCell72");
//
// xrTableCell53
//
this.xrTableCell53.Name = "xrTableCell53";
this.xrTableCell53.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell53, "xrTableCell53");
//
// xrTableCell54
//
this.xrTableCell54.Name = "xrTableCell54";
this.xrTableCell54.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell54, "xrTableCell54");
//
// xrTableCell55
//
this.xrTableCell55.Name = "xrTableCell55";
this.xrTableCell55.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell55, "xrTableCell55");
//
// xrTableCell56
//
this.xrTableCell56.Name = "xrTableCell56";
this.xrTableCell56.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell56, "xrTableCell56");
//
// xrTableCell57
//
this.xrTableCell57.Name = "xrTableCell57";
this.xrTableCell57.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell57, "xrTableCell57");
//
// xrTableCell58
//
this.xrTableCell58.Name = "xrTableCell58";
this.xrTableCell58.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell58, "xrTableCell58");
//
// xrTableCell59
//
this.xrTableCell59.Name = "xrTableCell59";
this.xrTableCell59.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell59, "xrTableCell59");
//
// xrTableCell60
//
this.xrTableCell60.Name = "xrTableCell60";
this.xrTableCell60.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell60, "xrTableCell60");
//
// xrTableCell61
//
this.xrTableCell61.Name = "xrTableCell61";
this.xrTableCell61.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell61, "xrTableCell61");
//
// xrTableCell68
//
this.xrTableCell68.Name = "xrTableCell68";
resources.ApplyResources(this.xrTableCell68, "xrTableCell68");
//
// xrTableCell62
//
this.xrTableCell62.Name = "xrTableCell62";
this.xrTableCell62.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell62, "xrTableCell62");
//
// xrTableCell69
//
this.xrTableCell69.Name = "xrTableCell69";
resources.ApplyResources(this.xrTableCell69, "xrTableCell69");
//
// xrTableCell63
//
this.xrTableCell63.Name = "xrTableCell63";
this.xrTableCell63.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell63, "xrTableCell63");
//
// xrTableCell64
//
this.xrTableCell64.Name = "xrTableCell64";
this.xrTableCell64.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell64, "xrTableCell64");
//
// xrTableCell65
//
this.xrTableCell65.Name = "xrTableCell65";
this.xrTableCell65.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell65, "xrTableCell65");
//
// DetailReport
//
this.DetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.CustomDetail,
this.CustomReportHeader});
this.DetailReport.DataAdapter = this.m_Adapter;
this.DetailReport.DataMember = "MonthlyV6";
this.DetailReport.DataSource = this.m_DataSet;
resources.ApplyResources(this.DetailReport, "DetailReport");
this.DetailReport.Level = 0;
this.DetailReport.Name = "DetailReport";
this.DetailReport.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
//
// CustomDetail
//
this.CustomDetail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.PageBreakAtLine36,
this.DetailTable});
resources.ApplyResources(this.CustomDetail, "CustomDetail");
this.CustomDetail.Name = "CustomDetail";
this.CustomDetail.StylePriority.UseFont = false;
this.CustomDetail.StylePriority.UseTextAlignment = false;
//
// PageBreakAtLine36
//
this.PageBreakAtLine36.FormattingRules.Add(this.formattingRule2);
resources.ApplyResources(this.PageBreakAtLine36, "PageBreakAtLine36");
this.PageBreakAtLine36.Name = "PageBreakAtLine36";
//
// formattingRule2
//
this.formattingRule2.Condition = "[DataSource.CurrentRowIndex] ==36";
this.formattingRule2.DataMember = "MonthlyV6";
this.formattingRule2.DataSource = this.m_DataSet;
//
//
//
this.formattingRule2.Formatting.Visible = DevExpress.Utils.DefaultBoolean.True;
this.formattingRule2.Name = "formattingRule2";
//
// DetailTable
//
this.DetailTable.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.DetailTable.FormattingRules.Add(this.formattingRule3);
resources.ApplyResources(this.DetailTable, "DetailTable");
this.DetailTable.Name = "DetailTable";
this.DetailTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.DetailRow});
this.DetailTable.StylePriority.UseBorders = false;
this.DetailTable.StylePriority.UseFont = false;
this.DetailTable.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// formattingRule3
//
this.formattingRule3.Condition = "[DataSource.CurrentRowIndex] ==36";
//
//
//
this.formattingRule3.Formatting.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.formattingRule3.Name = "formattingRule3";
//
// DetailRow
//
this.DetailRow.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell73,
this.strDiseaseName,
this.cellICD10,
this.cellAge_0_1,
this.cellAge_1_4,
this.cellAge_5_14,
this.cellAge_15_19,
this.cellAge_20_29,
this.cellAge_30_59,
this.cellAge_60_more,
this.xrTableCell94,
this.cellTotal,
this.xrTableCell96,
this.cellLabTested,
this.cellLabConfirmed,
this.cellTotalConfirmed});
this.DetailRow.Name = "DetailRow";
this.DetailRow.StylePriority.UseBorders = false;
resources.ApplyResources(this.DetailRow, "DetailRow");
//
// xrTableCell73
//
this.xrTableCell73.Name = "xrTableCell73";
this.xrTableCell73.StylePriority.UseFont = false;
xrSummary1.Func = DevExpress.XtraReports.UI.SummaryFunc.RecordNumber;
xrSummary1.Running = DevExpress.XtraReports.UI.SummaryRunning.Report;
this.xrTableCell73.Summary = xrSummary1;
resources.ApplyResources(this.xrTableCell73, "xrTableCell73");
this.xrTableCell73.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.NumberingCellBeforePrint);
//
// strDiseaseName
//
this.strDiseaseName.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MonthlyV6.strDiseaseName")});
this.strDiseaseName.Name = "strDiseaseName";
this.strDiseaseName.StylePriority.UseFont = false;
this.strDiseaseName.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.strDiseaseName, "strDiseaseName");
this.strDiseaseName.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellICD10
//
this.cellICD10.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MonthlyV6.strICD10")});
this.cellICD10.Name = "cellICD10";
this.cellICD10.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.cellICD10.StylePriority.UseFont = false;
this.cellICD10.StylePriority.UsePadding = false;
resources.ApplyResources(this.cellICD10, "cellICD10");
this.cellICD10.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellAge_0_1
//
this.cellAge_0_1.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MonthlyV6.intAge_0_1")});
this.cellAge_0_1.Name = "cellAge_0_1";
this.cellAge_0_1.StylePriority.UseFont = false;
resources.ApplyResources(this.cellAge_0_1, "cellAge_0_1");
this.cellAge_0_1.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellAge_1_4
//
this.cellAge_1_4.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MonthlyV6.intAge_1_4")});
this.cellAge_1_4.Name = "cellAge_1_4";
this.cellAge_1_4.StylePriority.UseFont = false;
resources.ApplyResources(this.cellAge_1_4, "cellAge_1_4");
this.cellAge_1_4.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellAge_5_14
//
this.cellAge_5_14.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MonthlyV6.intAge_5_14")});
this.cellAge_5_14.Name = "cellAge_5_14";
this.cellAge_5_14.StylePriority.UseFont = false;
resources.ApplyResources(this.cellAge_5_14, "cellAge_5_14");
this.cellAge_5_14.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellAge_15_19
//
this.cellAge_15_19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MonthlyV6.intAge_15_19")});
this.cellAge_15_19.Name = "cellAge_15_19";
this.cellAge_15_19.StylePriority.UseFont = false;
resources.ApplyResources(this.cellAge_15_19, "cellAge_15_19");
this.cellAge_15_19.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellAge_20_29
//
this.cellAge_20_29.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MonthlyV6.intAge_20_29")});
this.cellAge_20_29.Name = "cellAge_20_29";
this.cellAge_20_29.StylePriority.UseFont = false;
resources.ApplyResources(this.cellAge_20_29, "cellAge_20_29");
this.cellAge_20_29.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellAge_30_59
//
this.cellAge_30_59.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MonthlyV6.intAge_30_59")});
this.cellAge_30_59.Name = "cellAge_30_59";
this.cellAge_30_59.StylePriority.UseFont = false;
resources.ApplyResources(this.cellAge_30_59, "cellAge_30_59");
this.cellAge_30_59.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellAge_60_more
//
this.cellAge_60_more.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MonthlyV6.intAge_60_more")});
this.cellAge_60_more.Name = "cellAge_60_more";
this.cellAge_60_more.StylePriority.UseFont = false;
resources.ApplyResources(this.cellAge_60_more, "cellAge_60_more");
this.cellAge_60_more.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// xrTableCell94
//
this.xrTableCell94.Name = "xrTableCell94";
resources.ApplyResources(this.xrTableCell94, "xrTableCell94");
//
// cellTotal
//
this.cellTotal.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MonthlyV6.intTotal")});
this.cellTotal.Name = "cellTotal";
this.cellTotal.StylePriority.UseFont = false;
resources.ApplyResources(this.cellTotal, "cellTotal");
this.cellTotal.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellTotalBeforePrint);
//
// xrTableCell96
//
this.xrTableCell96.Name = "xrTableCell96";
resources.ApplyResources(this.xrTableCell96, "xrTableCell96");
//
// cellLabTested
//
this.cellLabTested.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MonthlyV6.intLabTested")});
this.cellLabTested.Name = "cellLabTested";
this.cellLabTested.StylePriority.UseFont = false;
resources.ApplyResources(this.cellLabTested, "cellLabTested");
this.cellLabTested.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellLabBeforePrint);
//
// cellLabConfirmed
//
this.cellLabConfirmed.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MonthlyV6.intLabConfirmed")});
this.cellLabConfirmed.Name = "cellLabConfirmed";
this.cellLabConfirmed.StylePriority.UseFont = false;
resources.ApplyResources(this.cellLabConfirmed, "cellLabConfirmed");
this.cellLabConfirmed.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellLabBeforePrint);
//
// cellTotalConfirmed
//
this.cellTotalConfirmed.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MonthlyV6.intTotalConfirmed")});
this.cellTotalConfirmed.Name = "cellTotalConfirmed";
this.cellTotalConfirmed.StylePriority.UseFont = false;
resources.ApplyResources(this.cellTotalConfirmed, "cellTotalConfirmed");
this.cellTotalConfirmed.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellLabBeforePrint);
//
// CustomReportHeader
//
this.CustomReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.CustomHeaderTable});
resources.ApplyResources(this.CustomReportHeader, "CustomReportHeader");
this.CustomReportHeader.Name = "CustomReportHeader";
this.CustomReportHeader.StylePriority.UseTextAlignment = false;
//
// m_Adapter
//
this.m_Adapter.ClearBeforeFill = true;
//
// m_HeaderAdapter
//
this.m_HeaderAdapter.ClearBeforeFill = true;
//
// cellLocation
//
this.cellLocation.Borders = DevExpress.XtraPrinting.BorderSide.None;
this.cellLocation.BorderWidth = 0F;
resources.ApplyResources(this.cellLocation, "cellLocation");
this.cellLocation.Name = "cellLocation";
this.cellLocation.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.cellLocation.StylePriority.UseBorders = false;
this.cellLocation.StylePriority.UseBorderWidth = false;
this.cellLocation.StylePriority.UseFont = false;
this.cellLocation.StylePriority.UseTextAlignment = false;
//
// formattingRule1
//
this.formattingRule1.Name = "formattingRule1";
//
// PrintDateTimeLabel
//
this.PrintDateTimeLabel.Borders = DevExpress.XtraPrinting.BorderSide.None;
resources.ApplyResources(this.PrintDateTimeLabel, "PrintDateTimeLabel");
this.PrintDateTimeLabel.Name = "PrintDateTimeLabel";
this.PrintDateTimeLabel.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.PrintDateTimeLabel.StylePriority.UseBorders = false;
this.PrintDateTimeLabel.StylePriority.UseFont = false;
this.PrintDateTimeLabel.PrintOnPage += new DevExpress.XtraReports.UI.PrintOnPageEventHandler(this.PrintDateTimeLabel_PrintOnPage);
//
// GroupFooter
//
this.GroupFooter.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.SignatureTable});
resources.ApplyResources(this.GroupFooter, "GroupFooter");
this.GroupFooter.Name = "GroupFooter";
//
// SignatureTable
//
resources.ApplyResources(this.SignatureTable, "SignatureTable");
this.SignatureTable.Name = "SignatureTable";
this.SignatureTable.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
this.SignatureTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow7});
this.SignatureTable.StylePriority.UseFont = false;
this.SignatureTable.StylePriority.UsePadding = false;
this.SignatureTable.StylePriority.UseTextAlignment = false;
//
// xrTableRow7
//
this.xrTableRow7.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell36});
this.xrTableRow7.Name = "xrTableRow7";
resources.ApplyResources(this.xrTableRow7, "xrTableRow7");
//
// xrTableCell36
//
this.xrTableCell36.Name = "xrTableCell36";
this.xrTableCell36.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell36, "xrTableCell36");
//
// InfectiousDiseasesMonthV6
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.ReportFooter,
this.DetailReport,
this.GroupFooter});
resources.ApplyResources(this, "$this");
this.FormattingRuleSheet.AddRange(new DevExpress.XtraReports.UI.FormattingRule[] {
this.formattingRule1,
this.formattingRule2,
this.formattingRule3});
this.Version = "15.1";
this.Controls.SetChildIndex(this.GroupFooter, 0);
this.Controls.SetChildIndex(this.DetailReport, 0);
this.Controls.SetChildIndex(this.ReportFooter, 0);
this.Controls.SetChildIndex(this.ReportHeader, 0);
this.Controls.SetChildIndex(this.PageFooter, 0);
this.Controls.SetChildIndex(this.PageHeader, 0);
this.Controls.SetChildIndex(this.Detail, 0);
((System.ComponentModel.ISupportInitialize)(this.tableInterval)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableCustomHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.m_HeaderDataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableCustomFooter)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CustomHeaderTable)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.DetailTable)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.SignatureTable)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.XRTable tableCustomHeader;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow8;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell10;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.XRTableCell cellNameOfrespondent;
private DevExpress.XtraReports.UI.XRTableCell cellActualAddress;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell18;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell20;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell21;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell23;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell24;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell26;
private DevExpress.XtraReports.UI.XRTableCell cellTelephone;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow15;
private DevExpress.XtraReports.UI.XRTableCell cellReportedPeriod;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell30;
private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter;
private DevExpress.XtraReports.UI.XRTable tableCustomFooter;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow18;
private DevExpress.XtraReports.UI.XRTable CustomHeaderTable;
private DevExpress.XtraReports.UI.XRTableRow CustomHeaderFirstRow;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell40;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell41;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell42;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell43;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell47;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell46;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell44;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell48;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell49;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell52;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell45;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell51;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell50;
private DevExpress.XtraReports.UI.XRTableRow CustomHeaderSecondRow;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell53;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell54;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell55;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell56;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell57;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell58;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell59;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell60;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell61;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell62;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell63;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell64;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell66;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell67;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell68;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell69;
private DevExpress.XtraReports.UI.DetailReportBand DetailReport;
private DevExpress.XtraReports.UI.DetailBand CustomDetail;
private DevExpress.XtraReports.UI.ReportHeaderBand CustomReportHeader;
private DevExpress.XtraReports.UI.XRTable DetailTable;
private DevExpress.XtraReports.UI.XRTableRow DetailRow;
private DevExpress.XtraReports.UI.XRTableCell strDiseaseName;
private DevExpress.XtraReports.UI.XRTableCell cellICD10;
private DevExpress.XtraReports.UI.XRTableCell cellAge_0_1;
private DevExpress.XtraReports.UI.XRTableCell cellAge_1_4;
private DevExpress.XtraReports.UI.XRTableCell cellAge_5_14;
private DevExpress.XtraReports.UI.XRTableCell cellAge_15_19;
private DevExpress.XtraReports.UI.XRTableCell cellAge_20_29;
private DevExpress.XtraReports.UI.XRTableCell cellAge_30_59;
private DevExpress.XtraReports.UI.XRTableCell cellAge_60_more;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell94;
private DevExpress.XtraReports.UI.XRTableCell cellTotal;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell96;
private DevExpress.XtraReports.UI.XRTableCell cellLabTested;
private DevExpress.XtraReports.UI.XRTableCell cellLabConfirmed;
private DevExpress.XtraReports.UI.XRTableCell cellTotalConfirmed;
private EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthV6DataSet m_DataSet;
private EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthHeaderV6DataSet m_HeaderDataSet;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow23;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell70;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow21;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell27;
private DevExpress.XtraReports.UI.XRTableCell ChiefFooterCell;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthV6DataSetTableAdapters.MonthlyV6Adapter m_Adapter;
private EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthHeaderV6DataSetTableAdapters.MonthlyHeaderV6Adapter m_HeaderAdapter;
private DevExpress.XtraReports.UI.XRLabel cellLocation;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell14;
private DevExpress.XtraReports.UI.XRTableRow EnTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell38;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell75;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell81;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell82;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell85;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell86;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell87;
private DevExpress.XtraReports.UI.XRTableRow EnTableRow2;
private DevExpress.XtraReports.UI.XRTableRow GgTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private DevExpress.XtraReports.UI.XRTableRow GgTableRow2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell89;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell92;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell93;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell95;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell97;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell90;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell71;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell72;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell73;
private DevExpress.XtraReports.UI.XRTableCell MonthFooterCell;
private DevExpress.XtraReports.UI.XRTableCell YearFooterCell;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell32;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell34;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell35;
private DevExpress.XtraReports.UI.XRTableCell DayFooterCell;
private DevExpress.XtraReports.UI.FormattingRule formattingRule1;
private DevExpress.XtraReports.UI.XRPageBreak PageBreakAtLine36;
private DevExpress.XtraReports.UI.FormattingRule formattingRule2;
private DevExpress.XtraReports.UI.FormattingRule formattingRule3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell331;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell361;
private DevExpress.XtraReports.UI.XRLabel PrintDateTimeLabel;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell112;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell132;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell65;
private DevExpress.XtraReports.UI.GroupFooterBand GroupFooter;
private DevExpress.XtraReports.UI.XRTable SignatureTable;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell36;
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using Internal.Fakeables;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Targets;
#if SILVERLIGHT
using System.Windows;
#endif
#if !SILVERLIGHT && !NET2_0 && !MONO && !NET_CF
using System.IO.Abstractions;
#endif
/// <summary>
/// Creates and manages instances of <see cref="T:NLog.Logger" /> objects.
/// </summary>
public class LogFactory : IDisposable
{
#if !NET_CF && !SILVERLIGHT
private readonly MultiFileWatcher watcher;
private const int ReconfigAfterFileChangedTimeout = 1000;
#endif
private static IAppDomain currentAppDomain;
private readonly Dictionary<LoggerCacheKey, WeakReference> loggerCache = new Dictionary<LoggerCacheKey, WeakReference>();
private static TimeSpan defaultFlushTimeout = TimeSpan.FromSeconds(15);
#if !SILVERLIGHT && !NET2_0 && !MONO && !NET_CF
private IFileSystem fileSystem = new FileSystem();
#endif
#if !NET_CF && !SILVERLIGHT
private Timer reloadTimer;
#endif
private LoggingConfiguration config;
private LogLevel globalThreshold = LogLevel.MinLevel;
private bool configLoaded;
private int logsEnabled;
/// <summary>
/// Initializes a new instance of the <see cref="LogFactory" /> class.
/// </summary>
public LogFactory()
{
#if !NET_CF && !SILVERLIGHT
this.watcher = new MultiFileWatcher();
this.watcher.OnChange += this.ConfigFileChanged;
#endif
}
#if !SILVERLIGHT && !NET2_0 && !MONO && !NET_CF
/// <summary>
/// Initializes a new instance of the <see cref="LogFactory"/> class.
/// This constructor should only be used for testing purposes.
/// </summary>
/// <param name="fileSystem">The filesystem abstraction to inject.</param>
internal LogFactory(IFileSystem fileSystem)
: this()
{
this.fileSystem = fileSystem;
}
#endif
/// <summary>
/// Initializes a new instance of the <see cref="LogFactory" /> class.
/// </summary>
/// <param name="config">The config.</param>
public LogFactory(LoggingConfiguration config)
: this()
{
this.Configuration = config;
}
/// <summary>
/// Occurs when logging <see cref="Configuration" /> changes.
/// </summary>
public event EventHandler<LoggingConfigurationChangedEventArgs> ConfigurationChanged;
#if !NET_CF && !SILVERLIGHT
/// <summary>
/// Occurs when logging <see cref="Configuration" /> gets reloaded.
/// </summary>
public event EventHandler<LoggingConfigurationReloadedEventArgs> ConfigurationReloaded;
#endif
/// <summary>
/// Gets the current <see cref="IAppDomain"/>.
/// </summary>
public static IAppDomain CurrentAppDomain
{
get { return currentAppDomain ?? (currentAppDomain = AppDomainWrapper.CurrentDomain); }
set { currentAppDomain = value; }
}
/// <summary>
/// Gets or sets a value indicating whether exceptions should be thrown.
/// </summary>
/// <value>A value of <c>true</c> if exceptiosn should be thrown; otherwise, <c>false</c>.</value>
/// <remarks>By default exceptions
/// are not thrown under any circumstances.
/// </remarks>
public bool ThrowExceptions { get; set; }
/// <summary>
/// Gets or sets the current logging configuration.
/// </summary>
public LoggingConfiguration Configuration
{
get
{
lock (this)
{
if (this.configLoaded)
{
return this.config;
}
this.configLoaded = true;
#if !NET_CF && !SILVERLIGHT
if (this.config == null)
{
// try to load default configuration
this.config = XmlLoggingConfiguration.AppConfig;
}
#endif
if (this.config == null)
{
foreach (string configFile in GetCandidateFileNames())
{
#if !SILVERLIGHT && !NET2_0 && !MONO && !NET_CF
if (fileSystem.File.Exists(configFile))
{
InternalLogger.Debug("Attempting to load config from {0}", configFile);
this.config = new XmlLoggingConfiguration(configFile);
break;
}
#elif SILVERLIGHT
Uri configFileUri = new Uri(configFile, UriKind.Relative);
if (Application.GetResourceStream(configFileUri) != null)
{
InternalLogger.Debug("Attempting to load config from {0}", configFile);
this.config = new XmlLoggingConfiguration(configFile);
break;
}
#else
if (File.Exists(configFile))
{
InternalLogger.Debug("Attempting to load config from {0}", configFile);
this.config = new XmlLoggingConfiguration(configFile);
break;
}
#endif
}
}
#if !NET_CF && !SILVERLIGHT
if (this.config != null)
{
Dump(this.config);
this.watcher.Watch(this.config.FileNamesToWatch);
}
#endif
if (this.config != null)
{
this.config.InitializeAll();
}
return this.config;
}
}
set
{
#if !NET_CF && !SILVERLIGHT
try
{
this.watcher.StopWatching();
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Error("Cannot stop file watching: {0}", exception);
}
#endif
lock (this)
{
LoggingConfiguration oldConfig = this.config;
if (oldConfig != null)
{
InternalLogger.Info("Closing old configuration.");
#if !SILVERLIGHT
this.Flush();
#endif
oldConfig.Close();
}
this.config = value;
this.configLoaded = true;
if (this.config != null)
{
Dump(this.config);
this.config.InitializeAll();
this.ReconfigExistingLoggers(this.config);
#if !NET_CF && !SILVERLIGHT
try
{
this.watcher.Watch(this.config.FileNamesToWatch);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Warn("Cannot start file watching: {0}", exception);
}
#endif
}
var configurationChangedDelegate = this.ConfigurationChanged;
if (configurationChangedDelegate != null)
{
configurationChangedDelegate(this, new LoggingConfigurationChangedEventArgs(oldConfig, value));
}
}
}
}
/// <summary>
/// Gets or sets the global log threshold. Log events below this threshold are not logged.
/// </summary>
public LogLevel GlobalThreshold
{
get
{
return this.globalThreshold;
}
set
{
lock (this)
{
this.globalThreshold = value;
this.ReconfigExistingLoggers();
}
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Creates a logger that discards all log messages.
/// </summary>
/// <returns>Null logger instance.</returns>
public Logger CreateNullLogger()
{
TargetWithFilterChain[] targetsByLevel = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1];
Logger newLogger = new Logger();
newLogger.Initialize(string.Empty, new LoggerConfiguration(targetsByLevel), this);
return newLogger;
}
#if !NET_CF
/// <summary>
/// Gets the logger named after the currently-being-initialized class.
/// </summary>
/// <returns>The logger.</returns>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
public Logger GetCurrentClassLogger()
{
#if SILVERLIGHT
var frame = new StackFrame(1);
#else
var frame = new StackFrame(1, false);
#endif
return this.GetLogger(frame.GetMethod().DeclaringType.FullName);
}
/// <summary>
/// Gets the logger named after the currently-being-initialized class.
/// </summary>
/// <param name="loggerType">The type of the logger to create. The type must inherit from NLog.Logger.</param>
/// <returns>The logger.</returns>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
public Logger GetCurrentClassLogger(Type loggerType)
{
#if !SILVERLIGHT
var frame = new StackFrame(1, false);
#else
var frame = new StackFrame(1);
#endif
return this.GetLogger(frame.GetMethod().DeclaringType.FullName, loggerType);
}
#endif
/// <summary>
/// Gets the specified named logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument aren't guaranteed to return the same logger reference.</returns>
public Logger GetLogger(string name)
{
return this.GetLogger(new LoggerCacheKey(typeof(Logger), name));
}
/// <summary>
/// Gets the specified named logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <param name="loggerType">The type of the logger to create. The type must inherit from NLog.Logger.</param>
/// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the
/// same argument aren't guaranteed to return the same logger reference.</returns>
public Logger GetLogger(string name, Type loggerType)
{
return this.GetLogger(new LoggerCacheKey(loggerType, name));
}
/// <summary>
/// Loops through all loggers previously returned by GetLogger
/// and recalculates their target and filter list. Useful after modifying the configuration programmatically
/// to ensure that all loggers have been properly configured.
/// </summary>
public void ReconfigExistingLoggers()
{
this.ReconfigExistingLoggers(this.config);
}
#if !SILVERLIGHT
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
public void Flush()
{
this.Flush(defaultFlushTimeout);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public void Flush(TimeSpan timeout)
{
try
{
AsyncHelpers.RunSynchronously(cb => this.Flush(cb, timeout));
}
catch (Exception e)
{
if (ThrowExceptions)
{
throw;
}
InternalLogger.Error(e.ToString());
}
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public void Flush(int timeoutMilliseconds)
{
this.Flush(TimeSpan.FromMilliseconds(timeoutMilliseconds));
}
#endif
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
public void Flush(AsyncContinuation asyncContinuation)
{
this.Flush(asyncContinuation, TimeSpan.MaxValue);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public void Flush(AsyncContinuation asyncContinuation, int timeoutMilliseconds)
{
this.Flush(asyncContinuation, TimeSpan.FromMilliseconds(timeoutMilliseconds));
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public void Flush(AsyncContinuation asyncContinuation, TimeSpan timeout)
{
try
{
InternalLogger.Trace("LogFactory.Flush({0})", timeout);
var loggingConfiguration = this.Configuration;
if (loggingConfiguration != null)
{
InternalLogger.Trace("Flushing all targets...");
loggingConfiguration.FlushAllTargets(AsyncHelpers.WithTimeout(asyncContinuation, timeout));
}
else
{
asyncContinuation(null);
}
}
catch (Exception e)
{
if (ThrowExceptions)
{
throw;
}
InternalLogger.Error(e.ToString());
}
}
/// <summary>Decreases the log enable counter and if it reaches -1
/// the logs are disabled.</summary>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
/// <returns>An object that iplements IDisposable whose Dispose() method
/// reenables logging. To be used with C# <c>using ()</c> statement.</returns>
public IDisposable DisableLogging()
{
lock (this)
{
this.logsEnabled--;
if (this.logsEnabled == -1)
{
this.ReconfigExistingLoggers();
}
}
return new LogEnabler(this);
}
/// <summary>Increases the log enable counter and if it reaches 0 the logs are disabled.</summary>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
public void EnableLogging()
{
lock (this)
{
this.logsEnabled++;
if (this.logsEnabled == 0)
{
this.ReconfigExistingLoggers();
}
}
}
/// <summary>
/// Returns <see langword="true" /> if logging is currently enabled.
/// </summary>
/// <returns>A value of <see langword="true" /> if logging is currently enabled,
/// <see langword="false"/> otherwise.</returns>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
public bool IsLoggingEnabled()
{
return this.logsEnabled >= 0;
}
#if !NET_CF && !SILVERLIGHT
internal void ReloadConfigOnTimer(object state)
{
LoggingConfiguration configurationToReload = (LoggingConfiguration)state;
InternalLogger.Info("Reloading configuration...");
lock (this)
{
if (this.reloadTimer != null)
{
this.reloadTimer.Dispose();
this.reloadTimer = null;
}
this.watcher.StopWatching();
try
{
if (this.Configuration != configurationToReload)
{
throw new NLogConfigurationException("Config changed in between. Not reloading.");
}
LoggingConfiguration newConfig = configurationToReload.Reload();
if (newConfig != null)
{
this.Configuration = newConfig;
if (this.ConfigurationReloaded != null)
{
this.ConfigurationReloaded(true, null);
}
}
else
{
throw new NLogConfigurationException("Configuration.Reload() returned null. Not reloading.");
}
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
this.watcher.Watch(configurationToReload.FileNamesToWatch);
var configurationReloadedDelegate = this.ConfigurationReloaded;
if (configurationReloadedDelegate != null)
{
configurationReloadedDelegate(this, new LoggingConfigurationReloadedEventArgs(false, exception));
}
}
}
}
#endif
internal void ReconfigExistingLoggers(LoggingConfiguration configuration)
{
if (configuration != null)
{
configuration.EnsureInitialized();
}
foreach (var loggerWrapper in this.loggerCache.Values.ToList())
{
Logger logger = loggerWrapper.Target as Logger;
if (logger != null)
{
logger.SetConfiguration(this.GetConfigurationForLogger(logger.Name, configuration));
}
}
}
internal void GetTargetsByLevelForLogger(string name, IList<LoggingRule> rules, TargetWithFilterChain[] targetsByLevel, TargetWithFilterChain[] lastTargetsByLevel)
{
foreach (LoggingRule rule in rules)
{
if (!rule.NameMatches(name))
{
continue;
}
for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i)
{
if (i < this.GlobalThreshold.Ordinal || !rule.IsLoggingEnabledForLevel(LogLevel.FromOrdinal(i)))
{
continue;
}
foreach (Target target in rule.Targets)
{
var awf = new TargetWithFilterChain(target, rule.Filters);
if (lastTargetsByLevel[i] != null)
{
lastTargetsByLevel[i].NextInChain = awf;
}
else
{
targetsByLevel[i] = awf;
}
lastTargetsByLevel[i] = awf;
}
}
this.GetTargetsByLevelForLogger(name, rule.ChildRules, targetsByLevel, lastTargetsByLevel);
if (rule.Final)
{
break;
}
}
for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i)
{
TargetWithFilterChain tfc = targetsByLevel[i];
if (tfc != null)
{
tfc.PrecalculateStackTraceUsage();
}
}
}
internal LoggerConfiguration GetConfigurationForLogger(string name, LoggingConfiguration configuration)
{
TargetWithFilterChain[] targetsByLevel = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1];
TargetWithFilterChain[] lastTargetsByLevel = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1];
if (configuration != null && this.IsLoggingEnabled())
{
this.GetTargetsByLevelForLogger(name, configuration.LoggingRules, targetsByLevel, lastTargetsByLevel);
}
InternalLogger.Debug("Targets for {0} by level:", name);
for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat(CultureInfo.InvariantCulture, "{0} =>", LogLevel.FromOrdinal(i));
for (TargetWithFilterChain afc = targetsByLevel[i]; afc != null; afc = afc.NextInChain)
{
sb.AppendFormat(CultureInfo.InvariantCulture, " {0}", afc.Target.Name);
if (afc.FilterChain.Count > 0)
{
sb.AppendFormat(CultureInfo.InvariantCulture, " ({0} filters)", afc.FilterChain.Count);
}
}
InternalLogger.Debug(sb.ToString());
}
return new LoggerConfiguration(targetsByLevel);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing">True to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
#if !NET_CF && !SILVERLIGHT
this.watcher.Dispose();
if (this.reloadTimer != null)
{
this.reloadTimer.Dispose();
this.reloadTimer = null;
}
#endif
}
}
private static IEnumerable<string> GetCandidateFileNames()
{
#if NET_CF
yield return CompactFrameworkHelper.GetExeFileName() + ".nlog";
yield return Path.Combine(Path.GetDirectoryName(CompactFrameworkHelper.GetExeFileName()), "NLog.config");
yield return typeof(LogFactory).Assembly.GetName().CodeBase + ".nlog";
#elif SILVERLIGHT
yield return "NLog.config";
#else
// NLog.config from application directory
yield return Path.Combine(CurrentAppDomain.BaseDirectory, "NLog.config");
// current config file with .config renamed to .nlog
string cf = CurrentAppDomain.ConfigurationFile;
if (cf != null)
{
yield return Path.ChangeExtension(cf, ".nlog");
IEnumerable<string> privateBinPaths = CurrentAppDomain.PrivateBinPath;
if (privateBinPaths != null)
{
foreach (var path in privateBinPaths)
{
yield return Path.Combine(path, "NLog.config");
}
}
}
// get path to NLog.dll.nlog only if the assembly is not in the GAC
var nlogAssembly = typeof(LogFactory).Assembly;
if (!nlogAssembly.GlobalAssemblyCache)
{
if (!string.IsNullOrEmpty(nlogAssembly.Location))
{
yield return nlogAssembly.Location + ".nlog";
}
}
#endif
}
private static void Dump(LoggingConfiguration config)
{
if (!InternalLogger.IsDebugEnabled)
{
return;
}
config.Dump();
}
private Logger GetLogger(LoggerCacheKey cacheKey)
{
lock (this)
{
WeakReference l;
if (this.loggerCache.TryGetValue(cacheKey, out l))
{
Logger existingLogger = l.Target as Logger;
if (existingLogger != null)
{
// logger in the cache and still referenced
return existingLogger;
}
}
Logger newLogger;
if (cacheKey.ConcreteType != null && cacheKey.ConcreteType != typeof(Logger))
{
try
{
newLogger = (Logger)FactoryHelper.CreateInstance(cacheKey.ConcreteType);
}
catch(Exception exception)
{
if(exception.MustBeRethrown())
{
throw;
}
if(ThrowExceptions)
{
throw;
}
InternalLogger.Error("Cannot create instance of specified type. Proceeding with default type instance. Exception : {0}",exception);
//Creating default instance of logger if instance of specified type cannot be created.
cacheKey = new LoggerCacheKey(typeof(Logger),cacheKey.Name);
newLogger = new Logger();
}
}
else
{
newLogger = new Logger();
}
if (cacheKey.ConcreteType != null)
{
newLogger.Initialize(cacheKey.Name, this.GetConfigurationForLogger(cacheKey.Name, this.Configuration), this);
}
this.loggerCache[cacheKey] = new WeakReference(newLogger);
return newLogger;
}
}
#if !NET_CF && !SILVERLIGHT
private void ConfigFileChanged(object sender, EventArgs args)
{
InternalLogger.Info("Configuration file change detected! Reloading in {0}ms...", ReconfigAfterFileChangedTimeout);
// In the rare cases we may get multiple notifications here,
// but we need to reload config only once.
//
// The trick is to schedule the reload in one second after
// the last change notification comes in.
lock (this)
{
if (this.reloadTimer == null)
{
this.reloadTimer = new Timer(
this.ReloadConfigOnTimer,
this.Configuration,
ReconfigAfterFileChangedTimeout,
Timeout.Infinite);
}
else
{
this.reloadTimer.Change(ReconfigAfterFileChangedTimeout, Timeout.Infinite);
}
}
}
#endif
/// <summary>
/// Logger cache key.
/// </summary>
internal class LoggerCacheKey
{
internal LoggerCacheKey(Type loggerConcreteType, string name)
{
this.ConcreteType = loggerConcreteType;
this.Name = name;
}
internal Type ConcreteType { get; private set; }
internal string Name { get; private set; }
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
public override int GetHashCode()
{
return this.ConcreteType.GetHashCode() ^ this.Name.GetHashCode();
}
/// <summary>
/// Determines if two objects are equal in value.
/// </summary>
/// <param name="o">Other object to compare to.</param>
/// <returns>True if objects are equal, false otherwise.</returns>
public override bool Equals(object o)
{
var key = o as LoggerCacheKey;
if (ReferenceEquals(key, null))
{
return false;
}
return (this.ConcreteType == key.ConcreteType) && (key.Name == this.Name);
}
}
/// <summary>
/// Enables logging in <see cref="IDisposable.Dispose"/> implementation.
/// </summary>
private class LogEnabler : IDisposable
{
private LogFactory factory;
/// <summary>
/// Initializes a new instance of the <see cref="LogEnabler" /> class.
/// </summary>
/// <param name="factory">The factory.</param>
public LogEnabler(LogFactory factory)
{
this.factory = factory;
}
/// <summary>
/// Enables logging.
/// </summary>
void IDisposable.Dispose()
{
this.factory.EnableLogging();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Xml;
namespace Epi.Windows.Docking
{
internal partial class DockForm : Form
{
#region Constructor
public DockForm()
{
InitializeComponent();
// Create and initialize the root container.
rootContainer = new DockContainer();
rootContainer.Dock = DockStyle.Fill;
this.Controls.Add(rootContainer);
RegisterToMdiContainer();
}
public DockForm(Panel dragObject)
{
InitializeComponent();
this.Opacity = 0;
if (dragObject is DockContainer)
{
DockContainer c = dragObject as DockContainer;
if (c.panList.Count == 1)
this.ClientSize = (c.panList[0] as DockPanel).Form.ClientSize;
else
this.ClientSize = dragObject.Size;
if (c.removeable)
rootContainer = c;
else
{
rootContainer = new DockContainer();
rootContainer.Controls.AddRange((DockPanel[])c.panList.ToArray(typeof(DockPanel)));
rootContainer.Controls.AddRange((DockContainer[])c.conList.ToArray(typeof(DockContainer)));
ArrayList list = new ArrayList();
rootContainer.GetPanels(list);
if (list.Count > 0)
rootContainer.DockType = (list[0] as DockPanel).Form.DockType;
}
}
else if (dragObject is DockPanel)
{
DockPanel p = dragObject as DockPanel;
this.ClientSize = p.Form.ClientSize;
rootContainer = new DockContainer();
p.Form.CopyToDockForm(this);
}
if (rootContainer.panList.Count > 0)
{
(rootContainer.panList[0] as DockPanel).Form.CopyPropToDockForm(this);
rootContainer.SetFormSizeBounds(this);
rootContainer.SelectTab(0);
}
rootContainer.Dock = DockStyle.Fill;
this.Controls.Add(rootContainer);
RegisterToMdiContainer();
}
private void RegisterToMdiContainer()
{
if (Application.OpenForms.Count > 0)
Application.OpenForms[0].AddOwnedForm(this);
DockManager.RegisterForm(this);
}
#endregion
#region Variables
private OverlayForm dragWindow = null;
private DockContainer dragTarget = null;
private DockContainer rootContainer = null;
private bool moving = false;
private bool allowDock = true;
private Point ptStart;
private Point ptRef;
#endregion
#region Properties
public DockContainer DragTarget
{
get { return dragTarget; }
}
public bool Moving
{
get { return moving; }
}
public bool AllowDock
{
get { return allowDock; }
set { allowDock = value; }
}
public DockContainer RootContainer
{
get { return rootContainer; }
set
{
if (rootContainer != null)
{
this.Controls.Remove(rootContainer);
rootContainer.Dispose();
}
rootContainer = value;
this.Controls.Add(rootContainer);
}
}
#endregion
#region Moving and Docking
#region WndProc for mouse events
/// <summary>
/// Since there are no non-client area notifications in .NET, this message loop hook is needed.
/// Captures a window move event and starts own movement procedure with an attached drag window.
/// </summary>
/// <param name="m">The Windows Message to process.</param>
protected override void WndProc(ref Message m)
{
if ((m.Msg == (int)Win32.Msgs.WM_NCLBUTTONDOWN) & (m.WParam == (IntPtr)Win32.HitTest.HTCAPTION))
{
StartMoving(new Point(MousePosition.X, MousePosition.Y));
return;
}
else if (moving)
{
if (m.Msg == (int)Win32.Msgs.WM_MOUSEMOVE)
{
Application.DoEvents();
if (this.IsDisposed)
return;
if (MouseButtons == MouseButtons.None)
{
EndMoving();
Show();
}
else
{
if (DockManager.FastMoveDraw & this.Visible)
Hide();
this.Location = new Point(ptRef.X + MousePosition.X - ptStart.X, ptRef.Y + MousePosition.Y - ptStart.Y);
MoveWindow();
this.Capture = true;
}
return;
}
else if ((m.Msg == (int)Win32.Msgs.WM_LBUTTONUP) | ((m.Msg == (int)Win32.Msgs.WM_NCMOUSEMOVE) & (MouseButtons == MouseButtons.None)))
{
EndMoving();
if (SendDockEvent(true) != null)
{
rootContainer = null;
this.Close();
return;
}
Show();
}
else if (m.Msg == (int)Win32.Msgs.WM_MOUSELEAVE)
{
EndMoving();
Show();
}
}
base.WndProc(ref m);
}
public void StartMoving(Point start)
{
moving = true;
ptStart = start;
ptRef = new Point(this.Location.X, this.Location.Y);
BringToFront();
this.Capture = true;
this.Opacity = 1;
}
private void EndMoving()
{
CloseDragWindow();
BringToFront();
this.Capture = false;
moving = false;
DockManager.HideDockGuide();
}
#endregion
#region DragWindow
/// <summary>
/// Closes the attached drag window.
/// </summary>
private void CloseDragWindow()
{
if (dragWindow != null)
{
dragWindow.Close();
dragWindow.Dispose();
dragWindow = null;
}
}
#endregion
#region MoveWindow function
/// <summary>
/// Invokes the drag event and adjusts the size and location if a valid docking position was received.
/// This method is only used by explicit drag windows (see flag).
/// </summary>
internal void MoveWindow()
{
dragTarget = SendDockEvent(false);
if (dragTarget != null)
{
if (dragWindow == null)
{
dragWindow = new OverlayForm();
dragWindow.Size = dragTarget.Size;
dragWindow.Show();
this.BringToFront();
}
else
dragWindow.Size = dragTarget.Size;
if (dragTarget.Parent != null)
dragWindow.Location = dragTarget.RectangleToScreen(dragTarget.ClientRectangle).Location;
else
dragWindow.Location = dragTarget.Location;
}
else if (DockManager.FastMoveDraw)
{
if (dragWindow == null)
{
dragWindow = new OverlayForm();
dragWindow.Size = this.Size;
dragWindow.Show();
}
else
dragWindow.Size = this.Size;
dragWindow.Location = this.Location;
}
else
CloseDragWindow();
}
#endregion
#region Dock Event
/// <summary>
/// Invokes a drag event that accepts a valid position for docking.
/// </summary>
/// <param name="confirm">Set this flag to confirm the docking position, if available.</param>
/// <returns>Returns the target <see cref="DockContainer"/>.</returns>
internal DockContainer SendDockEvent(bool confirm)
{
DockEventArgs e = new DockEventArgs(new Point(MousePosition.X, MousePosition.Y), rootContainer.DockType, confirm);
DockManager.InvokeDragEvent(this, e);
if (e.Release)
DockManager.HideDockGuide();
return e.Target;
}
#endregion
#endregion
#region Overrides
protected override void OnKeyDown(KeyEventArgs e)
{
this.rootContainer.InvokeKeyDown(this, e);
}
protected override void OnKeyUp(KeyEventArgs e)
{
this.rootContainer.InvokeKeyUp(this, e);
}
protected override void OnClosing(CancelEventArgs e)
{
if (rootContainer != null)
{
rootContainer.ActivePanel = null;
rootContainer.CloseClick(this, new EventArgs());
}
base.OnClosing(e);
}
protected override void OnActivated(EventArgs e)
{
base.OnActivated(e);
DockManager.FormActivated(this);
}
#endregion
#region XML r/w
/// <summary>
/// Writes the form data to the window save list.
/// </summary>
/// <param name="writer">The <see cref="XmlTextWriter"/> object that writes to the target stream.</param>
internal void WriteXml(XmlTextWriter writer)
{
writer.WriteStartElement("form");
writer.WriteAttributeString("width", this.Width.ToString());
writer.WriteAttributeString("height", this.Height.ToString());
writer.WriteAttributeString("x", this.Location.X.ToString());
writer.WriteAttributeString("y", this.Location.Y.ToString());
rootContainer.WriteXml(writer);
writer.WriteEndElement();
}
/// <summary>
/// Reads the form data from the window save list.
/// </summary>
/// <param name="reader">The <see cref="XmlReader"/> object that reads from the source stream.</param>
internal void ReadXml(XmlReader reader)
{
try
{
string s;
int x = 0, y = 0;
s = reader.GetAttribute("width");
if (s != null)
this.Width = int.Parse(s);
s = reader.GetAttribute("height");
if (s != null)
this.Height = int.Parse(s);
s = reader.GetAttribute("x");
if (s != null)
x = int.Parse(s);
s = reader.GetAttribute("y");
if (s != null)
y = int.Parse(s);
this.Location = new Point(x, y);
reader.Read();
while (!reader.EOF)
{
if (reader.IsStartElement() & (reader.Name == "container"))
{
Console.WriteLine("container");
rootContainer.ReadXml(reader.ReadSubtree());
break;
}
else
reader.Read();
}
}
catch (Exception ex)
{
Console.WriteLine("DockContainer.ReadXml: " + ex.Message);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Xml;
using BulletSharp.Math;
namespace BulletSharp
{
public class BulletXmlWorldImporter : WorldImporter
{
private int _fileVersion = -1;
private bool _fileOK = false;
private List<byte[]> _collisionShapeData = new List<byte[]>();
private List<byte[]> _constraintData = new List<byte[]>();
private List<byte[]> _rigidBodyData = new List<byte[]>();
private Dictionary<long, byte[]> _pointerLookup = new Dictionary<long, byte[]>();
public BulletXmlWorldImporter(DynamicsWorld world)
: base(world)
{
}
private void AutoSerializeRootLevelChildren(XmlElement parent)
{
foreach (XmlNode node in parent)
{
if (node.NodeType != XmlNodeType.Element)
{
continue;
}
XmlElement element = node as XmlElement;
switch (element.Name)
{
case "btCompoundShapeChildData":
DeSerializeCompoundShapeChildData(element);
continue;
case "btCompoundShapeData":
DeSerializeCompoundShapeData(element);
continue;
case "btConvexHullShapeData":
DeSerializeConvexHullShapeData(element);
continue;
case "btConvexInternalShapeData":
DeSerializeConvexInternalShapeData(element);
continue;
case "btDynamicsWorldFloatData":
DeSerializeDynamicsWorldData(element);
continue;
case "btGeneric6DofConstraintData":
DeSerializeGeneric6DofConstraintData(element);
continue;
case "btRigidBodyFloatData":
DeSerializeRigidBodyFloatData(element);
continue;
case "btStaticPlaneShapeData":
DeSerializeStaticPlaneShapeData(element);
continue;
case "btVector3FloatData":
DeSerializeVector3FloatData(element);
continue;
default:
throw new NotImplementedException();
}
}
foreach (byte[] shapeData in _collisionShapeData)
{
CollisionShape shape = ConvertCollisionShape(shapeData, _pointerLookup);
if (shape != null)
{
foreach (KeyValuePair<long, byte[]> lib in _pointerLookup)
{
if (lib.Value == shapeData)
{
_shapeMap.Add(lib.Key, shape);
break;
}
}
using (MemoryStream stream = new MemoryStream(shapeData, false))
{
using (BulletReader reader = new BulletReader(stream))
{
long namePtr = reader.ReadPtr(CollisionShapeFloatData.Offset("Name"));
if (namePtr != 0)
{
byte[] nameData = _pointerLookup[namePtr];
int length = Array.IndexOf(nameData, (byte)0);
string name = System.Text.Encoding.ASCII.GetString(nameData, 0, length);
_objectNameMap.Add(shape, name);
_nameShapeMap.Add(name, shape);
}
}
}
}
}
foreach (byte[] rbData in _rigidBodyData)
{
ConvertRigidBodyFloat(rbData, _pointerLookup);
}
foreach (byte[] constraintData in _constraintData)
{
//throw new NotImplementedException();
//ConvertConstraint(constraintData);
}
}
private void DeSerializeCollisionShapeData(XmlElement parent, BulletWriter writer)
{
SetIntValue(writer, parent["m_shapeType"], CollisionShapeFloatData.Offset("ShapeType"));
writer.Write(0, CollisionShapeFloatData.Offset("Name"));
}
private void DeSerializeCompoundShapeChildData(XmlElement element)
{
int ptr = int.Parse(element.GetAttribute("pointer"));
XmlNodeList transforms = element.SelectNodes("m_transform");
XmlNodeList childShapes = element.SelectNodes("m_childShape");
XmlNodeList childShapeTypes = element.SelectNodes("m_childShapeType");
XmlNodeList childMargins = element.SelectNodes("m_childMargin");
int numChildren = transforms.Count;
int dataSize = Marshal.SizeOf(typeof(CompoundShapeChildFloatData));
byte[] compoundChild = new byte[dataSize * numChildren];
using (MemoryStream stream = new MemoryStream(compoundChild))
{
using (BulletWriter writer = new BulletWriter(stream))
{
int offset = 0;
for (int i = 0; i < numChildren; i++)
{
SetTransformValue(writer, transforms[i], offset + CompoundShapeChildFloatData.Offset("Transform"));
SetPointerValue(writer, childShapes[i], offset + CompoundShapeChildFloatData.Offset("ChildShape"));
SetIntValue(writer, childShapeTypes[i], offset + CompoundShapeChildFloatData.Offset("ChildShapeType"));
SetFloatValue(writer, childMargins[i], offset + CompoundShapeChildFloatData.Offset("ChildMargin"));
offset += dataSize;
}
}
}
_pointerLookup.Add(ptr, compoundChild);
}
private void DeSerializeCompoundShapeData(XmlElement element)
{
int ptr = int.Parse(element.GetAttribute("pointer"));
byte[] convexShape = new byte[Marshal.SizeOf(typeof(CompoundShapeFloatData))];
using (MemoryStream stream = new MemoryStream(convexShape))
{
using (BulletWriter writer = new BulletWriter(stream))
{
XmlNode node = element["m_collisionShapeData"];
if (node == null)
{
return;
}
DeSerializeCollisionShapeData(node as XmlElement, writer);
SetIntValue(writer, element["m_numChildShapes"], CompoundShapeFloatData.Offset("NumChildShapes"));
SetPointerValue(writer, element["m_childShapePtr"], CompoundShapeFloatData.Offset("ChildShapePtr"));
SetFloatValue(writer, element["m_collisionMargin"], CompoundShapeFloatData.Offset("CollisionMargin"));
}
}
_collisionShapeData.Add(convexShape);
_pointerLookup.Add(ptr, convexShape);
}
private void DeSerializeConvexHullShapeData(XmlElement element)
{
int ptr = int.Parse(element.GetAttribute("pointer"));
byte[] convexHullData = new byte[Marshal.SizeOf(typeof(ConvexHullShapeFloatData))];
using (MemoryStream stream = new MemoryStream(convexHullData))
{
using (BulletWriter writer = new BulletWriter(stream))
{
XmlNode node = element["m_convexInternalShapeData"];
if (node == null)
{
return;
}
DeSerializeConvexInternalShapeData(node as XmlElement, writer);
SetPointerValue(writer, element["m_unscaledPointsFloatPtr"], ConvexHullShapeFloatData.Offset("UnscaledPointsFloatPtr"));
SetPointerValue(writer, element["m_unscaledPointsFloatPtr"], ConvexHullShapeFloatData.Offset("UnscaledPointsFloatPtr"));
SetIntValue(writer, element["m_numUnscaledPoints"], ConvexHullShapeFloatData.Offset("NumUnscaledPoints"));
}
}
_collisionShapeData.Add(convexHullData);
_pointerLookup.Add(ptr, convexHullData);
}
private void DeSerializeConvexInternalShapeData(XmlElement element)
{
int ptr = int.Parse(element.GetAttribute("pointer"));
byte[] convexShapeData = new byte[Marshal.SizeOf(typeof(ConvexInternalShapeFloatData))];
using (MemoryStream stream = new MemoryStream(convexShapeData))
{
using (BulletWriter writer = new BulletWriter(stream))
{
DeSerializeConvexInternalShapeData(element, writer);
}
}
_collisionShapeData.Add(convexShapeData);
_pointerLookup.Add(ptr, convexShapeData);
}
private void DeSerializeConvexInternalShapeData(XmlElement element, BulletWriter writer)
{
XmlNode node = element["m_collisionShapeData"];
if (node == null)
{
return;
}
DeSerializeCollisionShapeData(node as XmlElement, writer);
SetFloatValue(writer, element["m_collisionMargin"], ConvexInternalShapeFloatData.Offset("CollisionMargin"));
SetVector4Value(writer, element["m_localScaling"], ConvexInternalShapeFloatData.Offset("LocalScaling"));
SetVector4Value(writer, element["m_implicitShapeDimensions"], ConvexInternalShapeFloatData.Offset("ImplicitShapeDimensions"));
}
private void DeSerializeDynamicsWorldData(XmlElement element)
{
}
private void DeSerializeGeneric6DofConstraintData(XmlElement element)
{
int ptr = int.Parse(element.GetAttribute("pointer"));
byte[] dof6Data = new byte[Marshal.SizeOf(typeof(Generic6DofConstraintFloatData))];
using (MemoryStream stream = new MemoryStream(dof6Data))
{
using (BulletWriter writer = new BulletWriter(stream))
{
XmlNode node = element["m_typeConstraintData"];
if (node == null)
{
return;
}
SetPointerValue(writer, node["m_rbA"], TypedConstraintFloatData.Offset("RigidBodyA"));
SetPointerValue(writer, node["m_rbB"], TypedConstraintFloatData.Offset("RigidBodyB"));
writer.Write(0, TypedConstraintFloatData.Offset("Name"));
SetIntValue(writer, node["m_objectType"], TypedConstraintFloatData.Offset("ObjectType"));
SetIntValue(writer, node["m_userConstraintType"], TypedConstraintFloatData.Offset("UserConstraintType"));
SetIntValue(writer, node["m_userConstraintId"], TypedConstraintFloatData.Offset("UserConstraintId"));
SetIntValue(writer, node["m_needsFeedback"], TypedConstraintFloatData.Offset("NeedsFeedback"));
SetFloatValue(writer, node["m_appliedImpulse"], TypedConstraintFloatData.Offset("AppliedImpulse"));
SetFloatValue(writer, node["m_dbgDrawSize"], TypedConstraintFloatData.Offset("DebugDrawSize"));
SetIntValue(writer, node["m_disableCollisionsBetweenLinkedBodies"], TypedConstraintFloatData.Offset("DisableCollisionsBetweenLinkedBodies"));
SetIntValue(writer, node["m_overrideNumSolverIterations"], TypedConstraintFloatData.Offset("OverrideNumSolverIterations"));
SetFloatValue(writer, node["m_breakingImpulseThreshold"], TypedConstraintFloatData.Offset("BreakingImpulseThreshold"));
SetIntValue(writer, node["m_isEnabled"], TypedConstraintFloatData.Offset("IsEnabled"));
SetTransformValue(writer, element["m_rbAFrame"], Generic6DofConstraintFloatData.Offset("RigidBodyAFrame"));
SetTransformValue(writer, element["m_rbBFrame"], Generic6DofConstraintFloatData.Offset("RigidBodyBFrame"));
SetVector4Value(writer, element["m_linearUpperLimit"], Generic6DofConstraintFloatData.Offset("LinearUpperLimit"));
SetVector4Value(writer, element["m_linearLowerLimit"], Generic6DofConstraintFloatData.Offset("LinearLowerLimit"));
SetVector4Value(writer, element["m_angularUpperLimit"], Generic6DofConstraintFloatData.Offset("AngularUpperLimit"));
SetVector4Value(writer, element["m_angularLowerLimit"], Generic6DofConstraintFloatData.Offset("AngularLowerLimit"));
SetIntValue(writer, element["m_useLinearReferenceFrameA"], Generic6DofConstraintFloatData.Offset("UseLinearReferenceFrameA"));
SetIntValue(writer, element["m_useOffsetForConstraintFrame"], Generic6DofConstraintFloatData.Offset("UseOffsetForConstraintFrame"));
}
}
_constraintData.Add(dof6Data);
}
private void DeSerializeRigidBodyFloatData(XmlElement element)
{
int ptr;
if (!int.TryParse(element.GetAttribute("pointer"), out ptr))
{
_fileOK = false;
return;
}
byte[] rbData = new byte[Marshal.SizeOf(typeof(RigidBodyFloatData))];
using (MemoryStream stream = new MemoryStream(rbData))
{
using (BulletWriter writer = new BulletWriter(stream))
{
XmlNode node = element["m_collisionObjectData"];
if (node == null)
{
return;
}
SetPointerValue(writer, node["m_collisionShape"], CollisionObjectFloatData.Offset("CollisionShape"));
SetTransformValue(writer, node["m_worldTransform"], CollisionObjectFloatData.Offset("WorldTransform"));
SetTransformValue(writer, node["m_interpolationWorldTransform"], CollisionObjectFloatData.Offset("InterpolationWorldTransform"));
SetVector4Value(writer, node["m_interpolationLinearVelocity"], CollisionObjectFloatData.Offset("InterpolationLinearVelocity"));
SetVector4Value(writer, node["m_interpolationAngularVelocity"], CollisionObjectFloatData.Offset("InterpolationAngularVelocity"));
SetVector4Value(writer, node["m_anisotropicFriction"], CollisionObjectFloatData.Offset("AnisotropicFriction"));
SetFloatValue(writer, node["m_contactProcessingThreshold"], CollisionObjectFloatData.Offset("ContactProcessingThreshold"));
SetFloatValue(writer, node["m_deactivationTime"], CollisionObjectFloatData.Offset("DeactivationTime"));
SetFloatValue(writer, node["m_friction"], CollisionObjectFloatData.Offset("Friction"));
SetFloatValue(writer, node["m_restitution"], CollisionObjectFloatData.Offset("Restitution"));
SetFloatValue(writer, node["m_hitFraction"], CollisionObjectFloatData.Offset("HitFraction"));
SetFloatValue(writer, node["m_ccdSweptSphereRadius"], CollisionObjectFloatData.Offset("CcdSweptSphereRadius"));
SetFloatValue(writer, node["m_ccdMotionThreshold"], CollisionObjectFloatData.Offset("CcdMotionThreshold"));
SetIntValue(writer, node["m_hasAnisotropicFriction"], CollisionObjectFloatData.Offset("HasAnisotropicFriction"));
SetIntValue(writer, node["m_collisionFlags"], CollisionObjectFloatData.Offset("CollisionFlags"));
SetIntValue(writer, node["m_islandTag1"], CollisionObjectFloatData.Offset("IslandTag1"));
SetIntValue(writer, node["m_companionId"], CollisionObjectFloatData.Offset("CompanionId"));
SetIntValue(writer, node["m_activationState1"], CollisionObjectFloatData.Offset("ActivationState1"));
SetIntValue(writer, node["m_internalType"], CollisionObjectFloatData.Offset("InternalType"));
SetIntValue(writer, node["m_checkCollideWith"], CollisionObjectFloatData.Offset("CheckCollideWith"));
SetMatrix3x3Value(writer, element["m_invInertiaTensorWorld"], RigidBodyFloatData.Offset("InvInertiaTensorWorld"));
SetVector4Value(writer, element["m_linearVelocity"], RigidBodyFloatData.Offset("LinearVelocity"));
SetVector4Value(writer, element["m_angularVelocity"], RigidBodyFloatData.Offset("AngularVelocity"));
SetVector4Value(writer, element["m_angularFactor"], RigidBodyFloatData.Offset("AngularFactor"));
SetVector4Value(writer, element["m_linearFactor"], RigidBodyFloatData.Offset("LinearFactor"));
SetVector4Value(writer, element["m_gravity"], RigidBodyFloatData.Offset("Gravity"));
SetVector4Value(writer, element["m_gravity_acceleration"], RigidBodyFloatData.Offset("GravityAcceleration"));
SetVector4Value(writer, element["m_invInertiaLocal"], RigidBodyFloatData.Offset("InvInertiaLocal"));
SetVector4Value(writer, element["m_totalTorque"], RigidBodyFloatData.Offset("TotalTorque"));
SetVector4Value(writer, element["m_totalForce"], RigidBodyFloatData.Offset("TotalForce"));
SetFloatValue(writer, element["m_inverseMass"], RigidBodyFloatData.Offset("InverseMass"));
SetFloatValue(writer, element["m_linearDamping"], RigidBodyFloatData.Offset("LinearDamping"));
SetFloatValue(writer, element["m_angularDamping"], RigidBodyFloatData.Offset("AngularDamping"));
SetFloatValue(writer, element["m_additionalDampingFactor"], RigidBodyFloatData.Offset("AdditionalDampingFactor"));
SetFloatValue(writer, element["m_additionalLinearDampingThresholdSqr"], RigidBodyFloatData.Offset("AdditionalLinearDampingThresholdSqr"));
SetFloatValue(writer, element["m_additionalAngularDampingThresholdSqr"], RigidBodyFloatData.Offset("AdditionalAngularDampingThresholdSqr"));
SetFloatValue(writer, element["m_additionalAngularDampingFactor"], RigidBodyFloatData.Offset("AdditionalAngularDampingFactor"));
SetFloatValue(writer, element["m_angularSleepingThreshold"], RigidBodyFloatData.Offset("AngularSleepingThreshold"));
SetFloatValue(writer, element["m_linearSleepingThreshold"], RigidBodyFloatData.Offset("LinearSleepingThreshold"));
SetIntValue(writer, element["m_additionalDamping"], RigidBodyFloatData.Offset("AdditionalDamping"));
}
}
_rigidBodyData.Add(rbData);
}
private void DeSerializeStaticPlaneShapeData(XmlElement element)
{
int ptr = int.Parse(element.GetAttribute("pointer"));
byte[] convexShape = new byte[Marshal.SizeOf(typeof(StaticPlaneShapeFloatData))];
using (MemoryStream stream = new MemoryStream(convexShape))
{
using (BulletWriter writer = new BulletWriter(stream))
{
XmlNode node = element["m_collisionShapeData"];
if (node == null)
{
return;
}
DeSerializeCollisionShapeData(node as XmlElement, writer);
SetVector4Value(writer, element["m_localScaling"], StaticPlaneShapeFloatData.Offset("LocalScaling"));
SetVector4Value(writer, element["m_planeNormal"], StaticPlaneShapeFloatData.Offset("PlaneNormal"));
SetFloatValue(writer, element["m_planeConstant"], StaticPlaneShapeFloatData.Offset("PlaneConstant"));
}
}
_collisionShapeData.Add(convexShape);
_pointerLookup.Add(ptr, convexShape);
}
private void DeSerializeVector3FloatData(XmlElement element)
{
int ptr = int.Parse(element.GetAttribute("pointer"));
XmlNodeList vectors = element.SelectNodes("m_floats");
int numVectors = vectors.Count;
int vectorSize = Marshal.SizeOf(typeof(Vector3FloatData));
byte[] v = new byte[numVectors * vectorSize];
using (MemoryStream stream = new MemoryStream(v))
{
using (BulletWriter writer = new BulletWriter(stream))
{
int offset = 0;
for (int i = 0; i < numVectors; i++)
{
SetVector4Value(writer, vectors[i], offset);
offset += vectorSize;
}
}
}
_pointerLookup.Add(ptr, v);
}
public bool LoadFile(string fileName)
{
XmlDocument doc = new XmlDocument();
doc.Load(fileName);
XmlElement bulletPhysics = doc.DocumentElement;
if (!bulletPhysics.Name.Equals("bullet_physics"))
{
Console.WriteLine("ERROR: no bullet_physics element");
return false;
}
if (!int.TryParse(bulletPhysics.GetAttribute("version"), out _fileVersion))
{
return false;
}
if (_fileVersion == 281)
{
_fileOK = true;
AutoSerializeRootLevelChildren(bulletPhysics);
return _fileOK;
}
return false;
}
private void SetFloatValue(BulletWriter writer, XmlNode valueNode, int offset)
{
writer.Write(float.Parse(valueNode.InnerText, CultureInfo.InvariantCulture), offset);
}
private void SetIntValue(BulletWriter writer, XmlNode valueNode, int offset)
{
writer.Write(int.Parse(valueNode.InnerText), offset);
}
private void SetPointerValue(BulletWriter writer, XmlNode valueNode, int offset)
{
writer.Write(new IntPtr(long.Parse(valueNode.InnerText)), offset);
}
private void SetMatrix3x3Value(BulletWriter writer, XmlElement valueNode, int offset)
{
XmlNode floats = valueNode["m_el"]["m_floats"];
SetVector4Value(writer, floats, offset);
floats = floats.NextSibling;
SetVector4Value(writer, floats, offset + 16);
floats = floats.NextSibling;
SetVector4Value(writer, floats, offset + 32);
}
private void SetTransformValue(BulletWriter writer, XmlNode valueNode, int offset)
{
SetMatrix3x3Value(writer, valueNode["m_basis"], offset);
SetVector4Value(writer, valueNode["m_origin"], offset + TransformFloatData.OriginOffset);
}
private void SetVector4Value(BulletWriter writer, XmlNode valueNode, int offset)
{
int i = 0;
foreach (string value in valueNode.InnerText.Split(' '))
{
if (!string.IsNullOrEmpty(value))
{
writer.Write(float.Parse(value, CultureInfo.InvariantCulture), offset + i * sizeof(float));
i++;
if (i == 4)
{
break;
}
}
}
}
}
}
| |
/*
* 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.
*/
/*
* Created on May 19, 2005
*
*/
namespace NPOI.SS.Formula.Functions
{
using System;
/**
* @author Amol S. Deshmukh < amolweb at ya hoo dot com >
* This class Is an extension to the standard math library
* provided by java.lang.Math class. It follows the Math class
* in that it has a private constructor and all static methods.
*/
public class MathX
{
private MathX() { }
/**
* Returns a value rounded to p digits after decimal.
* If p Is negative, then the number Is rounded to
* places to the left of the decimal point. eg.
* 10.23 rounded to -1 will give: 10. If p Is zero,
* the returned value Is rounded to the nearest integral
* value.
* If n Is negative, the resulting value Is obtained
* as the round value of absolute value of n multiplied
* by the sign value of n (@see MathX.sign(double d)).
* Thus, -0.6666666 rounded to p=0 will give -1 not 0.
* If n Is NaN, returned value Is NaN.
* @param n
* @param p
*/
public static double Round(double n, int p)
{
double retval;
if (double.IsNaN(n) || double.IsInfinity(n))
{
retval = double.NaN;
}
else if (double.MaxValue == n)
return double.MaxValue;
else if (double.MinValue == n)
return 0;
else
{
if (p >= 0)
{
retval = (double)Math.Round((decimal)n, p, MidpointRounding.AwayFromZero);
}
else
{
int temp = (int)Math.Pow(10, Math.Abs(p));
retval = (double)(Math.Round((decimal)(n) / temp, MidpointRounding.AwayFromZero) * temp);
}
}
return retval;
}
/**
* Returns a value rounded-up to p digits after decimal.
* If p Is negative, then the number Is rounded to
* places to the left of the decimal point. eg.
* 10.23 rounded to -1 will give: 20. If p Is zero,
* the returned value Is rounded to the nearest integral
* value.
* If n Is negative, the resulting value Is obtained
* as the round-up value of absolute value of n multiplied
* by the sign value of n (@see MathX.sign(double d)).
* Thus, -0.2 rounded-up to p=0 will give -1 not 0.
* If n Is NaN, returned value Is NaN.
* @param n
* @param p
*/
public static double RoundUp(double n, int p)
{
double retval;
if (double.IsNaN(n) || double.IsInfinity(n))
{
retval = double.NaN;
}
else if (double.MaxValue == n)
return double.MaxValue;
else if (double.MinValue == n)
{
double digit = 1;
while (p > 0)
{
digit = digit / 10;
p--;
}
return digit;
}
else
{
if (p != 0)
{
double temp = Math.Pow(10, p);
double nat = (double)((decimal)Math.Abs(n * temp));
retval = Sign(n) *
((nat == (long)nat)
? nat / temp
: Math.Round(nat + 0.5) / temp);
}
else
{
double na = Math.Abs(n);
retval = Sign(n) *
((na == (long)na)
? na
: (long)na + 1);
}
}
return retval;
}
/**
* Returns a value rounded to p digits after decimal.
* If p Is negative, then the number Is rounded to
* places to the left of the decimal point. eg.
* 10.23 rounded to -1 will give: 10. If p Is zero,
* the returned value Is rounded to the nearest integral
* value.
* If n Is negative, the resulting value Is obtained
* as the round-up value of absolute value of n multiplied
* by the sign value of n (@see MathX.sign(double d)).
* Thus, -0.8 rounded-down to p=0 will give 0 not -1.
* If n Is NaN, returned value Is NaN.
* @param n
* @param p
*/
public static double RoundDown(double n, int p)
{
double retval;
if (double.IsNaN(n) || double.IsInfinity(n))
{
retval = double.NaN;
}
else if (double.MaxValue == n)
return double.MaxValue;
else if (double.MinValue == n)
return 0;
else
{
if (p != 0)
{
double temp = Math.Pow(10, p);
retval = Sign(n) * Math.Round((Math.Abs(n) * temp) - 0.5, MidpointRounding.AwayFromZero) / temp;
}
else
{
retval = (long)n;
}
}
return retval;
}
/*
* If d < 0, returns short -1
* <br/>
* If d > 0, returns short 1
* <br/>
* If d == 0, returns short 0
* If d Is NaN, then 1 will be returned. It Is the responsibility
* of caller to Check for d IsNaN if some other value Is desired.
* @param d
*/
public static short Sign(double d)
{
return (short)((d == 0)
? 0
: (d < 0)
? -1
: 1);
}
/**
* average of all values
* @param values
*/
public static double Average(double[] values)
{
double ave = 0;
double sum = 0;
for (int i = 0, iSize = values.Length; i < iSize; i++)
{
sum += values[i];
}
ave = sum / values.Length;
return ave;
}
/**
* sum of all values
* @param values
*/
public static double Sum(double[] values)
{
double sum = 0;
for (int i = 0, iSize = values.Length; i < iSize; i++)
{
sum += values[i];
}
return sum;
}
/**
* sum of squares of all values
* @param values
*/
public static double Sumsq(double[] values)
{
double sumsq = 0;
for (int i = 0, iSize = values.Length; i < iSize; i++)
{
sumsq += values[i] * values[i];
}
return sumsq;
}
/**
* product of all values
* @param values
*/
public static double Product(double[] values)
{
double product = 0;
if (values != null && values.Length > 0)
{
product = 1;
for (int i = 0, iSize = values.Length; i < iSize; i++)
{
product *= values[i];
}
}
return product;
}
/**
* min of all values. If supplied array Is zero Length,
* double.POSITIVE_INFINITY Is returned.
* @param values
*/
public static double Min(double[] values)
{
double min = double.PositiveInfinity;
for (int i = 0, iSize = values.Length; i < iSize; i++)
{
min = Math.Min(min, values[i]);
}
return min;
}
/**
* min of all values. If supplied array Is zero Length,
* double.NEGATIVE_INFINITY Is returned.
* @param values
*/
public static double Max(double[] values)
{
double max = double.NegativeInfinity;
for (int i = 0, iSize = values.Length; i < iSize; i++)
{
max = Math.Max(max, values[i]);
}
return max;
}
/**
* Note: this function Is different from java.lang.Math.floor(..).
*
* When n and s are "valid" arguments, the returned value Is: Math.floor(n/s) * s;
* <br/>
* n and s are invalid if any of following conditions are true:
* <ul>
* <li>s Is zero</li>
* <li>n Is negative and s Is positive</li>
* <li>n Is positive and s Is negative</li>
* </ul>
* In all such cases, double.NaN Is returned.
* @param n
* @param s
*/
public static double Floor(double n, double s)
{
double f;
if ((n < 0 && s > 0) || (n > 0 && s < 0) || (s == 0 && n != 0))
{
f = double.NaN;
}
else
{
f = (n == 0 || s == 0) ? 0 : Math.Floor(n / s) * s;
}
return f;
}
/**
* Note: this function Is different from java.lang.Math.ceil(..).
*
* When n and s are "valid" arguments, the returned value Is: Math.ceiling(n/s) * s;
* <br/>
* n and s are invalid if any of following conditions are true:
* <ul>
* <li>s Is zero</li>
* <li>n Is negative and s Is positive</li>
* <li>n Is positive and s Is negative</li>
* </ul>
* In all such cases, double.NaN Is returned.
* @param n
* @param s
*/
public static double Ceiling(double n, double s)
{
double c;
if (n > 0 && s < 0)
{
c = double.NaN;
}
else
{
c = (n == 0 || s == 0) ? 0 : Math.Ceiling(n / s) * s;
}
return c;
}
/**
* <br/> for all n >= 1; factorial n = n * (n-1) * (n-2) * ... * 1
* <br/> else if n == 0; factorial n = 1
* <br/> else if n < 0; factorial n = double.NaN
* <br/> Loss of precision can occur if n Is large enough.
* If n Is large so that the resulting value would be greater
* than double.MAX_VALUE; double.POSITIVE_INFINITY Is returned.
* If n < 0, double.NaN Is returned.
* @param n
*/
public static double Factorial(int n)
{
double d = 1;
if (n >= 0)
{
if (n <= 170)
{
for (int i = 1; i <= n; i++)
{
d *= i;
}
}
else
{
d = double.PositiveInfinity;
}
}
else
{
d = double.NaN;
}
return d;
}
/**
* returns the remainder resulting from operation:
* n / d.
* <br/> The result has the sign of the divisor.
* <br/> Examples:
* <ul>
* <li>mod(3.4, 2) = 1.4</li>
* <li>mod(-3.4, 2) = 0.6</li>
* <li>mod(-3.4, -2) = -1.4</li>
* <li>mod(3.4, -2) = -0.6</li>
* </ul>
* If d == 0, result Is NaN
* @param n
* @param d
*/
public static double Mod(double n, double d)
{
double result = 0;
if (d == 0)
{
result = double.NaN;
}
else if (Sign(n) == Sign(d))
{
//double t = Math.Abs(n / d);
//t = t - (long)t;
//result = sign(d) * Math.Abs(t * d);
result = n % d;
}
else
{
//double t = Math.Abs(n / d);
//t = t - (long)t;
//t = Math.Ceiling(t) - t;
//result = sign(d) * Math.Abs(t * d);
result = ((n % d) + d) % d;
}
return result;
}
/**
* inverse hyperbolic cosine
* @param d
*/
public static double Acosh(double d)
{
return Math.Log(Math.Sqrt(Math.Pow(d, 2) - 1) + d);
}
/**
* inverse hyperbolic sine
* @param d
*/
public static double Asinh(double d)
{
double d2 = d * d;
return Math.Log(Math.Sqrt(d * d + 1) + d);
}
/**
* inverse hyperbolic tangent
* @param d
*/
public static double Atanh(double d)
{
return Math.Log((1 + d) / (1 - d)) / 2;
}
/**
* hyperbolic cosine
* @param d
*/
public static double Cosh(double d)
{
double ePowX = Math.Pow(Math.E, d);
double ePowNegX = Math.Pow(Math.E, -d);
d = (ePowX + ePowNegX) / 2;
return d;
}
/**
* hyperbolic sine
* @param d
*/
public static double Sinh(double d)
{
double ePowX = Math.Pow(Math.E, d);
double ePowNegX = Math.Pow(Math.E, -d);
d = (ePowX - ePowNegX) / 2;
return d;
}
/**
* hyperbolic tangent
* @param d
*/
public static double Tanh(double d)
{
double ePowX = Math.Pow(Math.E, d);
double ePowNegX = Math.Pow(Math.E, -d);
d = (ePowX - ePowNegX) / (ePowX + ePowNegX);
return d;
}
/**
* returns the sum of product of corresponding double value in each
* subarray. It Is the responsibility of the caller to Ensure that
* all the subarrays are of equal Length. If the subarrays are
* not of equal Length, the return value can be Unpredictable.
* @param arrays
*/
public static double SumProduct(double[][] arrays)
{
double d = 0;
try
{
int narr = arrays.Length;
int arrlen = arrays[0].Length;
for (int j = 0; j < arrlen; j++)
{
double t = 1;
for (int i = 0; i < narr; i++)
{
t *= arrays[i][j];
}
d += t;
}
}
catch (IndexOutOfRangeException)
{
d = double.NaN;
}
return d;
}
/**
* returns the sum of difference of squares of corresponding double
* value in each subarray: ie. sigma (xarr[i]^2-yarr[i]^2)
* <br/>
* It Is the responsibility of the caller
* to Ensure that the two subarrays are of equal Length. If the
* subarrays are not of equal Length, the return value can be
* Unpredictable.
* @param xarr
* @param yarr
*/
public static double Sumx2my2(double[] xarr, double[] yarr)
{
double d = 0;
try
{
for (int i = 0, iSize = xarr.Length; i < iSize; i++)
{
d += (xarr[i] + yarr[i]) * (xarr[i] - yarr[i]);
}
}
catch (IndexOutOfRangeException)
{
d = double.NaN;
}
return d;
}
/**
* returns the sum of sum of squares of corresponding double
* value in each subarray: ie. sigma (xarr[i]^2 + yarr[i]^2)
* <br/>
* It Is the responsibility of the caller
* to Ensure that the two subarrays are of equal Length. If the
* subarrays are not of equal Length, the return value can be
* Unpredictable.
* @param xarr
* @param yarr
*/
public static double Sumx2py2(double[] xarr, double[] yarr)
{
double d = 0;
try
{
for (int i = 0, iSize = xarr.Length; i < iSize; i++)
{
d += (xarr[i] * xarr[i]) + (yarr[i] * yarr[i]);
}
}
catch (IndexOutOfRangeException )
{
d = double.NaN;
}
return d;
}
/**
* returns the sum of squares of difference of corresponding double
* value in each subarray: ie. sigma ( (xarr[i]-yarr[i])^2 )
* <br/>
* It Is the responsibility of the caller
* to Ensure that the two subarrays are of equal Length. If the
* subarrays are not of equal Length, the return value can be
* Unpredictable.
* @param xarr
* @param yarr
*/
public static double Sumxmy2(double[] xarr, double[] yarr)
{
double d = 0;
try
{
for (int i = 0, iSize = xarr.Length; i < iSize; i++)
{
double t = (xarr[i] - yarr[i]);
d += t * t;
}
}
catch (IndexOutOfRangeException )
{
d = double.NaN;
}
return d;
}
/**
* returns the total number of combinations possible when
* k items are chosen out of total of n items. If the number
* Is too large, loss of precision may occur (since returned
* value Is double). If the returned value Is larger than
* double.MAX_VALUE, double.POSITIVE_INFINITY Is returned.
* If either of the parameters Is negative, double.NaN Is returned.
* @param n
* @param k
*/
public static double NChooseK(int n, int k)
{
double d = 1;
if (n < 0 || k < 0 || n < k)
{
d = double.NaN;
}
else
{
int minnk = Math.Min(n - k, k);
int maxnk = Math.Max(n - k, k);
for (int i = maxnk; i < n; i++)
{
d *= i + 1;
}
d /= Factorial(minnk);
}
return d;
}
}
}
| |
namespace Greatbone
{
/// <summary>
/// An XML parser structure that deals with well-formed XML documents.
/// </summary>
public struct XmlParser : IParser<XElem>
{
static readonly ParserException ParserEx = new ParserException("error parsing xml");
// bytes to parse
readonly byte[] bytebuf;
// chars to parse
readonly string strbuf;
readonly int length;
// UTF-8 string builder
readonly Text text;
public XmlParser(byte[] bytebuf, int length)
{
this.bytebuf = bytebuf;
this.strbuf = null;
this.length = length;
this.text = new Text(1024);
}
public XmlParser(string strbuf)
{
this.bytebuf = null;
this.strbuf = strbuf;
this.length = strbuf.Length;
this.text = new Text(1024);
}
int this[int index] => bytebuf?[index] ?? (int) strbuf[index];
public XElem Parse()
{
int p = 0;
// seek to a less-than (<)
int b;
while (IsWs(b = this[p]))
{
p++;
} // skip ws
if (b != '<') throw ParserEx;
// the first char
b = this[++p];
if (b == '?') // skip the prolog line
{
while (this[++p] != '>')
{
}
// seek to a <
for (;;)
{
b = this[++p];
if (IsWs(b)) continue; // skip ws
if (b == '<') break;
throw ParserEx;
}
}
if (IsNameStartChar(b))
{
return ParseElem(ref p, b);
}
throw ParserEx;
}
static bool IsWs(int c)
{
return c == ' ' || c == '\t' || c == '\n' || c == '\r';
}
static bool IsNameStartChar(int c)
{
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '_';
}
static bool IsNameChar(int c)
{
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '_' || c == '-' || c >= '0' && c <= '9';
}
XElem ParseElem(ref int pos, int startchar)
{
int p = pos;
int b;
// parse element tag name
text.Clear();
text.Accept(startchar);
while (IsNameChar(b = this[++p]))
{
text.Accept(b); // to comprise start tag
}
string tag = text.ToString();
XElem elem = new XElem(tag);
// optionally parse attributes
while (IsWs(b))
{
while (IsWs(b = this[++p]))
{
} // skip ws
if (IsNameStartChar(b))
{
// attribute name
text.Clear();
text.Accept(b);
while ((b = this[++p]) != '=')
{
text.Accept(b);
}
string name = text.ToString();
// attribute value
if (this[++p] != '"') throw ParserEx; // left quote
text.Clear();
while ((b = this[++p]) != '"') // till right quote
{
if (b == '&') // escape < > & "
{
int b1 = this[p + 1];
int b2 = this[p + 2];
int b3 = this[p + 3];
if (b1 == 'l' && b2 == 't' && b3 == ';')
{
b = '<';
p += 3;
}
else if (b1 == 'g' && b2 == 't' && b3 == ';')
{
b = '>';
p += 3;
}
else if (b1 == 'a' && b2 == 'm' && b3 == 'p' && this[p + 4] == ';')
{
b = '&';
p += 4;
}
else if (b1 == 'q' && b2 == 'u' && b3 == 'o' && this[p + 4] == 't' && this[p + 5] == ';')
{
b = '"';
p += 5;
}
}
text.Accept(b);
}
string value = text.ToString();
elem.AddAttr(name, value);
b = this[++p]; // step
}
} // end of attributes
if (b == '>') // a start tag just finished, expecting the ending-tag
{
for (;;) // child nodes iteration
{
while (IsWs(b = this[++p])) // skip ws
{
}
if (b == '<')
{
b = this[++p];
if (b == '/') // the ending tag
{
// consume
text.Clear();
while ((b = this[++p]) != '>')
{
text.Accept(b);
}
if (!text.Equals(tag)) throw ParserEx;
pos = p; // adjust current position
return elem;
}
else if (b == '!') // CDATA section
{
if (this[p + 1] == '[' && this[p + 2] == 'C' && this[p + 3] == 'D' && this[p + 4] == 'A' && this[p + 5] == 'T' && this[p + 6] == 'A' && this[p + 7] == '[')
{
text.Clear();
p += 7;
while ((b = this[++p]) != ']' || this[p + 1] != ']' || this[p + 2] != '>')
{
text.Accept(b);
}
elem.Text = text.ToString();
p += 2; // skip ]>
}
}
else if (IsNameStartChar(b))
{
XElem child = ParseElem(ref p, b);
elem.Add(child);
}
}
else // text node
{
text.Clear();
while ((b = this[p]) != '<') // NOTE from the first char
{
if (b == '&') // escape < > & "
{
int b1 = this[p + 1];
int b2 = this[p + 2];
int b3 = this[p + 3];
if (b1 == 'l' && b2 == 't' && b3 == ';')
{
b = '<';
p += 3;
}
else if (b1 == 'g' && b2 == 't' && b3 == ';')
{
b = '>';
p += 3;
}
else if (b1 == 'a' && b2 == 'm' && b3 == 'p' && this[p + 4] == ';')
{
b = '&';
p += 4;
}
else if (b1 == 'q' && b2 == 'u' && b3 == 'o' && this[p + 4] == 't' && this[p + 5] == ';')
{
b = '"';
p += 5;
}
}
text.Accept(b);
++p;
}
if (text.Count > 0)
{
elem.Text = text.ToString();
}
// NOTE decrease in position to behave as other child nodes
--p;
}
} // child nodes iteration
}
if (b == '/' && this[++p] == '>') // empty-element
{
pos = p; // adjust current position
return elem;
}
throw ParserEx;
}
}
}
| |
/*
* Exchange Web Services Managed API
*
* 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.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
/// <summary>
/// XML reader.
/// </summary>
internal class EwsServiceXmlReader : EwsXmlReader
{
#region Private members
private ExchangeService service;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="EwsServiceXmlReader"/> class.
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="service">The service.</param>
internal EwsServiceXmlReader(Stream stream, ExchangeService service)
: base(stream)
{
this.service = service;
}
#endregion
/// <summary>
/// Converts the specified string into a DateTime objects.
/// </summary>
/// <param name="dateTimeString">The date time string to convert.</param>
/// <returns>A DateTime representing the converted string.</returns>
private DateTime? ConvertStringToDateTime(string dateTimeString)
{
return this.Service.ConvertUniversalDateTimeStringToLocalDateTime(dateTimeString);
}
/// <summary>
/// Converts the specified string into a unspecified Date object, ignoring offset.
/// </summary>
/// <param name="dateTimeString">The date time string to convert.</param>
/// <returns>A DateTime representing the converted string.</returns>
private DateTime? ConvertStringToUnspecifiedDate(string dateTimeString)
{
return this.Service.ConvertStartDateToUnspecifiedDateTime(dateTimeString);
}
/// <summary>
/// Reads the element value as date time.
/// </summary>
/// <returns>Element value.</returns>
public DateTime? ReadElementValueAsDateTime()
{
return this.ConvertStringToDateTime(this.ReadElementValue());
}
/// <summary>
/// Reads the element value as unspecified date.
/// </summary>
/// <returns>Element value.</returns>
public DateTime? ReadElementValueAsUnspecifiedDate()
{
return this.ConvertStringToUnspecifiedDate(this.ReadElementValue());
}
/// <summary>
/// Reads the element value as date time, assuming it is unbiased (e.g. 2009/01/01T08:00)
/// and scoped to service's time zone.
/// </summary>
/// <returns>The element's value as a DateTime object.</returns>
public DateTime ReadElementValueAsUnbiasedDateTimeScopedToServiceTimeZone()
{
string elementValue = this.ReadElementValue();
return EwsUtilities.ParseAsUnbiasedDatetimescopedToServicetimeZone(elementValue, this.Service);
}
/// <summary>
/// Reads the element value as date time.
/// </summary>
/// <param name="xmlNamespace">The XML namespace.</param>
/// <param name="localName">Name of the local.</param>
/// <returns>Element value.</returns>
public DateTime? ReadElementValueAsDateTime(XmlNamespace xmlNamespace, string localName)
{
return this.ConvertStringToDateTime(this.ReadElementValue(xmlNamespace, localName));
}
/// <summary>
/// Reads the service objects collection from XML.
/// </summary>
/// <typeparam name="TServiceObject">The type of the service object.</typeparam>
/// <param name="collectionXmlNamespace">Namespace of the collection XML element.</param>
/// <param name="collectionXmlElementName">Name of the collection XML element.</param>
/// <param name="getObjectInstanceDelegate">The get object instance delegate.</param>
/// <param name="clearPropertyBag">if set to <c>true</c> [clear property bag].</param>
/// <param name="requestedPropertySet">The requested property set.</param>
/// <param name="summaryPropertiesOnly">if set to <c>true</c> [summary properties only].</param>
/// <returns>List of service objects.</returns>
public List<TServiceObject> ReadServiceObjectsCollectionFromXml<TServiceObject>(
XmlNamespace collectionXmlNamespace,
string collectionXmlElementName,
GetObjectInstanceDelegate<TServiceObject> getObjectInstanceDelegate,
bool clearPropertyBag,
PropertySet requestedPropertySet,
bool summaryPropertiesOnly) where TServiceObject : ServiceObject
{
List<TServiceObject> serviceObjects = new List<TServiceObject>();
TServiceObject serviceObject = null;
if (!this.IsStartElement(collectionXmlNamespace, collectionXmlElementName))
{
this.ReadStartElement(collectionXmlNamespace, collectionXmlElementName);
}
if (!this.IsEmptyElement)
{
do
{
this.Read();
if (this.IsStartElement())
{
serviceObject = getObjectInstanceDelegate(this.Service, this.LocalName);
if (serviceObject == null)
{
this.SkipCurrentElement();
}
else
{
if (string.Compare(this.LocalName, serviceObject.GetXmlElementName(), StringComparison.Ordinal) != 0)
{
throw new ServiceLocalException(
string.Format(
"The type of the object in the store ({0}) does not match that of the local object ({1}).",
this.LocalName,
serviceObject.GetXmlElementName()));
}
serviceObject.LoadFromXml(
this,
clearPropertyBag,
requestedPropertySet,
summaryPropertiesOnly);
serviceObjects.Add(serviceObject);
}
}
}
while (!this.IsEndElement(collectionXmlNamespace, collectionXmlElementName));
}
return serviceObjects;
}
/// <summary>
/// Reads the service objects collection from XML.
/// </summary>
/// <typeparam name="TServiceObject">The type of the service object.</typeparam>
/// <param name="collectionXmlElementName">Name of the collection XML element.</param>
/// <param name="getObjectInstanceDelegate">The get object instance delegate.</param>
/// <param name="clearPropertyBag">if set to <c>true</c> [clear property bag].</param>
/// <param name="requestedPropertySet">The requested property set.</param>
/// <param name="summaryPropertiesOnly">if set to <c>true</c> [summary properties only].</param>
/// <returns>List of service objects.</returns>
public List<TServiceObject> ReadServiceObjectsCollectionFromXml<TServiceObject>(
string collectionXmlElementName,
GetObjectInstanceDelegate<TServiceObject> getObjectInstanceDelegate,
bool clearPropertyBag,
PropertySet requestedPropertySet,
bool summaryPropertiesOnly) where TServiceObject : ServiceObject
{
return this.ReadServiceObjectsCollectionFromXml<TServiceObject>(
XmlNamespace.Messages,
collectionXmlElementName,
getObjectInstanceDelegate,
clearPropertyBag,
requestedPropertySet,
summaryPropertiesOnly);
}
/// <summary>
/// Gets the service.
/// </summary>
/// <value>The service.</value>
public ExchangeService Service
{
get { return this.service; }
}
}
}
| |
//
// PermissionSetTest.cs - NUnit Test Cases for PermissionSet
//
// Author:
// Sebastien Pouliot <[email protected]>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using NUnit.Framework;
using System;
using System.Collections;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Text;
namespace MonoTests.System.Security {
[TestFixture]
public class PermissionSetTest : Assertion {
[Test]
public void PermissionStateNone ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
Assert ("PermissionStateNone.IsUnrestricted", !ps.IsUnrestricted ());
Assert ("PermissionStateNone.IsEmpty", ps.IsEmpty ());
Assert ("PermissionStateNone.IsReadOnly", !ps.IsReadOnly);
AssertEquals ("PermissionStateNone.ToXml().ToString()==ToString()", ps.ToXml ().ToString (), ps.ToString ());
}
[Test]
public void PermissionStateUnrestricted ()
{
PermissionSet ps = new PermissionSet (PermissionState.Unrestricted);
Assert ("PermissionStateUnrestricted.IsUnrestricted", ps.IsUnrestricted ());
Assert ("PermissionStateUnrestricted.IsEmpty", !ps.IsEmpty ());
Assert ("PermissionStateUnrestricted.IsReadOnly", !ps.IsReadOnly);
AssertEquals ("PermissionStateUnrestricted.ToXml().ToString()==ToString()", ps.ToXml ().ToString (), ps.ToString ());
}
[Test]
public void PermissionSetNull ()
{
// no exception is thrown
PermissionSet ps = new PermissionSet (null);
#if NET_2_0
Assert ("PermissionStateNull.IsUnrestricted", !ps.IsUnrestricted ());
Assert ("PermissionStateNull.IsEmpty", ps.IsEmpty ());
#else
Assert ("PermissionStateNull.IsUnrestricted", ps.IsUnrestricted ());
Assert ("PermissionStateNull.IsEmpty", !ps.IsEmpty ());
#endif
Assert ("PermissionStateNull.IsReadOnly", !ps.IsReadOnly);
AssertEquals ("PermissionStateNull.ToXml().ToString()==ToString()", ps.ToXml ().ToString (), ps.ToString ());
}
[Test]
public void PermissionSetPermissionSet ()
{
FileDialogPermission fdp = new FileDialogPermission (FileDialogPermissionAccess.Open);
PermissionSet ps1 = new PermissionSet (PermissionState.None);
ps1.AddPermission (fdp);
Assert ("ps1.IsEmpty", !ps1.IsEmpty ());
PermissionSet ps = new PermissionSet (ps1);
Assert ("PermissionSetPermissionSet.IsUnrestricted", !ps.IsUnrestricted ());
Assert ("PermissionSetPermissionSet.IsEmpty", !ps.IsEmpty ());
Assert ("PermissionSetPermissionSet.IsReadOnly", !ps.IsReadOnly);
AssertEquals ("PermissionSetPermissionSet.ToXml().ToString()==ToString()", ps.ToXml ().ToString (), ps.ToString ());
}
[Test]
public void PermissionSetNamedPermissionSet ()
{
NamedPermissionSet nps = new NamedPermissionSet ("Test", PermissionState.Unrestricted);
PermissionSet ps = new PermissionSet (nps);
Assert ("IsUnrestricted", ps.IsUnrestricted ());
}
[Test]
public void AddPermission ()
{
SecurityPermission sp1 = new SecurityPermission (SecurityPermissionFlag.ControlEvidence);
SecurityPermission sp2 = new SecurityPermission (SecurityPermissionFlag.ControlPolicy);
PermissionSet ps = new PermissionSet (PermissionState.None);
SecurityPermission result = (SecurityPermission)ps.AddPermission (sp1);
AssertEquals ("1-ControlEvidence", 1, ps.Count);
AssertEquals ("Flags-1", SecurityPermissionFlag.ControlEvidence, result.Flags);
result = (SecurityPermission)ps.AddPermission (sp2);
AssertEquals ("1-ControlEvidence+ControlPolicy", 1, ps.Count);
AssertEquals ("Flags-2", SecurityPermissionFlag.ControlPolicy | SecurityPermissionFlag.ControlEvidence, result.Flags);
result = (SecurityPermission)ps.AddPermission (sp2);
AssertEquals ("no change-1", 1, ps.Count);
AssertEquals ("Flags-3", SecurityPermissionFlag.ControlPolicy | SecurityPermissionFlag.ControlEvidence, result.Flags);
result = (SecurityPermission)ps.AddPermission (sp1);
AssertEquals ("no change-2", 1, ps.Count);
AssertEquals ("Flags-4", SecurityPermissionFlag.ControlPolicy | SecurityPermissionFlag.ControlEvidence, result.Flags);
}
[Test]
public void AddPermission_Null ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
IPermission result = ps.AddPermission (null);
AssertNull ("Add(null)", result);
AssertEquals ("0", 0, ps.Count);
}
[Test]
public void AddPermission_SetUnrestricted ()
{
PermissionSet ps = new PermissionSet (PermissionState.Unrestricted);
SecurityPermission sp = new SecurityPermission (SecurityPermissionFlag.ControlEvidence);
IPermission result = ps.AddPermission (sp);
AssertNotNull ("Add(SecurityPermission)", result);
AssertEquals ("SecurityPermission", SecurityPermissionFlag.AllFlags, (result as SecurityPermission).Flags);
AssertEquals ("0", 0, ps.Count);
ZoneIdentityPermission zip = new ZoneIdentityPermission (SecurityZone.MyComputer);
result = ps.AddPermission (zip);
AssertNotNull ("Add(ZoneIdentityPermission)", result);
#if NET_2_0
// Identity permissions aren't added to unrestricted permission sets in 2.0
AssertEquals ("ZoneIdentityPermission", SecurityZone.NoZone, (result as ZoneIdentityPermission).SecurityZone);
AssertEquals ("1", 0, ps.Count);
#else
AssertEquals ("ZoneIdentityPermission", zip.SecurityZone, (result as ZoneIdentityPermission).SecurityZone);
AssertEquals ("1", 1, ps.Count);
#endif
}
[Test]
public void AddPermission_PermissionUnrestricted ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
SecurityPermission sp = new SecurityPermission (PermissionState.Unrestricted);
IPermission result = ps.AddPermission (sp);
AssertNotNull ("Add(SecurityPermission)", result);
AssertEquals ("SecurityPermission", SecurityPermissionFlag.AllFlags, (result as SecurityPermission).Flags);
AssertEquals ("1", 1, ps.Count);
Assert ("State", !ps.IsUnrestricted ());
}
[Test]
public void AddPermission_NoCopy ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
SecurityPermission sp1 = new SecurityPermission (SecurityPermissionFlag.ControlEvidence);
SecurityPermission result = (SecurityPermission)ps.AddPermission (sp1);
SecurityPermission entry = (SecurityPermission)ps.GetPermission (typeof (SecurityPermission));
// are they the same (reference) or different ?
sp1.Flags = SecurityPermissionFlag.AllFlags;
result.Flags = SecurityPermissionFlag.Assertion;
}
[Test]
public void ContainsNonCodeAccessPermissions ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
Assert ("Empty", !ps.ContainsNonCodeAccessPermissions ());
SecurityPermission sp = new SecurityPermission (PermissionState.Unrestricted);
ps.AddPermission (sp);
Assert ("SecurityPermission", !ps.ContainsNonCodeAccessPermissions ());
PrincipalPermission pp = new PrincipalPermission ("mono", "hacker");
ps.AddPermission (pp);
Assert ("PrincipalPermission", ps.ContainsNonCodeAccessPermissions ());
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void ConvertPermissionSet_NullIn ()
{
PermissionSet.ConvertPermissionSet (null, new byte [0], "XML");
}
[Test]
public void ConvertPermissionSet_UnknownIn ()
{
byte[] result = PermissionSet.ConvertPermissionSet (String.Empty, new byte [0], "XML");
AssertNull (result);
}
[Test]
public void ConvertPermissionSet_NullData ()
{
byte[] result = PermissionSet.ConvertPermissionSet ("BINARY", null, "XML");
AssertNull (result);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void ConvertPermissionSet_NullOut ()
{
PermissionSet.ConvertPermissionSet ("BINARY", new byte [0], null);
}
[Test]
[ExpectedException (typeof (SerializationException))]
public void ConvertPermissionSet_UnknownOut ()
{
PermissionSet.ConvertPermissionSet ("BINARY", new byte [0], String.Empty);
}
[Test]
#if !NET_2_0
[Ignore ("Don't know why it doesn't work under Fx 1.1")]
#endif
public void ConvertPermissionSet_BinaryToBinary ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
byte[] data = Encoding.ASCII.GetBytes (ps.ToString ());
byte[] result = PermissionSet.ConvertPermissionSet ("XML", data, "BINARY");
byte[] result2 = PermissionSet.ConvertPermissionSet ("BINARY", result, "BINARY");
// there's only a little difference - but it doesn't throw an exception
//Assert ("BINARY!=BINARY", BitConverter.ToString (result) != BitConverter.ToString (result2));
}
[Test]
#if !NET_2_0
[Ignore ("Don't know why it doesn't work under Fx 1.1")]
#endif
public void ConvertPermissionSet_XmlToBinary ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
byte[] data = Encoding.ASCII.GetBytes (ps.ToString ());
byte[] result = PermissionSet.ConvertPermissionSet ("XML", data, "BINARY");
byte[] result2 = PermissionSet.ConvertPermissionSet ("XMLASCII", data, "BINARY");
AssertEquals ("XML==XMLASCII", BitConverter.ToString (result), BitConverter.ToString (result2));
byte[] back = PermissionSet.ConvertPermissionSet ("BINARY", result, "XML");
AssertEquals ("PS-XML", Encoding.ASCII.GetString (back), ps.ToString ());
back = PermissionSet.ConvertPermissionSet ("BINARY", result2, "XMLASCII");
AssertEquals ("PS-XMLASCII", Encoding.ASCII.GetString (back), ps.ToString ());
}
[Test]
public void ConvertPermissionSet_XmlToXml ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
byte[] data = Encoding.ASCII.GetBytes (ps.ToString ());
byte[] result = PermissionSet.ConvertPermissionSet ("XML", data, "XML");
AssertEquals ("PS-XML", Encoding.ASCII.GetString (result), ps.ToString ());
result = PermissionSet.ConvertPermissionSet ("XMLASCII", data, "XMLASCII");
AssertEquals ("PS-XMLASCII", Encoding.ASCII.GetString (result), ps.ToString ());
}
[Test]
#if NET_2_0
[ExpectedException (typeof (XmlSyntaxException))]
#else
[ExpectedException (typeof (ArgumentException))]
#endif
public void ConvertPermissionSet_XmlAsciiToXmlUnicode ()
{
PermissionSet ps = new PermissionSet (PermissionState.Unrestricted);
byte[] data = Encoding.Unicode.GetBytes (ps.ToString ());
byte[] result = PermissionSet.ConvertPermissionSet ("XMLASCII", data, "XMLUNICODE");
// the method isn't intended to convert between ASCII and Unicode
}
[Test]
public void Copy_None ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
PermissionSet copy = ps.Copy ();
Assert ("1.State", !copy.IsUnrestricted ());
AssertEquals ("1.Count", 0, copy.Count);
SecurityPermission sp = new SecurityPermission (SecurityPermissionFlag.ControlEvidence);
IPermission result = ps.AddPermission (sp);
AssertNotNull ("1.Add", result);
copy = ps.Copy ();
Assert ("2.State", !copy.IsUnrestricted ());
AssertEquals ("2.Count", 1, copy.Count);
ZoneIdentityPermission zip = new ZoneIdentityPermission (SecurityZone.MyComputer);
result = ps.AddPermission (zip);
AssertNotNull ("2.Add", result);
copy = ps.Copy ();
Assert ("3.State", !copy.IsUnrestricted ());
AssertEquals ("3.Count", 2, copy.Count);
}
[Test]
public void Copy_Unrestricted ()
{
PermissionSet ps = new PermissionSet (PermissionState.Unrestricted);
PermissionSet copy = ps.Copy ();
Assert ("1.State", copy.IsUnrestricted ());
AssertEquals ("1.Count", 0, copy.Count);
SecurityPermission sp = new SecurityPermission (SecurityPermissionFlag.ControlEvidence);
IPermission result = ps.AddPermission (sp);
AssertNotNull ("1.Add", result);
copy = ps.Copy ();
Assert ("2.State", copy.IsUnrestricted ());
AssertEquals ("2.Count", 0, copy.Count);
ZoneIdentityPermission zip = new ZoneIdentityPermission (SecurityZone.MyComputer);
result = ps.AddPermission (zip);
AssertNotNull ("2.Add", result);
copy = ps.Copy ();
Assert ("3.State", copy.IsUnrestricted ());
#if NET_2_0
// Identity permissions aren't added to unrestricted permission sets in 2.0
AssertEquals ("3.Count", 0, copy.Count);
#else
AssertEquals ("3.Count", 1, copy.Count);
#endif
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void CopyTo_Null ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
ps.CopyTo (null, 0);
}
[Test]
public void CopyTo_Rank_Empty ()
{
IPermission[,] pa = new IPermission [1,1];
PermissionSet ps = new PermissionSet (PermissionState.None);
ps.CopyTo (pa, 0);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void CopyTo_Rank ()
{
IPermission [,] pa = new IPermission [1, 1];
PermissionSet ps = new PermissionSet (PermissionState.None);
ps.AddPermission (new SecurityPermission (SecurityPermissionFlag.Assertion));
ps.CopyTo (pa, 0);
}
[Test]
public void CopyTo_NegativeIndex_Empty ()
{
IPermission[] pa = new IPermission [1];
PermissionSet ps = new PermissionSet (PermissionState.None);
ps.CopyTo (pa, Int32.MinValue);
}
[Test]
[ExpectedException (typeof (IndexOutOfRangeException))]
public void CopyTo_NegativeIndex ()
{
IPermission [] pa = new IPermission [1];
PermissionSet ps = new PermissionSet (PermissionState.None);
ps.AddPermission (new SecurityPermission (SecurityPermissionFlag.Assertion));
ps.CopyTo (pa, Int32.MinValue);
}
[Test]
public void CopyTo_IndexOverLength_Empty ()
{
IPermission [] pa = new IPermission [1];
PermissionSet ps = new PermissionSet (PermissionState.None);
ps.CopyTo (pa, pa.Length);
}
[Test]
[ExpectedException (typeof (IndexOutOfRangeException))]
public void CopyTo_IndexOverLength ()
{
IPermission [] pa = new IPermission [1];
PermissionSet ps = new PermissionSet (PermissionState.None);
ps.AddPermission (new SecurityPermission (SecurityPermissionFlag.Assertion));
ps.CopyTo (pa, pa.Length);
}
[Test]
public void CopyTo ()
{
IPermission [] pa = new IPermission [1];
SecurityPermission sp = new SecurityPermission (SecurityPermissionFlag.Assertion);
PermissionSet ps = new PermissionSet (PermissionState.None);
ps.AddPermission (sp);
ps.CopyTo (pa, 0);
AssertEquals ("CopyTo", pa [0].ToString (), sp.ToString ());
Assert ("Reference", Object.ReferenceEquals (pa [0], sp));
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void FromXmlNull ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
ps.FromXml (null);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void FromXmlInvalidPermission ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
SecurityElement se = ps.ToXml ();
// can't modify - so we create our own
SecurityElement se2 = new SecurityElement ("InvalidPermissionSet", se.Text);
se2.AddAttribute ("class", se.Attribute ("class"));
se2.AddAttribute ("version", se.Attribute ("version"));
ps.FromXml (se2);
}
[Test]
// [ExpectedException (typeof (ArgumentException))]
public void FromXmlWrongVersion ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
SecurityElement se = ps.ToXml ();
// can't modify - so we create our own
SecurityElement se2 = new SecurityElement (se.Tag, se.Text);
se2.AddAttribute ("class", se.Attribute ("class"));
se2.AddAttribute ("version", "2");
ps.FromXml (se2);
// wow - here we accept a version 2 !!!
}
[Test]
public void FromXmlEmpty ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
SecurityElement se = ps.ToXml ();
AssertNotNull ("Empty.ToXml()", se);
AssertEquals ("Empty.Count", 0, ps.Count);
PermissionSet ps2 = (PermissionSet) ps.Copy ();
ps2.FromXml (se);
Assert ("FromXml-Copy.IsUnrestricted", !ps2.IsUnrestricted ());
se.AddAttribute ("Unrestricted", "true");
ps2.FromXml (se);
Assert ("FromXml-Unrestricted.IsUnrestricted", ps2.IsUnrestricted ());
}
[Test]
public void FromXmlOne ()
{
FileDialogPermission fdp = new FileDialogPermission (FileDialogPermissionAccess.Open);
PermissionSet ps1 = new PermissionSet (PermissionState.None);
ps1.AddPermission (fdp);
Assert ("ps1.IsEmpty", !ps1.IsEmpty ());
PermissionSet ps = new PermissionSet (ps1);
SecurityElement se = ps.ToXml ();
AssertNotNull ("One.ToXml()", se);
AssertEquals ("One.Count", 1, ps.Count);
PermissionSet ps2 = (PermissionSet) ps.Copy ();
ps2.FromXml (se);
Assert ("FromXml-Copy.IsUnrestricted", !ps2.IsUnrestricted ());
AssertEquals ("Copy.Count", 1, ps2.Count);
se.AddAttribute ("Unrestricted", "true");
ps2.FromXml (se);
Assert ("FromXml-Unrestricted.IsUnrestricted", ps2.IsUnrestricted ());
#if NET_2_0
AssertEquals ("Unrestricted.Count", 0, ps2.Count);
#else
// IPermission not shown in XML but still present in Count
AssertEquals ("Unrestricted.Count", 1, ps2.Count);
#endif
}
[Test]
#if NET_2_0
[ExpectedException (typeof (TypeLoadException))]
#else
[ExpectedException (typeof (ArgumentException))]
#endif
public void FromXml_PermissionWithoutNamespace ()
{
SecurityElement child = new SecurityElement ("IPermission");
child.AddAttribute ("class", "EnvironmentPermission");
child.AddAttribute ("version", "1");
child.AddAttribute ("Read", "USERNAME");
SecurityElement se = new SecurityElement ("PermissionSet");
se.AddAttribute ("class", "PermissionSet");
se.AddAttribute ("version", "1");
se.AddChild (child);
PermissionSet ps = new PermissionSet (PermissionState.None);
ps.FromXml (se);
}
[Test]
#if NET_2_0
[ExpectedException (typeof (TypeLoadException))]
#else
[ExpectedException (typeof (ArgumentException))]
#endif
public void FromXml_PermissionOutsideCorlib ()
{
SecurityElement child = new SecurityElement ("IPermission");
child.AddAttribute ("class", "PrintingPermission"); // System.Drawing
child.AddAttribute ("version", "1");
child.AddAttribute ("Level", "DefaultPrinting");
SecurityElement se = new SecurityElement ("PermissionSet");
se.AddAttribute ("class", "PermissionSet");
se.AddAttribute ("version", "1");
se.AddChild (child);
PermissionSet ps = new PermissionSet (PermissionState.None);
ps.FromXml (se);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void FromXml_WithPermissionWithoutClass ()
{
SecurityElement child = new SecurityElement ("IPermission");
child.AddAttribute ("version", "1");
SecurityElement se = new SecurityElement ("PermissionSet");
se.AddAttribute ("class", "PermissionSet");
se.AddAttribute ("version", "1");
se.AddChild (child);
PermissionSet ps = new PermissionSet (PermissionState.None);
ps.FromXml (se);
}
[Test]
public void GetEnumerator ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
SecurityPermission sp = new SecurityPermission (SecurityPermissionFlag.Assertion);
ps.AddPermission (sp);
IEnumerator e = ps.GetEnumerator ();
AssertNotNull ("GetEnumerator", e);
int i=0;
while (e.MoveNext ()) {
Assert ("SecurityPermission", e.Current is SecurityPermission);
i++;
}
AssertEquals ("Count", 1, i);
}
#if NET_2_0
[Test]
public void GetHashCode_ ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
AssertEquals ("Empty", 0, ps.GetHashCode ());
SecurityPermission sp = new SecurityPermission (SecurityPermissionFlag.Assertion);
ps.AddPermission (sp);
Assert ("SecurityPermission", ps.GetHashCode () != 0);
PermissionSet copy = ps.Copy ();
Assert ("Copy", ps.GetHashCode () != copy.GetHashCode ());
}
#endif
[Test]
public void GetPermission_Null ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
AssertNull ("Empty", ps.GetPermission (null));
}
[Test]
public void GetPermission_None ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
AssertNull ("Empty", ps.GetPermission (typeof (SecurityPermission)));
}
[Test]
public void GetPermission_Unrestricted ()
{
PermissionSet ps = new PermissionSet (PermissionState.Unrestricted);
AssertNull ("Empty", ps.GetPermission (typeof (SecurityPermission)));
}
[Test]
public void GetPermission_Subclass ()
{
IsolatedStorageFilePermission isfp = new IsolatedStorageFilePermission (PermissionState.Unrestricted);
PermissionSet ps = new PermissionSet (PermissionState.None);
ps.AddPermission (isfp);
AssertNull ("Subclass", ps.GetPermission (typeof (IsolatedStoragePermission)));
}
private void Compare (string msg, PermissionSet ps, bool unrestricted, int count)
{
AssertNotNull (msg + "-NullCheck", ps);
Assert (msg + "-State", (ps.IsUnrestricted () == unrestricted));
AssertEquals (msg + "-Count", count, ps.Count);
}
[Test]
public void Intersect_Empty ()
{
PermissionSet ps1 = new PermissionSet (PermissionState.None);
PermissionSet ps2 = new PermissionSet (PermissionState.None);
AssertNull ("None N null", ps1.Intersect (null));
AssertNull ("None1 N None2", ps1.Intersect (ps2));
AssertNull ("None2 N None1", ps2.Intersect (ps1));
PermissionSet ups1 = new PermissionSet (PermissionState.Unrestricted);
AssertNull ("None1 N Unrestricted", ps1.Intersect (ups1));
AssertNull ("Unrestricted N None1", ups1.Intersect (ps1));
AssertNull ("Unrestricted N Null", ups1.Intersect (null));
PermissionSet ups2 = new PermissionSet (PermissionState.Unrestricted);
Compare ("ups1 N ups2", ups1.Intersect (ups2), true, 0);
Compare ("ups2 N ups1", ups2.Intersect (ups1), true, 0);
}
[Test]
public void Intersect_OnePermission ()
{
SecurityPermission sp = new SecurityPermission (SecurityPermissionFlag.Assertion);
PermissionSet ps1 = new PermissionSet (PermissionState.None);
ps1.AddPermission (sp);
PermissionSet ps2 = new PermissionSet (PermissionState.None);
AssertNull ("PS1 N null", ps1.Intersect (null));
AssertNull ("PS1 N None", ps1.Intersect (ps2));
AssertNull ("None N PS1", ps2.Intersect (ps1));
PermissionSet ps3 = ps1.Copy ();
Compare ("PS1 N PS3", ps1.Intersect (ps3), false, 1);
Compare ("PS3 N PS1", ps3.Intersect (ps1), false, 1);
PermissionSet ups1 = new PermissionSet (PermissionState.Unrestricted);
Compare ("PS1 N Unrestricted", ps1.Intersect (ups1), false, 1);
Compare ("Unrestricted N PS1", ups1.Intersect (ps1), false, 1);
}
[Test]
public void Intersect_OneNonIUnrestrictedPermission ()
{
ZoneIdentityPermission zip = new ZoneIdentityPermission (SecurityZone.MyComputer);
PermissionSet ps1 = new PermissionSet (PermissionState.None);
ps1.AddPermission (zip);
PermissionSet ps2 = new PermissionSet (PermissionState.None);
AssertNull ("PS1 N null", ps1.Intersect (null));
AssertNull ("PS1 N None", ps1.Intersect (ps2));
AssertNull ("None N PS1", ps2.Intersect (ps1));
PermissionSet ps3 = ps1.Copy ();
Compare ("PS1 N PS3", ps1.Intersect (ps3), false, 1);
Compare ("PS3 N PS1", ps3.Intersect (ps1), false, 1);
PermissionSet ups1 = new PermissionSet (PermissionState.Unrestricted);
ups1.AddPermission (zip);
Compare ("PS1 N Unrestricted", ps1.Intersect (ups1), false, 1);
Compare ("Unrestricted N PS1", ups1.Intersect (ps1), false, 1);
PermissionSet ups2 = new PermissionSet (PermissionState.Unrestricted);
Compare ("UPS1 N UPS2", ups1.Intersect (ups2), true, 0);
Compare ("UPS2 N UPS1", ups2.Intersect (ups1), true, 0);
ups2.AddPermission (zip);
#if NET_2_0
// Identity permissions aren't added to unrestricted permission sets in 2.0
Compare ("UPS1 N UPS2+ZIP", ups1.Intersect (ups2), true, 0);
Compare ("UPS2+ZIP N UPS1", ups2.Intersect (ups1), true, 0);
#else
Compare ("UPS1 N UPS2+ZIP", ups1.Intersect (ups2), true, 1);
Compare ("UPS2+ZIP N UPS1", ups2.Intersect (ups1), true, 1);
#endif
}
[Test]
public void IsEmpty_None ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
Assert ("Empty.IsEmpty", ps.IsEmpty ());
ps.AddPermission (new ZoneIdentityPermission (SecurityZone.NoZone));
AssertEquals ("Count==1", 1, ps.Count);
Assert ("Zip.IsEmpty", ps.IsEmpty ()); // yes empty!
}
[Test]
public void IsEmpty_Unrestricted ()
{
PermissionSet ps = new PermissionSet (PermissionState.Unrestricted);
Assert ("Unrestricted.IsEmpty", !ps.IsEmpty ());
ps.AddPermission (new ZoneIdentityPermission (SecurityZone.NoZone));
#if NET_2_0
// Identity permissions aren't added to unrestricted permission sets in 2.0
AssertEquals ("Count==0", 0, ps.Count);
#else
AssertEquals ("Count==1", 1, ps.Count);
#endif
Assert ("Zip.IsEmpty", !ps.IsEmpty ()); // yes empty!
}
[Test]
public void IsSubset_Empty ()
{
PermissionSet ps1 = new PermissionSet (PermissionState.None);
PermissionSet ps2 = new PermissionSet (PermissionState.None);
Assert ("None.IsSubsetOf(null)", ps1.IsSubsetOf (null));
Assert ("None1.IsSubsetOf(None2)", ps1.IsSubsetOf (ps2));
Assert ("None2.IsSubsetOf(None1)", ps2.IsSubsetOf (ps1));
PermissionSet ups1 = new PermissionSet (PermissionState.Unrestricted);
Assert ("None1.IsSubsetOf(Unrestricted)", ps1.IsSubsetOf (ups1));
Assert ("Unrestricted.IsSubsetOf(None1)", !ups1.IsSubsetOf (ps1));
Assert ("Unrestricted.IsSubsetOf(Null)", !ups1.IsSubsetOf (null));
PermissionSet ups2 = new PermissionSet (PermissionState.Unrestricted);
Assert ("ups1IsSubsetOf(ups2)", ups1.IsSubsetOf (ups2));
Assert ("ups2.IsSubsetOf(ups1)", ups2.IsSubsetOf (ups1));
}
[Test]
public void IsSubset_OnePermission ()
{
SecurityPermission sp = new SecurityPermission (SecurityPermissionFlag.Assertion);
PermissionSet ps1 = new PermissionSet (PermissionState.None);
ps1.AddPermission (sp);
PermissionSet ps2 = new PermissionSet (PermissionState.None);
Assert ("PS1.IsSubset(null)", !ps1.IsSubsetOf (null));
Assert ("PS1.IsSubset(None)", !ps1.IsSubsetOf (ps2));
Assert ("None.IsSubset(PS1)", ps2.IsSubsetOf (ps1));
PermissionSet ps3 = ps1.Copy ();
Assert ("PS1.IsSubset(PS3)", ps1.IsSubsetOf (ps3));
Assert ("PS3.IsSubset(PS1)", ps3.IsSubsetOf (ps1));
PermissionSet ups1 = new PermissionSet (PermissionState.Unrestricted);
Assert ("PS1.IsSubset(Unrestricted)", ps1.IsSubsetOf (ups1));
Assert ("Unrestricted.IsSubset(PS1)", !ups1.IsSubsetOf (ps1));
}
[Test]
public void IsSubset_OneNonIUnrestrictedPermission ()
{
ZoneIdentityPermission zip = new ZoneIdentityPermission (SecurityZone.MyComputer);
PermissionSet ps1 = new PermissionSet (PermissionState.None);
ps1.AddPermission (zip);
PermissionSet ps2 = new PermissionSet (PermissionState.None);
Assert ("PS1.IsSubset(null)", !ps1.IsSubsetOf (null));
Assert ("PS1.IsSubset(None)", !ps1.IsSubsetOf (ps2));
Assert ("None.IsSubset(PS1)", ps2.IsSubsetOf (ps1));
PermissionSet ps3 = ps1.Copy ();
Assert ("PS1.IsSubset(PS3)", ps1.IsSubsetOf (ps3));
Assert ("PS3.IsSubset(PS1)", ps3.IsSubsetOf (ps1));
PermissionSet ups1 = new PermissionSet (PermissionState.Unrestricted);
ups1.AddPermission (zip);
Assert ("PS1.IsSubset(Unrestricted)", ps1.IsSubsetOf (ups1));
Assert ("Unrestricted.IsSubset(PS1)", !ups1.IsSubsetOf (ps1));
PermissionSet ups2 = new PermissionSet (PermissionState.Unrestricted);
#if NET_2_0
// as ZoneIdentityPermission isn't added UPS1Z == UPS2
Assert ("UPS1Z.IsSubset(UPS2)", ups1.IsSubsetOf (ups2));
#else
Assert ("UPS1Z.IsSubset(UPS2)", !ups1.IsSubsetOf (ups2));
#endif
Assert ("UPS2.IsSubset(UPS1Z)", ups2.IsSubsetOf (ups1));
ups2.AddPermission (zip);
Assert ("UPS1Z.IsSubset(UPS2Z)", ups1.IsSubsetOf (ups2));
Assert ("UPS2Z.IsSubset(UPS1Z)", ups2.IsSubsetOf (ups1));
}
[Test]
public void RemovePermission_Null ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
AssertNull (ps.RemovePermission (null));
}
[Test]
public void RemovePermission_None ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
AssertNull ("Empty", ps.RemovePermission (typeof (SecurityPermission)));
SecurityPermission sp = new SecurityPermission (SecurityPermissionFlag.Assertion);
ps.AddPermission (sp);
SecurityPermission removed = (SecurityPermission) ps.RemovePermission (typeof (SecurityPermission));
AssertNotNull ("SecurityPermission", removed);
AssertEquals ("Flags", sp.Flags, removed.Flags);
AssertNull ("Empty-Again", ps.RemovePermission (typeof (SecurityPermission)));
}
[Test]
public void RemovePermission_Unrestricted ()
{
PermissionSet ps = new PermissionSet (PermissionState.Unrestricted);
AssertNull ("Empty", ps.RemovePermission (typeof (SecurityPermission)));
SecurityPermission sp = new SecurityPermission (SecurityPermissionFlag.Assertion);
ps.AddPermission (sp);
AssertNull ("SecurityPermissionn", ps.RemovePermission (typeof (SecurityPermission)));
ZoneIdentityPermission zip = new ZoneIdentityPermission (SecurityZone.MyComputer);
ps.AddPermission (zip);
ZoneIdentityPermission removed = (ZoneIdentityPermission)ps.RemovePermission (typeof (ZoneIdentityPermission));
#if NET_2_0
// identity permissions aren't added to unrestricted permission sets
// so they cannot be removed later (hence the null)
AssertNull ("ZoneIdentityPermission", removed);
#else
AssertNotNull ("ZoneIdentityPermission", removed);
#endif
}
[Test]
public void SetPermission_Null ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
AssertNull (ps.SetPermission (null));
}
[Test]
public void SetPermission_None ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
AssertEquals ("Empty", 0, ps.Count);
Assert ("State-None", !ps.IsUnrestricted ());
SecurityPermission sp = new SecurityPermission (PermissionState.Unrestricted);
SecurityPermission result = (SecurityPermission)ps.SetPermission (sp);
AssertEquals ("SecurityPermission", 1, ps.Count);
AssertEquals ("Flags", SecurityPermissionFlag.AllFlags, result.Flags);
Assert ("State-None-2", !ps.IsUnrestricted ());
sp = new SecurityPermission (SecurityPermissionFlag.ControlAppDomain);
result = (SecurityPermission)ps.SetPermission (sp);
AssertEquals ("SecurityPermission-2", 1, ps.Count);
AssertEquals ("Flags", SecurityPermissionFlag.ControlAppDomain, result.Flags);
ZoneIdentityPermission zip = new ZoneIdentityPermission (SecurityZone.MyComputer);
ZoneIdentityPermission zipr = (ZoneIdentityPermission) ps.SetPermission (zip);
AssertEquals ("ZoneIdentityPermission", 2, ps.Count);
AssertEquals ("SecurityZone", SecurityZone.MyComputer, zipr.SecurityZone);
zip = new ZoneIdentityPermission (SecurityZone.Intranet);
zipr = (ZoneIdentityPermission)ps.SetPermission (zip);
AssertEquals ("ZoneIdentityPermission", 2, ps.Count);
AssertEquals ("SecurityZone", SecurityZone.Intranet, zipr.SecurityZone);
}
[Test]
public void SetPermission_Unrestricted ()
{
SecurityPermission sp = new SecurityPermission (PermissionState.Unrestricted);
PermissionSet ps = new PermissionSet (PermissionState.Unrestricted);
AssertEquals ("Empty", 0, ps.Count);
Assert ("State-Unrestricted", ps.IsUnrestricted ());
ZoneIdentityPermission zip = new ZoneIdentityPermission (SecurityZone.MyComputer);
ZoneIdentityPermission zipr = (ZoneIdentityPermission)ps.SetPermission (zip);
AssertEquals ("ZoneIdentityPermission", 1, ps.Count);
AssertEquals ("SecurityZone", SecurityZone.MyComputer, zipr.SecurityZone);
#if NET_2_0
// Adding a non unrestricted identity permission now results in
// a permission set loosing it's unrestricted status
Assert ("State-Unrestricted-2", !ps.IsUnrestricted ());
#else
Assert ("State-Unrestricted-2", ps.IsUnrestricted ());
#endif
zip = new ZoneIdentityPermission (SecurityZone.Intranet);
zipr = (ZoneIdentityPermission)ps.SetPermission (zip);
AssertEquals ("ZoneIdentityPermission-2", 1, ps.Count);
AssertEquals ("SecurityZone-2", SecurityZone.Intranet, zipr.SecurityZone);
SecurityPermission result = (SecurityPermission)ps.SetPermission (sp);
AssertEquals ("SecurityPermission", 2, ps.Count);
AssertEquals ("Flags", SecurityPermissionFlag.AllFlags, result.Flags);
Assert ("State-None", !ps.IsUnrestricted ());
sp = new SecurityPermission (SecurityPermissionFlag.ControlAppDomain);
result = (SecurityPermission)ps.SetPermission (sp);
AssertEquals ("SecurityPermission-2", 2, ps.Count);
AssertEquals ("Flags-2", SecurityPermissionFlag.ControlAppDomain, result.Flags);
}
[Test]
public void ToXmlNone ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
SecurityElement se = ps.ToXml ();
Assert ("None.ToString().StartsWith", ps.ToString().StartsWith ("<PermissionSet"));
AssertEquals ("None.class", "System.Security.PermissionSet", (se.Attributes ["class"] as string));
AssertEquals ("None.version", "1", (se.Attributes ["version"] as string));
AssertNull ("None.Unrestricted", (se.Attributes ["Unrestricted"] as string));
}
[Test]
public void ToXmlUnrestricted ()
{
PermissionSet ps = new PermissionSet (PermissionState.Unrestricted);
SecurityElement se = ps.ToXml ();
Assert ("Unrestricted.ToString().StartsWith", ps.ToString().StartsWith ("<PermissionSet"));
AssertEquals ("Unrestricted.class", "System.Security.PermissionSet", (se.Attributes ["class"] as string));
AssertEquals ("Unrestricted.version", "1", (se.Attributes ["version"] as string));
AssertEquals ("Unrestricted.Unrestricted", "true", (se.Attributes ["Unrestricted"] as string));
}
[Test]
public void Union_Empty ()
{
PermissionSet ps1 = new PermissionSet (PermissionState.None);
PermissionSet ps2 = new PermissionSet (PermissionState.None);
Compare ("None U null", ps1.Union (null), false, 0);
Compare ("None1 U None2", ps1.Union (ps2), false, 0);
Compare ("None2 U None1", ps2.Union (ps1), false, 0);
PermissionSet ups1 = new PermissionSet (PermissionState.Unrestricted);
Compare ("None1 U Unrestricted", ps1.Union (ups1), true, 0);
Compare ("Unrestricted U None1", ups1.Union (ps1), true, 0);
Compare ("Unrestricted U Null", ups1.Union (null), true, 0);
PermissionSet ups2 = new PermissionSet (PermissionState.Unrestricted);
Compare ("ups1 U ups2", ups1.Union (ups2), true, 0);
Compare ("ups2 U ups1", ups2.Union (ups1), true, 0);
}
[Test]
public void Union_OnePermission ()
{
SecurityPermission sp = new SecurityPermission (SecurityPermissionFlag.Assertion);
PermissionSet ps1 = new PermissionSet (PermissionState.None);
ps1.AddPermission (sp);
PermissionSet ps2 = new PermissionSet (PermissionState.None);
Compare ("PS1 U null", ps1.Union (null), false, 1);
Compare ("PS1 U None", ps1.Union (ps2), false, 1);
Compare ("None U PS1", ps2.Union (ps1), false, 1);
PermissionSet ps3 = ps1.Copy ();
Compare ("PS1 U PS3", ps1.Union (ps3), false, 1);
Compare ("PS3 U PS1", ps3.Union (ps1), false, 1);
PermissionSet ups1 = new PermissionSet (PermissionState.Unrestricted);
Compare ("PS1 U Unrestricted", ps1.Union (ups1), true, 0);
Compare ("Unrestricted U PS1", ups1.Union (ps1), true, 0);
}
[Test]
public void Union_OneNonIUnrestrictedPermission ()
{
ZoneIdentityPermission zip = new ZoneIdentityPermission (SecurityZone.MyComputer);
PermissionSet ps1 = new PermissionSet (PermissionState.None);
ps1.AddPermission (zip);
PermissionSet ps2 = new PermissionSet (PermissionState.None);
Compare ("PS1 U null", ps1.Union (null), false, 1);
Compare ("PS1 U None", ps1.Union (ps2), false, 1);
Compare ("None U PS1", ps2.Union (ps1), false, 1);
PermissionSet ps3 = ps1.Copy ();
Compare ("PS1 U PS3", ps1.Union (ps3), false, 1);
Compare ("PS3 U PS1", ps3.Union (ps1), false, 1);
PermissionSet ups1 = new PermissionSet (PermissionState.Unrestricted);
ups1.AddPermission (zip);
#if NET_2_0
// Identity permissions aren't added to unrestricted permission sets in 2.0
Compare ("PS1 U Unrestricted", ps1.Union (ups1), true, 0);
Compare ("Unrestricted U PS1", ups1.Union (ps1), true, 0);
PermissionSet ups2 = new PermissionSet (PermissionState.Unrestricted);
Compare ("UPS1 U UPS2", ups1.Union (ups1), true, 0);
Compare ("UPS2 U UPS1", ups2.Union (ups1), true, 0);
ups2.AddPermission (zip);
Compare ("UPS1 U UPS2+ZIP", ups1.Union (ups2), true, 0);
Compare ("UPS2+ZIP U UPS1", ups2.Union (ups1), true, 0);
#else
Compare ("PS1 U Unrestricted", ps1.Union (ups1), true, 1);
Compare ("Unrestricted U PS1", ups1.Union (ps1), true, 1);
PermissionSet ups2 = new PermissionSet (PermissionState.Unrestricted);
Compare ("UPS1 U UPS2", ups1.Union (ups1), true, 1);
Compare ("UPS2 U UPS1", ups2.Union (ups1), true, 1);
ups2.AddPermission (zip);
Compare ("UPS1 U UPS2+ZIP", ups1.Union (ups2), true, 1);
Compare ("UPS2+ZIP U UPS1", ups2.Union (ups1), true, 1);
#endif
}
#if NET_2_0
[Test]
[Category ("NotWorking")] // requires imperative stack modifiers
[ExpectedException (typeof (ExecutionEngineException))]
public void RevertAssert_WithoutAssertion ()
{
PermissionSet.RevertAssert ();
}
[Test]
[Category ("NotWorking")] // requires imperative stack modifiers
public void RevertAssert_WithAssertion ()
{
PermissionSet ups = new PermissionSet (PermissionState.Unrestricted);
ups.Assert ();
PermissionSet.RevertAssert ();
}
#endif
[Test]
public void Assert_NonCasPermission ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
ps.AddPermission (new PrincipalPermission (PermissionState.None));
Assert ("ContainsNonCodeAccessPermissions", ps.ContainsNonCodeAccessPermissions ());
AssertEquals ("Count", 1, ps.Count);
ps.Assert ();
// it's simply ignored
}
[Test]
public void Deny_NonCasPermission ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
ps.AddPermission (new PrincipalPermission (PermissionState.None));
Assert ("ContainsNonCodeAccessPermissions", ps.ContainsNonCodeAccessPermissions ());
AssertEquals ("Count", 1, ps.Count);
ps.Deny ();
// it's simply ignored
}
[Test]
public void PermitOnly_NonCasPermission ()
{
PermissionSet ps = new PermissionSet (PermissionState.None);
ps.AddPermission (new PrincipalPermission (PermissionState.None));
Assert ("ContainsNonCodeAccessPermissions", ps.ContainsNonCodeAccessPermissions ());
AssertEquals ("Count", 1, ps.Count);
ps.PermitOnly ();
// it's simply ignored
}
// note: this only ensure that the ECMA key support unification (more test required, outside corlib, for other keys, like MS final).
private const string PermissionPattern = "<PermissionSet class=\"System.Security.PermissionSet\" version=\"1\"><IPermission class=\"System.Security.Permissions.FileDialogPermission, mscorlib, Version={0}, Culture=neutral, PublicKeyToken=b77a5c561934e089\" version=\"1\" Access=\"Open\"/></PermissionSet>";
private const string fx10version = "1.0.3300.0";
private const string fx11version = "1.0.5000.0";
private const string fx20version = "2.0.0.0";
private void Unification (string xml)
{
PermissionSetAttribute psa = new PermissionSetAttribute (SecurityAction.Assert);
psa.XML = xml;
string pset = psa.CreatePermissionSet ().ToString ();
string currentVersion = typeof (string).Assembly.GetName ().Version.ToString ();
Assert (currentVersion, pset.IndexOf (currentVersion) > 0);
}
[Test]
public void Unification_FromFx10 ()
{
Unification (String.Format (PermissionPattern, fx10version));
}
[Test]
public void Unification_FromFx11 ()
{
Unification (String.Format (PermissionPattern, fx11version));
}
[Test]
public void Unification_FromFx20 ()
{
Unification (String.Format (PermissionPattern, fx20version));
}
[Test]
public void Unification_FromFx99 ()
{
Unification (String.Format (PermissionPattern, "9.99.999.9999"));
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the PnRelNomencladorXDatoReportable class.
/// </summary>
[Serializable]
public partial class PnRelNomencladorXDatoReportableCollection : ActiveList<PnRelNomencladorXDatoReportable, PnRelNomencladorXDatoReportableCollection>
{
public PnRelNomencladorXDatoReportableCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnRelNomencladorXDatoReportableCollection</returns>
public PnRelNomencladorXDatoReportableCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnRelNomencladorXDatoReportable o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the PN_Rel_NomencladorXDatoReportable table.
/// </summary>
[Serializable]
public partial class PnRelNomencladorXDatoReportable : ActiveRecord<PnRelNomencladorXDatoReportable>, IActiveRecord
{
#region .ctors and Default Settings
public PnRelNomencladorXDatoReportable()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnRelNomencladorXDatoReportable(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnRelNomencladorXDatoReportable(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnRelNomencladorXDatoReportable(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("PN_Rel_NomencladorXDatoReportable", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdNomencladorXDatoReportable = new TableSchema.TableColumn(schema);
colvarIdNomencladorXDatoReportable.ColumnName = "idNomencladorXDatoReportable";
colvarIdNomencladorXDatoReportable.DataType = DbType.Int32;
colvarIdNomencladorXDatoReportable.MaxLength = 0;
colvarIdNomencladorXDatoReportable.AutoIncrement = true;
colvarIdNomencladorXDatoReportable.IsNullable = false;
colvarIdNomencladorXDatoReportable.IsPrimaryKey = true;
colvarIdNomencladorXDatoReportable.IsForeignKey = false;
colvarIdNomencladorXDatoReportable.IsReadOnly = false;
colvarIdNomencladorXDatoReportable.DefaultSetting = @"";
colvarIdNomencladorXDatoReportable.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdNomencladorXDatoReportable);
TableSchema.TableColumn colvarIdNomenclador = new TableSchema.TableColumn(schema);
colvarIdNomenclador.ColumnName = "idNomenclador";
colvarIdNomenclador.DataType = DbType.Int32;
colvarIdNomenclador.MaxLength = 0;
colvarIdNomenclador.AutoIncrement = false;
colvarIdNomenclador.IsNullable = true;
colvarIdNomenclador.IsPrimaryKey = false;
colvarIdNomenclador.IsForeignKey = true;
colvarIdNomenclador.IsReadOnly = false;
colvarIdNomenclador.DefaultSetting = @"";
colvarIdNomenclador.ForeignKeyTableName = "PN_nomenclador";
schema.Columns.Add(colvarIdNomenclador);
TableSchema.TableColumn colvarIdDatoReportable = new TableSchema.TableColumn(schema);
colvarIdDatoReportable.ColumnName = "idDatoReportable";
colvarIdDatoReportable.DataType = DbType.Int32;
colvarIdDatoReportable.MaxLength = 0;
colvarIdDatoReportable.AutoIncrement = false;
colvarIdDatoReportable.IsNullable = true;
colvarIdDatoReportable.IsPrimaryKey = false;
colvarIdDatoReportable.IsForeignKey = true;
colvarIdDatoReportable.IsReadOnly = false;
colvarIdDatoReportable.DefaultSetting = @"";
colvarIdDatoReportable.ForeignKeyTableName = "PN_datos_reportables";
schema.Columns.Add(colvarIdDatoReportable);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_Rel_NomencladorXDatoReportable",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdNomencladorXDatoReportable")]
[Bindable(true)]
public int IdNomencladorXDatoReportable
{
get { return GetColumnValue<int>(Columns.IdNomencladorXDatoReportable); }
set { SetColumnValue(Columns.IdNomencladorXDatoReportable, value); }
}
[XmlAttribute("IdNomenclador")]
[Bindable(true)]
public int? IdNomenclador
{
get { return GetColumnValue<int?>(Columns.IdNomenclador); }
set { SetColumnValue(Columns.IdNomenclador, value); }
}
[XmlAttribute("IdDatoReportable")]
[Bindable(true)]
public int? IdDatoReportable
{
get { return GetColumnValue<int?>(Columns.IdDatoReportable); }
set { SetColumnValue(Columns.IdDatoReportable, value); }
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a PnNomenclador ActiveRecord object related to this PnRelNomencladorXDatoReportable
///
/// </summary>
public DalSic.PnNomenclador PnNomenclador
{
get { return DalSic.PnNomenclador.FetchByID(this.IdNomenclador); }
set { SetColumnValue("idNomenclador", value.IdNomenclador); }
}
/// <summary>
/// Returns a PnDatosReportable ActiveRecord object related to this PnRelNomencladorXDatoReportable
///
/// </summary>
public DalSic.PnDatosReportable PnDatosReportable
{
get { return DalSic.PnDatosReportable.FetchByID(this.IdDatoReportable); }
set { SetColumnValue("idDatoReportable", value.IdDatoReportable); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int? varIdNomenclador,int? varIdDatoReportable)
{
PnRelNomencladorXDatoReportable item = new PnRelNomencladorXDatoReportable();
item.IdNomenclador = varIdNomenclador;
item.IdDatoReportable = varIdDatoReportable;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdNomencladorXDatoReportable,int? varIdNomenclador,int? varIdDatoReportable)
{
PnRelNomencladorXDatoReportable item = new PnRelNomencladorXDatoReportable();
item.IdNomencladorXDatoReportable = varIdNomencladorXDatoReportable;
item.IdNomenclador = varIdNomenclador;
item.IdDatoReportable = varIdDatoReportable;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdNomencladorXDatoReportableColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdNomencladorColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdDatoReportableColumn
{
get { return Schema.Columns[2]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdNomencladorXDatoReportable = @"idNomencladorXDatoReportable";
public static string IdNomenclador = @"idNomenclador";
public static string IdDatoReportable = @"idDatoReportable";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#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;
public struct VT
{
public short[,] short2darr;
public short[, ,] short3darr;
public short[,] short2darr_b;
public short[, ,] short3darr_b;
}
public class CL
{
public short[,] short2darr = { { 0, 1 }, { 0, 0 } };
public short[, ,] short3darr = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } };
public short[,] short2darr_b = { { 0, 49 }, { 0, 0 } };
public short[, ,] short3darr_b = { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } };
}
public class shortMDArrTest
{
static short[,] short2darr = { { 0, 1 }, { 0, 0 } };
static short[, ,] short3darr = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } };
static short[,] short2darr_b = { { 0, 49 }, { 0, 0 } };
static short[, ,] short3darr_b = { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } };
static short[][,] ja1 = new short[2][,];
static short[][, ,] ja2 = new short[2][, ,];
static short[][,] ja1_b = new short[2][,];
static short[][, ,] ja2_b = new short[2][, ,];
public static int Main()
{
bool pass = true;
VT vt1;
vt1.short2darr = new short[,] { { 0, 1 }, { 0, 0 } };
vt1.short3darr = new short[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } };
vt1.short2darr_b = new short[,] { { 0, 49 }, { 0, 0 } };
vt1.short3darr_b = new short[,,] { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } };
CL cl1 = new CL();
ja1[0] = new short[,] { { 0, 1 }, { 0, 0 } };
ja2[1] = new short[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } };
ja1_b[0] = new short[,] { { 0, 49 }, { 0, 0 } };
ja2_b[1] = new short[,,] { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } };
short result = 1;
// 2D
if (result != short2darr[0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != vt1.short2darr[0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != cl1.short2darr[0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != ja1[0][0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (result != short3darr[1, 0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != vt1.short3darr[1, 0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != cl1.short3darr[1, 0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != ja2[1][1, 0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int64ToBool
bool Bool_result = true;
// 2D
if (Bool_result != Convert.ToBoolean(short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(vt1.short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(cl1.short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Bool_result != Convert.ToBoolean(short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(vt1.short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(cl1.short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int16ToByte tests
byte Byte_result = 1;
// 2D
if (Byte_result != Convert.ToByte(short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(vt1.short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(cl1.short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Byte_result != Convert.ToByte(short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(vt1.short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(cl1.short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int16ToDecimal tests
decimal Decimal_result = 1;
// 2D
if (Decimal_result != Convert.ToDecimal(short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(vt1.short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(cl1.short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Decimal_result != Convert.ToDecimal(short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(vt1.short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(cl1.short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int16ToDouble
double Double_result = 1;
// 2D
if (Double_result != Convert.ToDouble(short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(vt1.short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(cl1.short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Double_result != Convert.ToDouble(short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(vt1.short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(cl1.short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int16ToSingle
float Single_result = 1;
// 2D
if (Single_result != Convert.ToSingle(short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(vt1.short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(cl1.short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Single_result != Convert.ToSingle(short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(vt1.short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(cl1.short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int16ToInt32 tests
int Int32_result = 1;
// 2D
if (Int32_result != Convert.ToInt32(short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(vt1.short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(cl1.short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Int32_result != Convert.ToInt32(short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(vt1.short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(cl1.short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int16ToInt64 tests
long Int64_result = 1;
// 2D
if (Int64_result != Convert.ToInt64(short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(vt1.short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(cl1.short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Int64_result != Convert.ToInt64(short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(vt1.short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(cl1.short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int16ToSByte
sbyte SByte_result = 1;
// 2D
if (SByte_result != Convert.ToSByte(short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(vt1.short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(cl1.short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (SByte_result != Convert.ToSByte(short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(vt1.short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(cl1.short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int16ToUInt32
uint UInt32_result = 1;
// 2D
if (UInt32_result != Convert.ToUInt32(short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(vt1.short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(cl1.short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (UInt32_result != Convert.ToUInt32(short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(vt1.short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(cl1.short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int16ToUInt64 tests
ulong UInt64_result = 1;
// 2D
if (UInt64_result != Convert.ToUInt64(short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(vt1.short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(cl1.short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (UInt64_result != Convert.ToUInt64(short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(vt1.short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(cl1.short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int16ToUInt16 tests
ushort UInt16_result = 1;
// 2D
if (UInt16_result != Convert.ToUInt16(short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("2darr[0, 1] is: {0}", short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(vt1.short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("vt1.short2darr[0, 1] is: {0}", vt1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(cl1.short2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("cl1.short2darr[0, 1] is: {0}", cl1.short2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (UInt16_result != Convert.ToUInt16(short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("short3darr[1,0,1] is: {0}", short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(vt1.short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("vt1.short3darr[1,0,1] is: {0}", vt1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(cl1.short3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("cl1.short3darr[1,0,1] is: {0}", cl1.short3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int16ToChar tests
char Char_result = '1';
// 2D
if (Char_result != Convert.ToChar(short2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("2darr[0, 1] is: {0}", short2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(vt1.short2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("vt1.short2darr_b[0, 1] is: {0}", vt1.short2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(cl1.short2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("cl1.short2darr_b[0, 1] is: {0}", cl1.short2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(ja1_b[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Char_result != Convert.ToChar(short3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("short3darr_b[1,0,1] is: {0}", short3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(vt1.short3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("vt1.short3darr_b[1,0,1] is: {0}", vt1.short3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(cl1.short3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("cl1.short3darr_b[1,0,1] is: {0}", cl1.short3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(ja2_b[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (!pass)
{
Console.WriteLine("FAILED");
return 1;
}
else
{
Console.WriteLine("PASSED");
return 100;
}
}
};
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Signum.Entities;
using System.Linq.Expressions;
using Signum.Utilities;
using Microsoft.SqlServer.Types;
using Microsoft.SqlServer.Server;
using Signum.Engine;
using Signum.Engine.Maps;
namespace Signum.Test.Environment
{
[Serializable, EntityKind(EntityKind.Shared, EntityData.Transactional), Mixin(typeof(CorruptMixin)),
Mixin(typeof(ColaboratorsMixin)), PrimaryKey(typeof(Guid))]
public class NoteWithDateEntity : Entity
{
[ForceNullable]
[StringLengthValidator(Min = 3, MultiLine = true)]
public string Text { get; set; }
[ForceNullable]
[ImplementedByAll]
public IEntity Target { get; set; }
[ImplementedByAll]
public Lite<IEntity>? OtherTarget { get; set; }
public DateTime CreationTime { get; set; }
public Date CreationDate { get; set; }
public override string ToString()
{
return "{0} -> {1}".FormatWith(CreationTime, Text);
}
}
[Serializable] // Just a pattern
public class ColaboratorsMixin : MixinEntity
{
ColaboratorsMixin(ModifiableEntity mainEntity, MixinEntity next) : base(mainEntity, next) { }
[NoRepeatValidator]
public MList<ArtistEntity> Colaborators { get; set; } = new MList<ArtistEntity>();
}
[AutoInit]
public static class NoteWithDateOperation
{
public static ExecuteSymbol<NoteWithDateEntity> Save;
}
[DescriptionOptions(DescriptionOptions.All)]
public interface IAuthorEntity : IEntity
{
string Name { get; }
AwardEntity? LastAward { get; }
string FullName { get; }
bool Lonely();
}
[Serializable, EntityKind(EntityKind.Shared, EntityData.Transactional)]
public class ArtistEntity : Entity, IAuthorEntity
{
[StringLengthValidator(Min = 3, Max = 100)]
public string Name { get; set; }
public bool Dead { get; set; }
public Sex Sex { get; set; }
public Status? Status { get; set; }
[AutoExpressionField]
public bool IsMale => As.Expression(() => Sex == Sex.Male);
[ImplementedByAll]
public AwardEntity? LastAward { get; set; }
[AutoExpressionField]
public IEnumerable<Lite<Entity>> FriendsCovariant() => As.Expression(() => (IEnumerable<Lite<Entity>>)Friends);
public MList<Lite<ArtistEntity>> Friends { get; set; } = new MList<Lite<ArtistEntity>>();
[Ignore]
[NoRepeatValidator]
public MList<AwardNominationEntity> Nominations { get; set; } = new MList<AwardNominationEntity>();
[AutoExpressionField]
public string FullName => As.Expression(() => Name + (Dead ? " Dead" : "") + (IsMale ? " Male" : " Female"));
[AutoExpressionField]
public bool Lonely() => As.Expression(() => !Friends.Any());
[AutoExpressionField]
public override string ToString() => As.Expression(() => Name);
}
[AutoInit]
public static class ArtistOperation
{
public static ExecuteSymbol<ArtistEntity> Save;
public static ExecuteSymbol<ArtistEntity> AssignPersonalAward;
}
[Flags]
public enum Sex : short
{
Male,
Female,
Undefined
}
public static class SexExtensions
{
[AutoExpressionField]
public static bool IsDefined(this Sex s) => As.Expression(() => s == Sex.Male || s == Sex.Female);
}
public enum Status
{
Single,
Married,
}
[Serializable, EntityKind(EntityKind.Main, EntityData.Transactional)]
public class BandEntity : Entity, IAuthorEntity
{
[UniqueIndex]
[StringLengthValidator(Min = 3, Max = 100)]
public string Name { get; set; }
public MList<ArtistEntity> Members { get; set; } = new MList<ArtistEntity>();
[ImplementedBy(typeof(GrammyAwardEntity), typeof(AmericanMusicAwardEntity))]
public AwardEntity? LastAward { get; set; }
[ImplementedBy(typeof(GrammyAwardEntity), typeof(AmericanMusicAwardEntity))]
public MList<AwardEntity> OtherAwards { get; set; } = new MList<AwardEntity>();
[AutoExpressionField]
public string FullName => As.Expression(() => Name + " (" + Members.Count + " members)");
[AutoExpressionField]
public bool Lonely() => As.Expression(() => !Members.Any());
[AutoExpressionField]
public override string ToString() => As.Expression(() => Name);
}
[AutoInit]
public static class BandOperation
{
public static ExecuteSymbol<BandEntity> Save;
}
[Serializable, EntityKind(EntityKind.Shared, EntityData.Transactional), PrimaryKey(typeof(long))]
public abstract class AwardEntity : Entity
{
public int Year { get; set; }
[StringLengthValidator(Min = 3, Max = 100)]
public string Category { get; set; }
public AwardResult Result { get; set; }
}
[AutoInit]
public static class AwardOperation
{
public static ExecuteSymbol<AwardEntity> Save;
}
public enum AwardResult
{
Won,
Nominated
}
[Serializable]
public class GrammyAwardEntity : AwardEntity
{
}
[Serializable]
public class AmericanMusicAwardEntity : AwardEntity
{
}
[Serializable]
public class PersonalAwardEntity : AwardEntity
{
}
[Serializable, EntityKind(EntityKind.Main, EntityData.Master)]
public class LabelEntity : Entity
{
[UniqueIndex]
[StringLengthValidator(Min = 3, Max = 100)]
public string Name { get; set; }
public CountryEntity Country { get; set; }
public Lite<LabelEntity>? Owner { get; set; }
[UniqueIndex]
public SqlHierarchyId Node { get; set; }
[AutoExpressionField]
public override string ToString() => As.Expression(() => Name);
}
[AutoInit]
public static class LabelOperation
{
public static ExecuteSymbol<LabelEntity> Save;
}
[Serializable, EntityKind(EntityKind.SystemString, EntityData.Master)]
public class CountryEntity : Entity
{
[UniqueIndex]
[StringLengthValidator(Min = 3, Max = 100)]
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
[Serializable, EntityKind(EntityKind.Main, EntityData.Transactional)]
public class AlbumEntity : Entity, ISecretContainer
{
[UniqueIndex]
[StringLengthValidator(Min = 3, Max = 100)]
public string Name { get; set; }
[NumberBetweenValidator(1900, 2100)]
public int Year { get; set; }
[ImplementedBy(typeof(ArtistEntity), typeof(BandEntity))]
public IAuthorEntity Author { get; set; }
[PreserveOrder]
public MList<SongEmbedded> Songs { get; set; } = new MList<SongEmbedded>();
public SongEmbedded? BonusTrack { get; set; }
[ForceNullable]
public LabelEntity Label { get; set; }
public AlbumState State { get; set; }
string? ISecretContainer.Secret { get; set; }
[AutoExpressionField]
public override string ToString() => As.Expression(() => Name);
}
public interface ISecretContainer
{
string? Secret { get; set; }
}
public enum AlbumState
{
[Ignore]
New,
Saved
}
[AutoInit]
public static class AlbumOperation
{
public static ExecuteSymbol<AlbumEntity> Save;
public static ExecuteSymbol<AlbumEntity> Modify;
public static ConstructSymbol<AlbumEntity>.From<BandEntity> CreateAlbumFromBand;
public static DeleteSymbol<AlbumEntity> Delete;
public static ConstructSymbol<AlbumEntity>.From<AlbumEntity> Clone;
public static ConstructSymbol<AlbumEntity>.FromMany<AlbumEntity> CreateGreatestHitsAlbum;
public static ConstructSymbol<AlbumEntity>.FromMany<AlbumEntity> CreateEmptyGreatestHitsAlbum;
}
[Serializable]
public class SongEmbedded : EmbeddedEntity
{
[StringLengthValidator(Min = 3, Max = 100)]
public string Name { get; set; }
TimeSpan? duration;
public TimeSpan? Duration
{
get { return duration; }
set
{
if (Set(ref duration, value))
Seconds = duration == null ? null : (int?)duration.Value.TotalSeconds;
}
}
public int? Seconds { get; set; }
public int Index { get; set; }
[AutoExpressionField]
public override string ToString() => As.Expression(() => Name);
}
[Serializable, EntityKind(EntityKind.System, EntityData.Transactional)]
public class AwardNominationEntity : Entity, ICanBeOrdered
{
[NotNullValidator(Disabled = true)]
[ImplementedBy(typeof(ArtistEntity), typeof(BandEntity))]
public Lite<IAuthorEntity> Author { get; set; }
[ForceNullable]
[ImplementedBy(typeof(GrammyAwardEntity), typeof(PersonalAwardEntity), typeof(AmericanMusicAwardEntity)), NotNullValidator(Disabled = true)]
public Lite<AwardEntity> Award { get; set; }
public int Year { get; set; }
public int Order { get; set; }
[PreserveOrder]
[NoRepeatValidator]
public MList<NominationPointEmbedded> Points { get; set; } = new MList<NominationPointEmbedded>();
}
[Serializable]
public class NominationPointEmbedded : EmbeddedEntity
{
public int Point { get; set; }
}
[Serializable, EntityKind(EntityKind.Main, EntityData.Transactional)]
public class ConfigEntity : Entity
{
public EmbeddedConfigEmbedded? EmbeddedConfig { get; set; }
}
[AutoInit]
public static class ConfigOperation
{
public static ExecuteSymbol<ConfigEntity> Save;
}
public class EmbeddedConfigEmbedded : EmbeddedEntity
{
public Lite<LabelEntity>? DefaultLabel { get; set; }
[NoRepeatValidator]
public MList<Lite<GrammyAwardEntity>> Awards { get; set; } = new MList<Lite<GrammyAwardEntity>>();
}
public static class MinimumExtensions
{
[SqlMethod(Name = "MinimumTableValued")]
public static IQueryable<IntValue> MinimumTableValued(int? a, int? b)
{
throw new InvalidOperationException("sql only");
}
[SqlMethod(Name = "MinimumScalar")]
public static int? MinimumScalar(int? a, int? b)
{
throw new InvalidOperationException("sql only");
}
internal static void IncludeFunction(SchemaAssets assets)
{
if (Schema.Current.Settings.IsPostgres)
{
assets.IncludeUserDefinedFunction("MinimumTableValued", @"(p1 integer, p2 integer)
RETURNS TABLE(""MinValue"" integer)
AS $$
BEGIN
RETURN QUERY
SELECT Case When p1 < p2 Then p1
Else COALESCE(p2, p1) End as MinValue;
END
$$ LANGUAGE plpgsql;");
assets.IncludeUserDefinedFunction("MinimumScalar", @"(p1 integer, p2 integer)
RETURNS integer
AS $$
BEGIN
RETURN (Case When p1 < p2 Then p1
Else COALESCE(p2, p1) End);
END
$$ LANGUAGE plpgsql;");
}
else
{
assets.IncludeUserDefinedFunction("MinimumTableValued", @"(@Param1 Integer, @Param2 Integer)
RETURNS Table As
RETURN (SELECT Case When @Param1 < @Param2 Then @Param1
Else COALESCE(@Param2, @Param1) End MinValue)");
assets.IncludeUserDefinedFunction("MinimumScalar", @"(@Param1 Integer, @Param2 Integer)
RETURNS Integer
AS
BEGIN
RETURN (Case When @Param1 < @Param2 Then @Param1
Else COALESCE(@Param2, @Param1) End);
END");
}
}
}
public class IntValue : IView
{
public int? MinValue;
}
[Serializable, EntityKind(EntityKind.System, EntityData.Transactional)]
public class FolderEntity : Entity
{
[UniqueIndex]
[StringLengthValidator(Max = 100)]
public string Name { get; set; }
public Lite<FolderEntity>? Parent { get; set; }
[AutoExpressionField]
public override string ToString() => As.Expression(() => Name);
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="SerializationPolicies.cs" company="Sirenix IVS">
// Copyright (c) 2018 Sirenix IVS
//
// 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 Stratus.OdinSerializer
{
using Utilities;
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using UnityEngine;
/// <summary>
/// Contains a set of default implementations of the <see cref="ISerializationPolicy"/> interface.
/// <para />
/// NOTE: Policies are not necessarily compatible with each other in intuitive ways.
/// Data serialized with the <see cref="SerializationPolicies.Everything"/> policy
/// will for example fail to deserialize auto-properties with <see cref="SerializationPolicies.Strict"/>,
/// even if only strict data is needed.
/// It is best to ensure that you always use the same policy for serialization and deserialization.
/// <para />
/// This class and all of its policies are thread-safe.
/// </summary>
public static class SerializationPolicies
{
private static readonly object LOCK = new object();
private static volatile ISerializationPolicy everythingPolicy;
private static volatile ISerializationPolicy unityPolicy;
private static volatile ISerializationPolicy strictPolicy;
/// <summary>
/// Tries to get a serialization policy by its id, in case a serialization graph has the policy used for serialization stored by name.
/// </summary>
public static bool TryGetByID(string name, out ISerializationPolicy policy)
{
switch (name)
{
case "OdinSerializerPolicies.Everything":
policy = SerializationPolicies.Everything;
break;
case "OdinSerializerPolicies.Unity":
policy = SerializationPolicies.Unity;
break;
case "OdinSerializerPolicies.Strict":
policy = SerializationPolicies.Strict;
break;
default:
policy = null;
break;
}
return policy != null;
}
/// <summary>
/// All fields not marked with <see cref="NonSerializedAttribute"/> are serialized. If a field is marked with both <see cref="NonSerializedAttribute"/> and <see cref="OdinSerializeAttribute"/>, then the field will be serialized.
/// </summary>
public static ISerializationPolicy Everything
{
get
{
if (everythingPolicy == null)
{
lock (LOCK)
{
if (everythingPolicy == null)
{
everythingPolicy = new CustomSerializationPolicy("OdinSerializerPolicies.Everything", true, (member) =>
{
if (!(member is FieldInfo))
{
return false;
}
if (member.IsDefined<OdinSerializeAttribute>(true))
{
return true;
}
return !member.IsDefined<NonSerializedAttribute>(true);
});
}
}
}
return everythingPolicy;
}
}
/// <summary>
/// Public fields, as well as fields or auto-properties marked with <see cref="SerializeField"/> or <see cref="OdinSerializeAttribute"/> and not marked with <see cref="NonSerializedAttribute"/>, are serialized.
/// <para />
/// There are two exceptions:
/// <para/>1) All fields in tuples, as well as in private nested types marked as compiler generated (e.g. lambda capture classes) are also serialized.
/// <para/>2) Virtual auto-properties are never serialized. Note that properties specified by an implemented interface are automatically marked virtual by the compiler.
/// </summary>
public static ISerializationPolicy Unity
{
get
{
if (unityPolicy == null)
{
lock (LOCK)
{
if (unityPolicy == null)
{
// In Unity 2017.1's .NET 4.6 profile, Tuples implement System.ITuple. In Unity 2017.2 and up, tuples implement System.ITupleInternal instead for some reason.
Type tupleInterface = typeof(string).Assembly.GetType("System.ITuple") ?? typeof(string).Assembly.GetType("System.ITupleInternal");
unityPolicy = new CustomSerializationPolicy("OdinSerializerPolicies.Unity", true, (member) =>
{
// Non-auto properties are never supported.
if (member is PropertyInfo && ((PropertyInfo)member).IsAutoProperty() == false)
{
return false;
}
// If OdinSerializeAttribute is defined, NonSerializedAttribute is ignored.
// This enables users to ignore Unity's infinite serialization depth warnings.
if (member.IsDefined<NonSerializedAttribute>(true) && !member.IsDefined<OdinSerializeAttribute>())
{
return false;
}
if (member is FieldInfo && ((member as FieldInfo).IsPublic || (member.DeclaringType.IsNestedPrivate && member.DeclaringType.IsDefined<CompilerGeneratedAttribute>()) || (tupleInterface != null && tupleInterface.IsAssignableFrom(member.DeclaringType))))
{
return true;
}
return member.IsDefined<SerializeField>(false) || member.IsDefined<OdinSerializeAttribute>(false) || (UnitySerializationUtility.SerializeReferenceAttributeType != null && member.IsDefined(UnitySerializationUtility.SerializeReferenceAttributeType, false));
});
}
}
}
return unityPolicy;
}
}
/// <summary>
/// Only fields and auto-properties marked with <see cref="SerializeField"/> or <see cref="OdinSerializeAttribute"/> and not marked with <see cref="NonSerializedAttribute"/> are serialized.
/// <para />
/// There are two exceptions:
/// <para/>1) All fields in private nested types marked as compiler generated (e.g. lambda capture classes) are also serialized.
/// <para/>2) Virtual auto-properties are never serialized. Note that properties specified by an implemented interface are automatically marked virtual by the compiler.
/// </summary>
public static ISerializationPolicy Strict
{
get
{
if (strictPolicy == null)
{
lock (LOCK)
{
if (strictPolicy == null)
{
strictPolicy = new CustomSerializationPolicy("OdinSerializerPolicies.Strict", true, (member) =>
{
// Non-auto properties are never supported.
if (member is PropertyInfo && ((PropertyInfo)member).IsAutoProperty() == false)
{
return false;
}
if (member.IsDefined<NonSerializedAttribute>())
{
return false;
}
if (member is FieldInfo && member.DeclaringType.IsNestedPrivate && member.DeclaringType.IsDefined<CompilerGeneratedAttribute>())
{
return true;
}
return member.IsDefined<SerializeField>(false) || member.IsDefined<OdinSerializeAttribute>(false) || (UnitySerializationUtility.SerializeReferenceAttributeType != null && member.IsDefined(UnitySerializationUtility.SerializeReferenceAttributeType, false));
});
}
}
}
return strictPolicy;
}
}
}
}
| |
/*
* Copyright 2006 Jeremias Maerki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Text;
namespace ZXing.Datamatrix.Encoder
{
/// <summary>
/// Symbol info table for DataMatrix.
/// </summary>
public class SymbolInfo
{
internal static readonly SymbolInfo[] PROD_SYMBOLS = {
new SymbolInfo(false, 3, 5, 8, 8, 1),
new SymbolInfo(false, 5, 7, 10, 10, 1),
/*rect*/new SymbolInfo(true, 5, 7, 16, 6, 1),
new SymbolInfo(false, 8, 10, 12, 12, 1),
/*rect*/new SymbolInfo(true, 10, 11, 14, 6, 2),
new SymbolInfo(false, 12, 12, 14, 14, 1),
/*rect*/new SymbolInfo(true, 16, 14, 24, 10, 1),
new SymbolInfo(false, 18, 14, 16, 16, 1),
new SymbolInfo(false, 22, 18, 18, 18, 1),
/*rect*/new SymbolInfo(true, 22, 18, 16, 10, 2),
new SymbolInfo(false, 30, 20, 20, 20, 1),
/*rect*/new SymbolInfo(true, 32, 24, 16, 14, 2),
new SymbolInfo(false, 36, 24, 22, 22, 1),
new SymbolInfo(false, 44, 28, 24, 24, 1),
/*rect*/new SymbolInfo(true, 49, 28, 22, 14, 2),
new SymbolInfo(false, 62, 36, 14, 14, 4),
new SymbolInfo(false, 86, 42, 16, 16, 4),
new SymbolInfo(false, 114, 48, 18, 18, 4),
new SymbolInfo(false, 144, 56, 20, 20, 4),
new SymbolInfo(false, 174, 68, 22, 22, 4),
new SymbolInfo(false, 204, 84, 24, 24, 4, 102, 42),
new SymbolInfo(false, 280, 112, 14, 14, 16, 140, 56),
new SymbolInfo(false, 368, 144, 16, 16, 16, 92, 36),
new SymbolInfo(false, 456, 192, 18, 18, 16, 114, 48),
new SymbolInfo(false, 576, 224, 20, 20, 16, 144, 56),
new SymbolInfo(false, 696, 272, 22, 22, 16, 174, 68),
new SymbolInfo(false, 816, 336, 24, 24, 16, 136, 56),
new SymbolInfo(false, 1050, 408, 18, 18, 36, 175, 68),
new SymbolInfo(false, 1304, 496, 20, 20, 36, 163, 62),
new DataMatrixSymbolInfo144(),
};
private static SymbolInfo[] symbols = PROD_SYMBOLS;
private readonly bool rectangular;
internal readonly int dataCapacity;
internal readonly int errorCodewords;
/// <summary>
/// matrix width
/// </summary>
public readonly int matrixWidth;
/// <summary>
/// matrix height
/// </summary>
public readonly int matrixHeight;
private readonly int dataRegions;
private readonly int rsBlockData;
private readonly int rsBlockError;
/**
* Overrides the symbol info set used by this class. Used for testing purposes.
*
* @param override the symbol info set to use
*/
public static void overrideSymbolSet(SymbolInfo[] @override)
{
symbols = @override;
}
/// <summary>
/// initializing constructor
/// </summary>
/// <param name="rectangular"></param>
/// <param name="dataCapacity"></param>
/// <param name="errorCodewords"></param>
/// <param name="matrixWidth"></param>
/// <param name="matrixHeight"></param>
/// <param name="dataRegions"></param>
public SymbolInfo(bool rectangular, int dataCapacity, int errorCodewords,
int matrixWidth, int matrixHeight, int dataRegions)
: this(rectangular, dataCapacity, errorCodewords, matrixWidth, matrixHeight, dataRegions,
dataCapacity, errorCodewords)
{
}
internal SymbolInfo(bool rectangular, int dataCapacity, int errorCodewords,
int matrixWidth, int matrixHeight, int dataRegions,
int rsBlockData, int rsBlockError)
{
this.rectangular = rectangular;
this.dataCapacity = dataCapacity;
this.errorCodewords = errorCodewords;
this.matrixWidth = matrixWidth;
this.matrixHeight = matrixHeight;
this.dataRegions = dataRegions;
this.rsBlockData = rsBlockData;
this.rsBlockError = rsBlockError;
}
/// <summary>
///
/// </summary>
/// <param name="dataCodewords"></param>
/// <returns></returns>
public static SymbolInfo lookup(int dataCodewords)
{
return lookup(dataCodewords, SymbolShapeHint.FORCE_NONE, true);
}
/// <summary>
///
/// </summary>
/// <param name="dataCodewords"></param>
/// <param name="shape"></param>
/// <returns></returns>
public static SymbolInfo lookup(int dataCodewords, SymbolShapeHint shape)
{
return lookup(dataCodewords, shape, true);
}
/// <summary>
///
/// </summary>
/// <param name="dataCodewords"></param>
/// <param name="allowRectangular"></param>
/// <param name="fail"></param>
/// <returns></returns>
public static SymbolInfo lookup(int dataCodewords, bool allowRectangular, bool fail)
{
SymbolShapeHint shape = allowRectangular
? SymbolShapeHint.FORCE_NONE : SymbolShapeHint.FORCE_SQUARE;
return lookup(dataCodewords, shape, fail);
}
private static SymbolInfo lookup(int dataCodewords, SymbolShapeHint shape, bool fail)
{
return lookup(dataCodewords, shape, null, null, fail);
}
/// <summary>
///
/// </summary>
/// <param name="dataCodewords"></param>
/// <param name="shape"></param>
/// <param name="minSize"></param>
/// <param name="maxSize"></param>
/// <param name="fail"></param>
/// <returns></returns>
public static SymbolInfo lookup(int dataCodewords,
SymbolShapeHint shape,
Dimension minSize,
Dimension maxSize,
bool fail)
{
foreach (SymbolInfo symbol in symbols)
{
if (shape == SymbolShapeHint.FORCE_SQUARE && symbol.rectangular)
{
continue;
}
if (shape == SymbolShapeHint.FORCE_RECTANGLE && !symbol.rectangular)
{
continue;
}
if (minSize != null
&& (symbol.getSymbolWidth() < minSize.Width
|| symbol.getSymbolHeight() < minSize.Height))
{
continue;
}
if (maxSize != null
&& (symbol.getSymbolWidth() > maxSize.Width
|| symbol.getSymbolHeight() > maxSize.Height))
{
continue;
}
if (dataCodewords <= symbol.dataCapacity)
{
return symbol;
}
}
if (fail)
{
throw new ArgumentException(
"Can't find a symbol arrangement that matches the message. Data codewords: "
+ dataCodewords);
}
return null;
}
private int getHorizontalDataRegions()
{
switch (dataRegions)
{
case 1:
return 1;
case 2:
case 4:
return 2;
case 16:
return 4;
case 36:
return 6;
default:
throw new InvalidOperationException("Cannot handle this number of data regions");
}
}
private int getVerticalDataRegions()
{
switch (dataRegions)
{
case 1:
case 2:
return 1;
case 4:
return 2;
case 16:
return 4;
case 36:
return 6;
default:
throw new InvalidOperationException("Cannot handle this number of data regions");
}
}
/// <summary>
/// symbol data width
/// </summary>
/// <returns></returns>
public int getSymbolDataWidth()
{
return getHorizontalDataRegions() * matrixWidth;
}
/// <summary>
/// symbol data height
/// </summary>
/// <returns></returns>
public int getSymbolDataHeight()
{
return getVerticalDataRegions() * matrixHeight;
}
/// <summary>
/// symbol width
/// </summary>
/// <returns></returns>
public int getSymbolWidth()
{
return getSymbolDataWidth() + (getHorizontalDataRegions() * 2);
}
/// <summary>
/// symbol height
/// </summary>
/// <returns></returns>
public int getSymbolHeight()
{
return getSymbolDataHeight() + (getVerticalDataRegions() * 2);
}
/// <summary>
/// codeword count
/// </summary>
/// <returns></returns>
public int getCodewordCount()
{
return dataCapacity + errorCodewords;
}
/// <summary>
/// interleaved block count
/// </summary>
/// <returns></returns>
public virtual int getInterleavedBlockCount()
{
return dataCapacity / rsBlockData;
}
/// <summary>
/// data length for interleaved block
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public virtual int getDataLengthForInterleavedBlock(int index)
{
return rsBlockData;
}
/// <summary>
/// error length for interleaved block
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public int getErrorLengthForInterleavedBlock(int index)
{
return rsBlockError;
}
/// <summary>
/// user friendly representation
/// </summary>
/// <returns></returns>
public override String ToString()
{
var sb = new StringBuilder();
sb.Append(rectangular ? "Rectangular Symbol:" : "Square Symbol:");
sb.Append(" data region ").Append(matrixWidth).Append('x').Append(matrixHeight);
sb.Append(", symbol size ").Append(getSymbolWidth()).Append('x').Append(getSymbolHeight());
sb.Append(", symbol data size ").Append(getSymbolDataWidth()).Append('x').Append(getSymbolDataHeight());
sb.Append(", codewords ").Append(dataCapacity).Append('+').Append(errorCodewords);
return sb.ToString();
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: SampleLMAX.SampleLMAXPublic
File: MainWindow.xaml.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace SampleLMAX
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using Ecng.Common;
using Ecng.Xaml;
using MoreLinq;
using StockSharp.BusinessEntities;
using StockSharp.LMAX;
using StockSharp.Localization;
public partial class MainWindow
{
private bool _isConnected;
public LmaxTrader Trader;
private readonly SecuritiesWindow _securitiesWindow = new SecuritiesWindow();
private readonly TradesWindow _tradesWindow = new TradesWindow();
private readonly MyTradesWindow _myTradesWindow = new MyTradesWindow();
private readonly OrdersWindow _ordersWindow = new OrdersWindow();
private readonly PortfoliosWindow _portfoliosWindow = new PortfoliosWindow();
private readonly StopOrdersWindow _stopOrdersWindow = new StopOrdersWindow();
public MainWindow()
{
InitializeComponent();
Title = Title.Put("LMAX");
_ordersWindow.MakeHideable();
_myTradesWindow.MakeHideable();
_tradesWindow.MakeHideable();
_securitiesWindow.MakeHideable();
_stopOrdersWindow.MakeHideable();
_portfoliosWindow.MakeHideable();
Instance = this;
}
protected override void OnClosing(CancelEventArgs e)
{
_ordersWindow.DeleteHideable();
_myTradesWindow.DeleteHideable();
_tradesWindow.DeleteHideable();
_securitiesWindow.DeleteHideable();
_stopOrdersWindow.DeleteHideable();
_portfoliosWindow.DeleteHideable();
_securitiesWindow.Close();
_tradesWindow.Close();
_myTradesWindow.Close();
_stopOrdersWindow.Close();
_ordersWindow.Close();
_portfoliosWindow.Close();
if (Trader != null)
Trader.Dispose();
base.OnClosing(e);
}
public static MainWindow Instance { get; private set; }
private void ConnectClick(object sender, RoutedEventArgs e)
{
if (!_isConnected)
{
if (Login.Text.IsEmpty())
{
MessageBox.Show(this, LocalizedStrings.Str2974);
return;
}
else if (Password.Password.IsEmpty())
{
MessageBox.Show(this, LocalizedStrings.Str2975);
return;
}
if (Trader == null)
{
// create connector
Trader = new LmaxTrader();
Trader.Restored += () => this.GuiAsync(() =>
{
// update gui labes
ChangeConnectStatus(true);
MessageBox.Show(this, LocalizedStrings.Str2958);
});
// subscribe on connection successfully event
Trader.Connected += () =>
{
// set flag (connection is established)
_isConnected = true;
// update gui labes
this.GuiAsync(() => ChangeConnectStatus(true));
};
Trader.Disconnected += () => this.GuiAsync(() => ChangeConnectStatus(false));
// subscribe on connection error event
Trader.ConnectionError += error => this.GuiAsync(() =>
{
// update gui labes
ChangeConnectStatus(false);
MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959);
});
// subscribe on error event
Trader.Error += error =>
this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955));
// subscribe on error of market data subscription event
Trader.MarketDataSubscriptionFailed += (security, type, error) =>
this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(type, security)));
Trader.NewSecurities += securities => _securitiesWindow.SecurityPicker.Securities.AddRange(securities);
Trader.NewMyTrades += trades => _myTradesWindow.TradeGrid.Trades.AddRange(trades);
Trader.NewTrades += trades => _tradesWindow.TradeGrid.Trades.AddRange(trades);
Trader.NewOrders += orders => _ordersWindow.OrderGrid.Orders.AddRange(orders);
Trader.NewStopOrders += orders => _stopOrdersWindow.OrderGrid.Orders.AddRange(orders);
Trader.NewPortfolios += portfolios =>
{
// subscribe on portfolio updates
portfolios.ForEach(Trader.RegisterPortfolio);
_portfoliosWindow.PortfolioGrid.Portfolios.AddRange(portfolios);
};
Trader.NewPositions += positions => _portfoliosWindow.PortfolioGrid.Positions.AddRange(positions);
// subscribe on error of order registration event
Trader.OrdersRegisterFailed += OrdersFailed;
// subscribe on error of order cancelling event
Trader.OrdersCancelFailed += OrdersFailed;
// subscribe on error of stop-order registration event
Trader.StopOrdersRegisterFailed += OrdersFailed;
// subscribe on error of stop-order cancelling event
Trader.StopOrdersCancelFailed += OrdersFailed;
// set market data provider
_securitiesWindow.SecurityPicker.MarketDataProvider = Trader;
ShowSecurities.IsEnabled = ShowTrades.IsEnabled =
ShowMyTrades.IsEnabled = ShowOrders.IsEnabled =
ShowPortfolios.IsEnabled = ShowStopOrders.IsEnabled = true;
}
Trader.Login = Login.Text;
Trader.Password = Password.Password;
Trader.IsDemo = IsDemo.IsChecked == true;
// in sandbox security identifies may be different than uploaded on the site
Trader.IsDownloadSecurityFromSite = !Trader.IsDemo;
// clear password box for security reason
//Password.Clear();
Trader.Connect();
}
else
{
Trader.Disconnect();
}
}
private void OrdersFailed(IEnumerable<OrderFail> fails)
{
this.GuiAsync(() =>
{
foreach (var fail in fails)
MessageBox.Show(this, fail.Error.ToString(), LocalizedStrings.Str2960);
});
}
private void ChangeConnectStatus(bool isConnected)
{
_isConnected = isConnected;
ConnectBtn.Content = isConnected ? LocalizedStrings.Disconnect : LocalizedStrings.Connect;
}
private void ShowSecuritiesClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_securitiesWindow);
}
private void ShowTradesClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_tradesWindow);
}
private void ShowMyTradesClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_myTradesWindow);
}
private void ShowOrdersClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_ordersWindow);
}
private void ShowPortfoliosClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_portfoliosWindow);
}
private void ShowStopOrdersClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_stopOrdersWindow);
}
private static void ShowOrHide(Window window)
{
if (window == null)
throw new ArgumentNullException(nameof(window));
if (window.Visibility == Visibility.Visible)
window.Hide();
else
window.Show();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.UseObjectInitializer;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseObjectInitializer
{
public partial class UseObjectInitializerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpUseObjectInitializerDiagnosticAnalyzer(), new CSharpUseObjectInitializerCodeFixProvider());
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)]
public async Task TestOnVariableDeclarator()
{
await TestInRegularAndScriptAsync(
@"class C
{
int i;
void M()
{
var c = [||]new C();
c.i = 1;
}
}",
@"class C
{
int i;
void M()
{
var c = new C
{
i = 1
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)]
public async Task TestDoNotUpdateAssignmentThatReferencesInitializedValue1Async()
{
await TestInRegularAndScriptAsync(
@"class C
{
int i;
void M()
{
var c = [||]new C();
c.i = 1;
c.i = c.i + 1;
}
}",
@"class C
{
int i;
void M()
{
var c = new C
{
i = 1
};
c.i = c.i + 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)]
public async Task TestDoNotUpdateAssignmentThatReferencesInitializedValue2Async()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
int i;
void M()
{
var c = [||]new C();
c.i = c.i + 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)]
public async Task TestDoNotUpdateAssignmentThatReferencesInitializedValue3Async()
{
await TestInRegularAndScriptAsync(
@"class C
{
int i;
void M()
{
C c;
c = [||]new C();
c.i = 1;
c.i = c.i + 1;
}
}",
@"class C
{
int i;
void M()
{
C c;
c = new C
{
i = 1
};
c.i = c.i + 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)]
public async Task TestDoNotUpdateAssignmentThatReferencesInitializedValue4Async()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
int i;
void M()
{
C c;
c = [||]new C();
c.i = c.i + 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)]
public async Task TestOnAssignmentExpression()
{
await TestInRegularAndScriptAsync(
@"class C
{
int i;
void M()
{
C c = null;
c = [||]new C();
c.i = 1;
}
}",
@"class C
{
int i;
void M()
{
C c = null;
c = new C
{
i = 1
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)]
public async Task TestStopOnDuplicateMember()
{
await TestInRegularAndScriptAsync(
@"class C
{
int i;
void M()
{
var c = [||]new C();
c.i = 1;
c.i = 2;
}
}",
@"class C
{
int i;
void M()
{
var c = new C
{
i = 1
};
c.i = 2;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)]
public async Task TestComplexInitializer()
{
await TestInRegularAndScriptAsync(
@"class C
{
int i;
int j;
void M()
{
C[] array;
array[0] = [||]new C();
array[0].i = 1;
array[0].j = 2;
}
}",
@"class C
{
int i;
int j;
void M()
{
C[] array;
array[0] = new C
{
i = 1,
j = 2
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)]
public async Task TestNotOnCompoundAssignment()
{
await TestInRegularAndScriptAsync(
@"class C
{
int i;
int j;
void M()
{
var c = [||]new C();
c.i = 1;
c.j += 1;
}
}",
@"class C
{
int i;
int j;
void M()
{
var c = new C
{
i = 1
};
c.j += 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)]
public async Task TestMissingWithExistingInitializer()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
int i;
int j;
void M()
{
var c = [||]new C() { i = 1 };
c.j = 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)]
public async Task TestMissingBeforeCSharp3()
{
await TestMissingAsync(
@"class C
{
int i;
int j;
void M()
{
var c = [||]new C();
c.j = 1;
}
}", new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp2)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)]
public async Task TestFixAllInDocument1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int i;
int j;
void M()
{
var v = {|FixAllInDocument:new|} C(() => {
var v2 = new C();
v2.i = 1;
});
v.j = 2;
}
}",
@"class C
{
int i;
int j;
void M()
{
var v = new C(() => {
var v2 = new C
{
i = 1
};
})
{
j = 2
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)]
public async Task TestFixAllInDocument2()
{
await TestInRegularAndScriptAsync(
@"class C
{
int i;
int j;
void M()
{
var v = {|FixAllInDocument:new|} C();
v.j = () => {
var v2 = new C();
v2.i = 1;
};
}
}",
@"class C
{
int i;
int j;
void M()
{
var v = new C
{
j = () => {
var v2 = new C
{
i = 1
};
}
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)]
public async Task TestFixAllInDocument3()
{
await TestInRegularAndScriptAsync(
@"class C
{
int i;
int j;
void M()
{
C[] array;
array[0] = {|FixAllInDocument:new|} C();
array[0].i = 1;
array[0].j = 2;
array[1] = new C();
array[1].i = 3;
array[1].j = 4;
}
}",
@"class C
{
int i;
int j;
void M()
{
C[] array;
array[0] = new C
{
i = 1,
j = 2
};
array[1] = new C
{
i = 3,
j = 4
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)]
public async Task TestTrivia1()
{
await TestInRegularAndScriptAsync(
@"
class C
{
int i;
int j;
void M()
{
var c = [||]new C();
c.i = 1; // Foo
c.j = 2; // Bar
}
}",
@"
class C
{
int i;
int j;
void M()
{
var c = new C
{
i = 1, // Foo
j = 2 // Bar
};
}
}",
ignoreTrivia: false);
}
[WorkItem(15459, "https://github.com/dotnet/roslyn/issues/15459")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)]
public async Task TestMissingInNonTopLevelObjectInitializer()
{
await TestMissingInRegularAndScriptAsync(
@"class C {
int a;
C Add(int x) {
var c = Add([||]new int());
c.a = 1;
return c;
}
}");
}
[WorkItem(17853, "https://github.com/dotnet/roslyn/issues/17853")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)]
public async Task TestMissingForDynamic()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Dynamic;
class C
{
void Foo()
{
dynamic body = [||]new ExpandoObject();
body.content = new ExpandoObject();
}
}");
}
[WorkItem(17953, "https://github.com/dotnet/roslyn/issues/17953")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)]
public async Task TestMissingAcrossPreprocessorDirective()
{
await TestMissingInRegularAndScriptAsync(
@"
public class Foo
{
public void M()
{
var foo = [||]new Foo();
#if true
foo.Value = "";
#endif
}
public string Value { get; set; }
}");
}
[WorkItem(17953, "https://github.com/dotnet/roslyn/issues/17953")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)]
public async Task TestAvailableInsidePreprocessorDirective()
{
await TestInRegularAndScript1Async(
@"
public class Foo
{
public void M()
{
#if true
var foo = [||]new Foo();
foo.Value = "";
#endif
}
public string Value { get; set; }
}",
@"
public class Foo
{
public void M()
{
#if true
var foo = new Foo
{
Value = "";
};
#endif
}
public string Value { get; set; }
}", ignoreTrivia: false);
}
[WorkItem(19253, "https://github.com/dotnet/roslyn/issues/19253")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)]
public async Task TestKeepBlankLinesAfter()
{
await TestInRegularAndScript1Async(
@"
class Foo
{
public int Bar { get; set; }
}
class MyClass
{
public void Main()
{
var foo = [||]new Foo();
foo.Bar = 1;
int horse = 1;
}
}",
@"
class Foo
{
public int Bar { get; set; }
}
class MyClass
{
public void Main()
{
var foo = new Foo
{
Bar = 1
};
int horse = 1;
}
}", ignoreTrivia: false);
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml.Linq;
using Skybrud.Social.Interfaces;
using Skybrud.Social.Json;
namespace Skybrud.Social {
/// <summary>
/// Static class with various utility methods used througout Skybrud.Social.
/// </summary>
public static class SocialUtils {
#region Version
/// <summary>
/// Gets the assembly version as a string.
/// </summary>
public static string GetVersion() {
return typeof (SocialUtils).Assembly.GetName().Version.ToString();
}
/// <summary>
/// Gets the file version as a string.
/// </summary>
/// <returns></returns>
public static string GetFileVersion() {
Assembly assembly = typeof(SocialUtils).Assembly;
return FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion;
}
/// <summary>
/// Gets the amount of days between the date of this build and the date the project was started - that is the 30th of July, 2012.
/// </summary>
public static int GetDaysSinceStart() {
// Get the third bit as a string
string str = GetFileVersion().Split('.')[2];
// Parse the string into an integer
return Int32.Parse(str);
}
/// <summary>
/// Gets the date of this build of Skybrud.Social.
/// </summary>
public static DateTime GetBuildDate() {
return new DateTime(2012, 7, 30).AddDays(GetDaysSinceStart());
}
/// <summary>
/// Gets the build number of the day. This is mostly used for internal
/// purposes to distinguish builds with the same assembly version.
/// </summary>
public static int GetBuildNumber() {
// Get the fourth bit as a string
string str = GetFileVersion().Split('.')[3];
// Parse the string into an integer
return Int32.Parse(str);
}
#endregion
#region HTTP helpers
private static HttpWebResponse DoHttpRequest(string url, string method, NameValueCollection queryString, NameValueCollection postData) {
// TODO: Decide better naming of method
// Merge the query string
url = new UriBuilder(url).MergeQueryString(queryString).ToString();
// Initialize the request
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
// Set the method
request.Method = method;
// Add the request body (if a POST request)
if (method == "POST" && postData != null && postData.Count > 0) {
string dataString = NameValueCollectionToQueryString(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = dataString.Length;
using (Stream stream = request.GetRequestStream()) {
stream.Write(Encoding.UTF8.GetBytes(dataString), 0, dataString.Length);
}
}
// Get the response
try {
return (HttpWebResponse)request.GetResponse();
} catch (WebException ex) {
return (HttpWebResponse)ex.Response;
}
}
#region GET
public static HttpWebResponse DoHttpGetRequest(string baseUrl, NameValueCollection queryString = null) {
return DoHttpRequest(baseUrl, "GET", queryString, null);
}
public static string DoHttpGetRequestAndGetBodyAsString(string url, NameValueCollection queryString = null) {
return DoHttpGetRequest(url, queryString).GetAsString();
}
public static IJsonObject DoHttpGetRequestAndGetBodyAsJson(string url, NameValueCollection queryString = null) {
return DoHttpGetRequest(url, queryString).GetAsJson();
}
public static JsonObject DoHttpGetRequestAndGetBodyAsJsonObject(string url, NameValueCollection queryString = null) {
return DoHttpGetRequest(url, queryString).GetAsJsonObject();
}
public static JsonArray DoHttpGetRequestAndGetBodyAsJsonArray(string url, NameValueCollection queryString = null) {
return DoHttpGetRequest(url, queryString).GetAsJsonArray();
}
public static XElement DoHttpGetRequestAndGetBodyAsXml(string url, NameValueCollection queryString = null) {
HttpWebResponse response = DoHttpGetRequest(url, queryString);
Stream stream = response.GetResponseStream();
return stream == null ? null : XElement.Parse(new StreamReader(stream).ReadToEnd());
}
#endregion
#region POST
public static HttpWebResponse DoHttpPostRequest(string baseUrl, NameValueCollection queryString, NameValueCollection postData) {
return DoHttpRequest(baseUrl, "POST", queryString, postData);
}
public static string DoHttpPostRequestAndGetBodyAsString(string url, NameValueCollection queryString = null, NameValueCollection postData = null) {
return DoHttpPostRequest(url, queryString, postData).GetAsString();
}
public static IJsonObject DoHttpPostRequestAndGetBodyAsJson(string url, NameValueCollection queryString = null, NameValueCollection postData = null) {
return DoHttpPostRequest(url, queryString, postData).GetAsJson();
}
public static JsonObject DoHttpPostRequestAndGetBodyAsJsonObject(string url, NameValueCollection queryString = null, NameValueCollection postData = null) {
return DoHttpPostRequest(url, queryString, postData).GetAsJsonObject();
}
public static JsonArray DoHttpPostRequestAndGetBodyAsJsonArray(string url, NameValueCollection queryString = null, NameValueCollection postData = null) {
return DoHttpPostRequest(url, queryString, postData).GetAsJsonArray();
}
public static XElement DoHttpPostRequestAndGetBodyAsXml(string url, NameValueCollection queryString = null, NameValueCollection postData = null) {
HttpWebResponse response = DoHttpPostRequest(url, queryString, postData);
Stream stream = response.GetResponseStream();
return stream == null ? null : XElement.Parse(new StreamReader(stream).ReadToEnd());
}
#endregion
#endregion
#region Other
public static string CamelCaseToUnderscore(Enum e) {
return CamelCaseToUnderscore(e.ToString());
}
public static string CamelCaseToUnderscore(string str) {
return Regex.Replace(str, @"(\p{Ll})(\p{Lu})", "$1_$2").ToLower();
}
/// <summary>
/// Encodes a URL string.
/// </summary>
/// <param name="str">The string to be encoded.</param>
/// <returns>Returns the encoded string.</returns>
public static string UrlEncode(string str) {
return HttpUtility.UrlEncode(str);
}
/// <summary>
/// Decodes a URL string.
/// </summary>
/// <param name="str">The string to be decoded.</param>
/// <returns>Returns the decoded string.</returns>
public static string UrlDecode(string str) {
return HttpUtility.UrlDecode(str);
}
/// <summary>
/// Parses a query string into a <code>System.Collections.Specialized.NameValueCollection</code> using <code>System.Text.Encoding.UTF8</code> encoding.
/// </summary>
/// <param name="query">The query string to parse.</param>
/// <returns>A <code>System.Collections.Specialized.NameValueCollection</code> of query parameters and values.</returns>
public static NameValueCollection ParseQueryString(string query) {
return HttpUtility.ParseQueryString(query);
}
/// <summary>
/// Converts the specified <var>NameValueCollection</var> into a query string using the proper encoding.
/// </summary>
/// <param name="collection">The collection to convert.</param>
/// <returns></returns>
public static string NameValueCollectionToQueryString(NameValueCollection collection) {
return String.Join("&", Array.ConvertAll(collection.AllKeys, key => UrlEncode(key) + "=" + UrlEncode(collection[key])));
}
public static string NameValueCollectionToQueryString(NameValueCollection collection, bool includeIfNull) {
return String.Join("&", (
from string key in collection.Keys
where collection[key] != null || includeIfNull
select UrlEncode(key) + "=" + UrlEncode(collection[key])
));
}
public static T GetAttributeValue<T>(XElement xElement, string name) {
string value = xElement.Attribute(name).Value;
return (T)Convert.ChangeType(value, typeof(T));
}
public static T GetAttributeValueOrDefault<T>(XElement xElement, string name) {
XAttribute attr = xElement.Attribute(name);
if (attr == null) return default(T);
return (T)Convert.ChangeType(attr.Value, typeof(T));
}
public static T GetElementValue<T>(XElement xElement, string name) {
string value = xElement.Element(name).Value;
return (T)Convert.ChangeType(value, typeof(T));
}
public static T GetElementValueOrDefault<T>(XElement xElement, string name) {
XElement e = xElement.Element(name);
if (e == null) return default(T);
return (T)Convert.ChangeType(e.Value, typeof(T));
}
#endregion
#region Timestamps
/// <summary>
/// ISO 8601 date format.
/// </summary>
public const string IsoDateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssK";
/// <summary>
/// Returns the current unix timestamp which is defined as the amount of seconds
/// since the start of the Unix epoch - 1st of January, 1970 - 00:00:00 GMT.
/// </summary>
public static long GetCurrentUnixTimestamp() {
return (long) Math.Floor(GetCurrentUnixTimestampAsDouble());
}
/// <summary>
/// Returns the current unix timestamp which is defined as the amount of seconds
/// since the start of the Unix epoch - 1st of January, 1970 - 00:00:00 GMT.
/// </summary>
public static double GetCurrentUnixTimestampAsDouble() {
return (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
}
public static DateTime GetDateTimeFromUnixTime(int timestamp) {
return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timestamp);
}
public static DateTime GetDateTimeFromUnixTime(double timestamp) {
return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timestamp);
}
public static DateTime GetDateTimeFromUnixTime(long timestamp) {
return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timestamp);
}
public static DateTime GetDateTimeFromUnixTime(string timestamp) {
return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(Int64.Parse(timestamp));
}
public static long GetUnixTimeFromDateTime(DateTime dateTime) {
return (int) (dateTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
}
#endregion
#region Locations and distance
/// <summary>
/// Calculates the distance in meters between two GPS locations.
/// </summary>
/// <param name="loc1">The first location.</param>
/// <param name="loc2">The second location.</param>
public static double GetDistance(ILocation loc1, ILocation loc2) {
return GetDistance(loc1.Latitude, loc1.Longitude, loc2.Latitude, loc2.Longitude);
}
/// <summary>
/// Calculates the distance in meters between two GPS locations.
/// </summary>
public static double GetDistance(double lat1, double lng1, double lat2, double lng2) {
// http://stackoverflow.com/a/3440123
double ee = (Math.PI * lat1 / 180);
double f = (Math.PI * lng1 / 180);
double g = (Math.PI * lat2 / 180);
double h = (Math.PI * lng2 / 180);
double i = (Math.Cos(ee) * Math.Cos(g) * Math.Cos(f) * Math.Cos(h) + Math.Cos(ee) * Math.Sin(f) * Math.Cos(g) * Math.Sin(h) + Math.Sin(ee) * Math.Sin(g));
double j = (Math.Acos(i));
return (6371 * j) * 1000d;
}
#endregion
#region Enums
public static T ParseEnum<T>(string str) where T : struct {
// Check whether the type of T is an enum
if (!typeof(T).IsEnum) throw new ArgumentException("Generic type T must be an enum");
// Parse the enum
foreach (string name in Enum.GetNames(typeof(T))) {
if (name.ToLowerInvariant() == str.ToLowerInvariant()) {
return (T) Enum.Parse(typeof(T), str, true);
}
}
throw new Exception("Unable to parse enum of type " + typeof(T).Name + " from value \"" + str + "\"");
}
public static T ParseEnum<T>(string str, T fallback) where T : struct {
// Check whether the type of T is an enum
if (!typeof(T).IsEnum) throw new ArgumentException("Generic type T must be an enum");
// Parse the enum
foreach (string name in Enum.GetNames(typeof(T))) {
if (name.ToLowerInvariant() == str.ToLowerInvariant()) {
return (T)Enum.Parse(typeof(T), str, true);
}
}
return fallback;
}
#endregion
}
}
| |
/*
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using UnityEngine;
using UnityEditor;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Text;
using System.Text.RegularExpressions;
/// <summary>
/// Custom editor scripts for various components of UnityUtilLib
/// </summary>
namespace UnityUtilLib.Editor {
/// <summary>
/// <para>A small data structure class hold values for making Doxygen config files </para>
/// </summary>
internal class DoxygenConfig {
public string Project = PlayerSettings.productName;
public string Synopsis = "";
public string Version = "";
public string ScriptsDirectory = Application.dataPath;
public string DocDirectory = Application.dataPath.Replace("Assets", "Docs");
public string PathtoDoxygen = "";
}
/// <summary>
/// An Editor Plugin for automatic doc generation through Doxygen
/// <para> Author: Jacob Pennock (http://Jacobpennock.com)</para>
/// <para> Version: 1.0</para>
/// </summary>
internal class DoxygenWindow : EditorWindow {
public static DoxygenWindow Instance;
public enum WindowModes{Generate,Configuration,About}
public string UnityProjectID = PlayerSettings.productName+":";
public string AssestsFolder = Application.dataPath;
public string[] Themes = new string[3] {"Default", "Dark and Colorful", "Light and Clean"};
public int SelectedTheme = 1;
WindowModes DisplayMode = WindowModes.Generate;
static DoxygenConfig Config;
static bool DoxyFileExists = false;
StringReader reader;
TextAsset basefile;
float DoxyfileCreateProgress = -1.0f;
float DoxyoutputProgress = -1.0f;
string CreateProgressString = "Creating Doxyfile..";
public string BaseFileString = null;
public string DoxygenOutputString = null;
public string CurentOutput = null;
DoxyThreadSafeOutput DoxygenOutput = null;
List<string> DoxygenLog = null;
bool ViewLog = false;
Vector2 scroll;
bool DocsGenerated = false;
[MenuItem( "Window/Documentation with Doxygen" )]
public static void Init() {
Instance = (DoxygenWindow)EditorWindow.GetWindow( typeof( DoxygenWindow ), false, "Documentation" );
Instance.minSize = new Vector2( 420, 245 );
Instance.maxSize = new Vector2( 420, 720 );
}
void OnEnable() {
LoadConfig();
DoxyoutputProgress = 0;
}
void OnDisable() {
DoxyoutputProgress = 0;
DoxygenLog = null;
}
void OnGUI() {
DisplayHeadingToolbar();
switch(DisplayMode) {
case WindowModes.Generate:
GenerateGUI();
break;
case WindowModes.Configuration:
ConfigGUI();
break;
case WindowModes.About:
AboutGUI();
break;
}
}
void DisplayHeadingToolbar() {
GUIStyle normalButton = new GUIStyle( EditorStyles.toolbarButton );
normalButton.fixedWidth = 140;
GUILayout.Space (5);
EditorGUILayout.BeginHorizontal( EditorStyles.toolbar ); {
if( GUILayout.Toggle( DisplayMode == WindowModes.Generate, "Generate Documentation", normalButton ) ){
DoxyfileCreateProgress = -1;
DisplayMode = WindowModes.Generate;
}
if( GUILayout.Toggle( DisplayMode == WindowModes.Configuration, "Settings/Configuration", normalButton ) ) {
DisplayMode = WindowModes.Configuration;
}
if( GUILayout.Toggle( DisplayMode == WindowModes.About, "About", normalButton ) ) {
DoxyfileCreateProgress = -1;
DisplayMode = WindowModes.About;
}
}
EditorGUILayout.EndHorizontal();
}
void ConfigGUI() {
GUILayout.Space (10);
if(Config.Project == "Enter your Project name (Required)" || Config.Project == "" || Config.PathtoDoxygen == "" )
UnityEngine.GUI.enabled = false;
if(GUILayout.Button ("Save Configuration and Build new DoxyFile", GUILayout.Height(40))) {
MakeNewDoxyFile(Config);
}
if(DoxyfileCreateProgress >= 0) {
Rect r = EditorGUILayout.BeginVertical();
EditorGUI.ProgressBar(r, DoxyfileCreateProgress, CreateProgressString);
GUILayout.Space(16);
EditorGUILayout.EndVertical();
}
UnityEngine.GUI.enabled = true;
GUILayout.Space (20);
GUILayout.Label("Set Path to Doxygen Install",EditorStyles.boldLabel);
GUILayout.Space (5);
EditorGUILayout.BeginHorizontal();
Config.PathtoDoxygen = EditorGUILayout.TextField("Doxygen.exe : ",Config.PathtoDoxygen);
if(GUILayout.Button ("...",EditorStyles.miniButtonRight, GUILayout.Width(22)))
Config.PathtoDoxygen = EditorUtility.OpenFilePanel ("Where is doxygen.exe installed?","", "");
EditorGUILayout.EndHorizontal();
GUILayout.Space (20);
GUILayout.Label("Provide some details about the project",EditorStyles.boldLabel);
GUILayout.Space (5);
Config.Project = EditorGUILayout.TextField("Project Name: ",Config.Project);
Config.Synopsis = EditorGUILayout.TextField("Project Brief: ",Config.Synopsis);
Config.Version = EditorGUILayout.TextField("Project Version: ",Config.Version);
GUILayout.Space (15);
GUILayout.Label("Select Theme",EditorStyles.boldLabel);
GUILayout.Space (5);
SelectedTheme = EditorGUILayout.Popup(SelectedTheme,Themes) ;
GUILayout.Space (20);
GUILayout.Label("Setup the Directories",EditorStyles.boldLabel);
GUILayout.Space (5);
EditorGUILayout.BeginHorizontal();
Config.ScriptsDirectory = EditorGUILayout.TextField("Scripts folder: ",Config.ScriptsDirectory);
if(GUILayout.Button ("...",EditorStyles.miniButtonRight, GUILayout.Width(22)))
Config.ScriptsDirectory = EditorUtility.OpenFolderPanel("Select your scripts folder", Config.ScriptsDirectory, "");
EditorGUILayout.EndHorizontal();
GUILayout.Space (5);
EditorGUILayout.BeginHorizontal();
Config.DocDirectory = EditorGUILayout.TextField("Output folder: ",Config.DocDirectory);
if(GUILayout.Button ("...",EditorStyles.miniButtonRight, GUILayout.Width(22)))
Config.DocDirectory = EditorUtility.OpenFolderPanel("Select your ouput Docs folder", Config.DocDirectory, "");
EditorGUILayout.EndHorizontal();
GUILayout.Space (5);
EditorGUILayout.BeginHorizontal();
GUILayout.Space (5);
GUILayout.Space (30);
GUILayout.Label("By default Doxygen will search through your whole Assets folder for C# script files to document. Then it will output the documentation it generates into a folder called \"Docs\" that is placed in your project folder next to the Assets folder. If you would like to set a specific script or output folder you can do so above. ",EditorStyles.wordWrappedMiniLabel);
GUILayout.Space (30);
EditorGUILayout.EndHorizontal();
}
void AboutGUI() {
GUIStyle CenterLable = new GUIStyle(EditorStyles.largeLabel);
GUIStyle littletext = new GUIStyle(EditorStyles.miniLabel) ;
CenterLable.alignment = TextAnchor.MiddleCenter;
GUILayout.Space (20);
GUILayout.Label( "Automatic C# Documentation Generation through Doxygen",CenterLable);
GUILayout.Label( "Version: 1.0",CenterLable);
GUILayout.Label( "By: Jacob Pennock",CenterLable);
GUILayout.Space (20);
EditorGUILayout.BeginHorizontal();
GUILayout.Space (20);
GUILayout.Label( "Follow me for more Unity tips and tricks",littletext);
GUILayout.Space (15);
if(GUILayout.Button( "twitter")) {
Application.OpenURL("http://twitter.com/@JacobPennock");
}
GUILayout.Space (20);
EditorGUILayout.EndHorizontal();
GUILayout.Space (10);
EditorGUILayout.BeginHorizontal();
GUILayout.Space (20);
GUILayout.Label( "Visit my site for more plugins and tutorials",littletext);
if(GUILayout.Button( "JacobPennock.com")) {
Application.OpenURL("http://www.jacobpennock.com/Blog/?cat=19");
}
GUILayout.Space (20);
EditorGUILayout.EndHorizontal();
}
void GenerateGUI() {
if(DoxyFileExists) {
//UnityEngine.print(DoxyoutputProgress);
GUILayout.Space (10);
if(!DocsGenerated) {
UnityEngine.GUI.enabled = false;
}
if(GUILayout.Button ("Browse Documentation", GUILayout.Height(40))) {
Application.OpenURL("File://"+Config.DocDirectory+"/html/annotated.html");
}
UnityEngine.GUI.enabled = true;
if(DoxygenOutput == null) {
if(GUILayout.Button ("Run Doxygen", GUILayout.Height(40))) {
DocsGenerated = false;
RunDoxygen();
}
if(DocsGenerated && DoxygenLog != null) {
if(GUILayout.Button( "View Doxygen Log",EditorStyles.toolbarDropDown))
ViewLog = !ViewLog;
if(ViewLog) {
scroll = EditorGUILayout.BeginScrollView(scroll, GUILayout.ExpandHeight(true));
foreach(string logitem in DoxygenLog) {
EditorGUILayout.SelectableLabel(logitem,EditorStyles.miniLabel,GUILayout.ExpandWidth(true));
}
EditorGUILayout.EndScrollView();
}
}
} else {
if(DoxygenOutput.isStarted() && !DoxygenOutput.isFinished()) {
string currentline = DoxygenOutput.ReadLine();
DoxyoutputProgress = DoxyoutputProgress + 0.1f;
if(DoxyoutputProgress >= 0.9f) {
DoxyoutputProgress = 0.75f;
}
Rect r = EditorGUILayout.BeginVertical();
EditorGUI.ProgressBar(r, DoxyoutputProgress,currentline );
GUILayout.Space(40);
EditorGUILayout.EndVertical();
}
if(DoxygenOutput.isFinished()) {
if (Event.current.type == EventType.Repaint)
{
/*
If you look at what SetTheme is doing, I know, it seems a little scary to be
calling file moving operations from inside a an OnGUI call like this. And
maybe it would be a better choice to call SetTheme and update these other vars
from inside of the OnDoxygenFinished callback. But since the callback is static
that would require a little bit of messy singleton instance checking to make sure
the call back was calling into the right functions. I did try to do it that way
but for some reason the file operations failed every time. I'm not sure why.
This is what I was getting from the debugger:
Error in file: C:/BuildAgent/work/842f9551727e852/Runtime/Mono/MonoManager.cpp at line 2212
UnityEditor.FileUtil:DeleteFileOrDirectory(String)
UnityEditor.FileUtil:ReplaceFile(String, String) (at C:\BuildAgent\work\842f9557127e852\Editor\MonoGenerated\Editor\FileUtil.cs:42)
Doing them here seems to work every time and the Repaint event check ensures that they will only be done once.
*/
SetTheme(SelectedTheme);
DoxygenLog = DoxygenOutput.ReadFullLog();
DoxyoutputProgress = -1.0f;
DoxygenOutput = null;
DocsGenerated = true;
EditorPrefs.SetBool(UnityProjectID+"DocsGenerated",DocsGenerated);
}
}
}
} else {
GUIStyle ErrorLabel = new GUIStyle(EditorStyles.largeLabel);
ErrorLabel.alignment = TextAnchor.MiddleCenter;
GUILayout.Space(20);
UnityEngine.GUI.contentColor = Color.red;
GUILayout.Label("You must set the path to your Doxygen install and \nbuild a new Doxyfile before you can generate documentation",ErrorLabel);
}
}
public void readBaseConfig() {
basefile = (TextAsset)Resources.Load("BaseDoxyfile", typeof(TextAsset));
reader = new StringReader(basefile.text);
if ( reader == null )
UnityEngine.Debug.LogError("BaseDoxyfile not found or not readable");
else
BaseFileString = reader.ReadToEnd();
}
internal void MakeNewDoxyFile(DoxygenConfig config) {
SaveConfigtoEditor(config);
CreateProgressString = "Creating Output Folder";
DoxyfileCreateProgress = 0.1f;
System.IO.Directory.CreateDirectory(config.DocDirectory);
DoxyfileCreateProgress = 0.1f;
string newfile = BaseFileString.Replace("PROJECT_NAME =", "PROJECT_NAME = "+"\""+config.Project+"\"");
DoxyfileCreateProgress = 0.2f;
newfile = newfile.Replace("PROJECT_NUMBER =", "PROJECT_NUMBER = "+config.Version);
DoxyfileCreateProgress = 0.3f;
newfile = newfile.Replace("PROJECT_BRIEF =", "PROJECT_BRIEF = "+"\""+config.Synopsis+"\"");
DoxyfileCreateProgress = 0.4f;
newfile = newfile.Replace("OUTPUT_DIRECTORY =", "OUTPUT_DIRECTORY = "+"\""+config.DocDirectory+"\"");
DoxyfileCreateProgress = 0.5f;
newfile = newfile.Replace("INPUT =", "INPUT = "+"\""+config.ScriptsDirectory+"\"");
DoxyfileCreateProgress = 0.6f;
switch(SelectedTheme)
{
case 0:
newfile = newfile.Replace("GENERATE_TREEVIEW = NO", "GENERATE_TREEVIEW = YES");
break;
case 1:
newfile = newfile.Replace("SEARCHENGINE = YES", "SEARCHENGINE = NO");
newfile = newfile.Replace("CLASS_DIAGRAMS = YES", "CLASS_DIAGRAMS = NO");
break;
}
newfile = newfile.Replace("HIDE_SCOPE_NAMES = NO", "HIDE_SCOPE_NAMES = YES");
CreateProgressString = "New Options Set";
StringBuilder sb = new StringBuilder();
sb.Append(newfile);
StreamWriter NewDoxyfile = new StreamWriter(config.DocDirectory + @"\Doxyfile");
NewDoxyfile.Write(sb.ToString());
NewDoxyfile.Close();
DoxyfileCreateProgress = 1.0f;
CreateProgressString = "New Doxyfile Created!";
DoxyFileExists = true;
EditorPrefs.SetBool(UnityProjectID+"DoxyFileExists",DoxyFileExists);
}
void SaveConfigtoEditor(DoxygenConfig config)
{
EditorPrefs.SetString(UnityProjectID+"DoxyProjectName",config.Project);
EditorPrefs.SetString(UnityProjectID+"DoxyProjectNumber",config.Version);
EditorPrefs.SetString(UnityProjectID+"DoxyProjectBrief",config.Synopsis);
EditorPrefs.SetString(UnityProjectID+"DoxyProjectFolder",config.ScriptsDirectory);
EditorPrefs.SetString(UnityProjectID+"DoxyProjectOutput",config.DocDirectory);
EditorPrefs.SetString("DoxyEXE", config.PathtoDoxygen);
EditorPrefs.SetInt(UnityProjectID+"DoxyTheme", SelectedTheme);
}
void LoadConfig()
{
if(BaseFileString == null)
readBaseConfig();
if(Config == null)
{
if(!LoadSavedConfig())
Config = new DoxygenConfig();
}
if(EditorPrefs.HasKey(UnityProjectID+"DoxyFileExists"))
DoxyFileExists = EditorPrefs.GetBool(UnityProjectID+"DoxyFileExists");
if(EditorPrefs.HasKey(UnityProjectID+"DocsGenerated"))
DocsGenerated = EditorPrefs.GetBool(UnityProjectID+"DocsGenerated");
if(EditorPrefs.HasKey(UnityProjectID+"DoxyTheme"))
SelectedTheme = EditorPrefs.GetInt(UnityProjectID+"DoxyTheme");
if(EditorPrefs.HasKey("DoxyEXE"))
Config.PathtoDoxygen = EditorPrefs.GetString("DoxyEXE");
}
bool LoadSavedConfig()
{
if( EditorPrefs.HasKey (UnityProjectID+"DoxyProjectName"))
{
Config = new DoxygenConfig();
Config.Project = EditorPrefs.GetString(UnityProjectID+"DoxyProjectName");
Config.Version = EditorPrefs.GetString(UnityProjectID+"DoxyProjectNumber");
Config.Synopsis = EditorPrefs.GetString(UnityProjectID+"DoxyProjectBrief");
Config.DocDirectory = EditorPrefs.GetString(UnityProjectID+"DoxyProjectOutput");
Config.ScriptsDirectory = EditorPrefs.GetString(UnityProjectID+"DoxyProjectFolder");
return true;
}
return false;
}
public static void OnDoxygenFinished(int code) {
if(code != 0) {
UnityEngine.Debug.LogError("Doxygen finsished with Error: return code " + code +"\nCheck the Doxgen Log for Errors.\nAlso try regenerating your Doxyfile,\nyou will new to close and reopen the\ndocumentation window before regenerating.");
}
}
void SetTheme(int theme) {
switch(theme) {
case 1:
FileUtil.ReplaceFile(AssestsFolder + "/External Libraries/UnityUtilLib/Editor/Doxygen/Resources/DarkTheme/doxygen.css", Config.DocDirectory+"/html/doxygen.css");
FileUtil.ReplaceFile(AssestsFolder + "/External Libraries/UnityUtilLib/Editor/Doxygen/Resources/DarkTheme/tabs.css", Config.DocDirectory+"/html/tabs.css");
FileUtil.ReplaceFile(AssestsFolder + "/External Libraries/UnityUtilLib/Editor/Doxygen/Resources/DarkTheme/img_downArrow.png", Config.DocDirectory+"/html/img_downArrow.png");
break;
case 2:
FileUtil.ReplaceFile(AssestsFolder + "/External Libraries/UnityUtilLib/Editor/Doxygen/Resources/LightTheme/doxygen.css", Config.DocDirectory+"/html/doxygen.css");
FileUtil.ReplaceFile(AssestsFolder + "/External Libraries/UnityUtilLib/Editor/Doxygen/Resources/LightTheme/tabs.css", Config.DocDirectory+"/html/tabs.css");
FileUtil.ReplaceFile(AssestsFolder + "/External Libraries/UnityUtilLib/Editor/Doxygen/Resources/LightTheme/img_downArrow.png", Config.DocDirectory+"/html/img_downArrow.png");
FileUtil.ReplaceFile(AssestsFolder + "/External Libraries/UnityUtilLib/Editor/Doxygen/Resources/LightTheme/background_navigation.png", Config.DocDirectory+"/html/background_navigation.png");
break;
}
}
public void RunDoxygen() {
string[] Args = new string[1];
Args[0] = Config.DocDirectory + "/Doxyfile";
DoxygenOutput = new DoxyThreadSafeOutput();
DoxygenOutput.SetStarted();
Action<int> setcallback = (int returnCode) => OnDoxygenFinished(returnCode);
DoxyRunner Doxygen = new DoxyRunner(Config.PathtoDoxygen,Args,DoxygenOutput,setcallback);
Thread DoxygenThread = new Thread(new ThreadStart(Doxygen.RunThreadedDoxy));
DoxygenThread.Start();
}
}
/// <summary>
/// This class spawns and runs Doxygen in a separate thread, and could serve as an example of how to create
/// plugins for unity that call a command line application and then get the data back into Unity safely.
/// </summary>
internal class DoxyRunner
{
DoxyThreadSafeOutput SafeOutput;
public Action<int> onCompleteCallBack;
List<string> DoxyLog = new List<string>();
public string EXE = null;
public string[] Args;
static string WorkingFolder;
public DoxyRunner(string exepath, string[] args,DoxyThreadSafeOutput safeoutput,Action<int> callback)
{
EXE = exepath;
Args = args;
SafeOutput = safeoutput;
onCompleteCallBack = callback;
WorkingFolder = FileUtil.GetUniqueTempPathInProject();
System.IO.Directory.CreateDirectory(WorkingFolder);
}
public void updateOuputString(string output)
{
SafeOutput.WriteLine(output);
DoxyLog.Add(output);
}
public void RunThreadedDoxy()
{
Action<string> GetOutput = (string output) => updateOuputString(output);
int ReturnCode = Run(GetOutput,null,EXE,Args);
SafeOutput.WriteFullLog(DoxyLog);
SafeOutput.SetFinished();
onCompleteCallBack(ReturnCode);
}
/// <summary>
/// Runs the specified executable with the provided arguments and returns the process' exit code.
/// </summary>
/// <param name="output">Recieves the output of either std/err or std/out</param>
/// <param name="input">Provides the line-by-line input that will be written to std/in, null for empty</param>
/// <param name="exe">The executable to run, may be unqualified or contain environment variables</param>
/// <param name="args">The list of unescaped arguments to provide to the executable</param>
/// <returns>Returns process' exit code after the program exits</returns>
/// <exception cref="System.IO.FileNotFoundException">Raised when the exe was not found</exception>
/// <exception cref="System.ArgumentNullException">Raised when one of the arguments is null</exception>
/// <exception cref="System.ArgumentOutOfRangeException">Raised if an argument contains '\0', '\r', or '\n'
public static int Run(Action<string> output, TextReader input, string exe, params string[] args)
{
if (String.IsNullOrEmpty(exe))
throw new FileNotFoundException();
if (output == null)
throw new ArgumentNullException("output");
ProcessStartInfo psi = new ProcessStartInfo();
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.CreateNoWindow = true;
psi.ErrorDialog = false;
psi.WorkingDirectory = WorkingFolder;
psi.FileName = FindExePath(exe);
psi.Arguments = EscapeArguments(args);
using (Process process = Process.Start(psi))
using (ManualResetEvent mreOut = new ManualResetEvent(false),
mreErr = new ManualResetEvent(false))
{
process.OutputDataReceived += (o, e) => { if (e.Data == null) mreOut.Set(); else output(e.Data); };
process.BeginOutputReadLine();
process.ErrorDataReceived += (o, e) => { if (e.Data == null) mreErr.Set(); else output(e.Data); };
process.BeginErrorReadLine();
string line;
while (input != null && null != (line = input.ReadLine()))
process.StandardInput.WriteLine(line);
process.StandardInput.Close();
process.WaitForExit();
mreOut.WaitOne();
mreErr.WaitOne();
return process.ExitCode;
}
}
/// <summary>
/// Quotes all arguments that contain whitespace, or begin with a quote and returns a single
/// argument string for use with Process.Start().
/// </summary>
/// <param name="args">A list of strings for arguments, may not contain null, '\0', '\r', or '\n'</param>
/// <returns>The combined list of escaped/quoted strings</returns>
/// <exception cref="System.ArgumentNullException">Raised when one of the arguments is null</exception>
/// <exception cref="System.ArgumentOutOfRangeException">Raised if an argument contains '\0', '\r', or '\n'</exception>
public static string EscapeArguments(params string[] args)
{
StringBuilder arguments = new StringBuilder();
Regex invalidChar = new Regex("[\x00\x0a\x0d]");// these can not be escaped
Regex needsQuotes = new Regex(@"\s|""");// contains whitespace or two quote characters
Regex escapeQuote = new Regex(@"(\\*)(""|$)");// one or more '\' followed with a quote or end of string
for (int carg = 0; args != null && carg < args.Length; carg++)
{
if (args[carg] == null)
{
throw new ArgumentNullException("args[" + carg + "]");
}
if (invalidChar.IsMatch(args[carg]))
{
throw new ArgumentOutOfRangeException("args[" + carg + "]");
}
if (args[carg] == String.Empty)
{
arguments.Append("\"\"");
}
else if (!needsQuotes.IsMatch(args[carg]))
{
arguments.Append(args[carg]);
}
else
{
arguments.Append('"');
arguments.Append(escapeQuote.Replace(args[carg], m =>
m.Groups[1].Value + m.Groups[1].Value +
(m.Groups[2].Value == "\"" ? "\\\"" : "")
));
arguments.Append('"');
}
if (carg + 1 < args.Length)
arguments.Append(' ');
}
return arguments.ToString();
}
/// <summary>
/// Expands environment variables and, if unqualified, locates the exe in the working directory
/// or the evironment's path.
/// </summary>
/// <param name="exe">The name of the executable file</param>
/// <returns>The fully-qualified path to the file</returns>
/// <exception cref="System.IO.FileNotFoundException">Raised when the exe was not found</exception>
public static string FindExePath(string exe)
{
exe = Environment.ExpandEnvironmentVariables(exe);
if (!File.Exists(exe))
{
if (Path.GetDirectoryName(exe) == String.Empty)
{
foreach (string test in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(';'))
{
string path = test.Trim();
if (!String.IsNullOrEmpty(path) && File.Exists(path = Path.Combine(path, exe)))
return Path.GetFullPath(path);
}
}
throw new FileNotFoundException(new FileNotFoundException().Message, exe);
}
return Path.GetFullPath(exe);
}
}
/// <summary>
/// This class encapsulates the data output by Doxygen so it can be shared with Unity in a thread share way.
/// </summary>
internal class DoxyThreadSafeOutput
{
private ReaderWriterLockSlim outputLock = new ReaderWriterLockSlim();
private string CurrentOutput = "";
private List<string> FullLog = new List<string>();
private bool Finished = false;
private bool Started = false;
public string ReadLine( )
{
outputLock.EnterReadLock();
try
{
return CurrentOutput;
}
finally
{
outputLock.ExitReadLock();
}
}
public void SetFinished( )
{
outputLock.EnterWriteLock();
try
{
Finished = true;
}
finally
{
outputLock.ExitWriteLock();
}
}
public void SetStarted( )
{
outputLock.EnterWriteLock();
try
{
Started = true;
}
finally
{
outputLock.ExitWriteLock();
}
}
public bool isStarted( )
{
outputLock.EnterReadLock();
try
{
return Started;
}
finally
{
outputLock.ExitReadLock();
}
}
public bool isFinished( )
{
outputLock.EnterReadLock();
try
{
return Finished;
}
finally
{
outputLock.ExitReadLock();
}
}
public List<string> ReadFullLog()
{
outputLock.EnterReadLock();
try
{
return FullLog;
}
finally
{
outputLock.ExitReadLock();
}
}
public void WriteFullLog(List<string> newLog)
{
outputLock.EnterWriteLock();
try
{
FullLog = newLog;
}
finally
{
outputLock.ExitWriteLock();
}
}
public void WriteLine(string newOutput)
{
outputLock.EnterWriteLock();
try
{
CurrentOutput = newOutput;
}
finally
{
outputLock.ExitWriteLock();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using JCG = J2N.Collections.Generic;
using Console = YAF.Lucene.Net.Util.SystemConsole;
namespace YAF.Lucene.Net.Store
{
/*
* 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 IndexFileNames = YAF.Lucene.Net.Index.IndexFileNames;
using IOUtils = YAF.Lucene.Net.Util.IOUtils;
// TODO
// - let subclass dictate policy...?
// - rename to MergeCacheingDir? NRTCachingDir
// :Post-Release-Update-Version.LUCENE_XY: (in <pre> block in javadoc below)
/// <summary>
/// Wraps a <see cref="RAMDirectory"/>
/// around any provided delegate directory, to
/// be used during NRT search.
///
/// <para>This class is likely only useful in a near-real-time
/// context, where indexing rate is lowish but reopen
/// rate is highish, resulting in many tiny files being
/// written. This directory keeps such segments (as well as
/// the segments produced by merging them, as long as they
/// are small enough), in RAM.</para>
///
/// <para>This is safe to use: when your app calls <see cref="Index.IndexWriter.Commit()"/>,
/// all cached files will be flushed from the cached and sync'd.</para>
///
/// <para/>Here's a simple example usage:
///
/// <code>
/// Directory fsDir = FSDirectory.Open(new DirectoryInfo("/path/to/index"));
/// NRTCachingDirectory cachedFSDir = new NRTCachingDirectory(fsDir, 5.0, 60.0);
/// IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_48, analyzer);
/// IndexWriter writer = new IndexWriter(cachedFSDir, conf);
/// </code>
///
/// <para>This will cache all newly flushed segments, all merges
/// whose expected segment size is <= 5 MB, unless the net
/// cached bytes exceeds 60 MB at which point all writes will
/// not be cached (until the net bytes falls below 60 MB).</para>
/// <para/>
/// @lucene.experimental
/// </summary>
public class NRTCachingDirectory : Directory
{
private readonly RAMDirectory cache = new RAMDirectory();
private readonly Directory @delegate;
private readonly long maxMergeSizeBytes;
private readonly long maxCachedBytes;
private static bool VERBOSE = false;
/// <summary>
/// We will cache a newly created output if 1) it's a
/// flush or a merge and the estimated size of the merged segment is <=
/// maxMergeSizeMB, and 2) the total cached bytes is <=
/// maxCachedMB
/// </summary>
public NRTCachingDirectory(Directory @delegate, double maxMergeSizeMB, double maxCachedMB)
{
this.@delegate = @delegate;
maxMergeSizeBytes = (long)(maxMergeSizeMB * 1024 * 1024);
maxCachedBytes = (long)(maxCachedMB * 1024 * 1024);
}
public virtual Directory Delegate
{
get
{
return @delegate;
}
}
public override LockFactory LockFactory
{
get
{
return @delegate.LockFactory;
}
}
public override void SetLockFactory(LockFactory lockFactory)
{
@delegate.SetLockFactory(lockFactory);
}
public override string GetLockID()
{
return @delegate.GetLockID();
}
public override Lock MakeLock(string name)
{
return @delegate.MakeLock(name);
}
public override void ClearLock(string name)
{
@delegate.ClearLock(name);
}
public override string ToString()
{
return "NRTCachingDirectory(" + @delegate + "; maxCacheMB=" + (maxCachedBytes / 1024 / 1024.0) + " maxMergeSizeMB=" + (maxMergeSizeBytes / 1024 / 1024.0) + ")";
}
public override string[] ListAll()
{
lock (this)
{
ISet<string> files = new JCG.HashSet<string>();
foreach (string f in cache.ListAll())
{
files.Add(f);
}
// LUCENE-1468: our NRTCachingDirectory will actually exist (RAMDir!),
// but if the underlying delegate is an FSDir and mkdirs() has not
// yet been called, because so far everything is a cached write,
// in this case, we don't want to throw a NoSuchDirectoryException
try
{
foreach (string f in @delegate.ListAll())
{
// Cannot do this -- if lucene calls createOutput but
// file already exists then this falsely trips:
//assert !files.contains(f): "file \"" + f + "\" is in both dirs";
files.Add(f);
}
}
catch (DirectoryNotFoundException /*ex*/)
{
// however, if there are no cached files, then the directory truly
// does not "exist"
if (files.Count == 0)
{
throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
}
}
return files.ToArray();
}
}
/// <summary>
/// Returns how many bytes are being used by the
/// <see cref="RAMDirectory"/> cache
/// </summary>
public virtual long GetSizeInBytes()
{
return cache.GetSizeInBytes();
}
[Obsolete("this method will be removed in 5.0")]
public override bool FileExists(string name)
{
lock (this)
{
return cache.FileExists(name) || @delegate.FileExists(name);
}
}
public override void DeleteFile(string name)
{
lock (this)
{
if (VERBOSE)
{
Console.WriteLine("nrtdir.deleteFile name=" + name);
}
#pragma warning disable 612, 618
if (cache.FileExists(name))
#pragma warning restore 612, 618
{
cache.DeleteFile(name);
}
else
{
@delegate.DeleteFile(name);
}
}
}
public override long FileLength(string name)
{
lock (this)
{
#pragma warning disable 612, 618
if (cache.FileExists(name))
#pragma warning restore 612, 618
{
return cache.FileLength(name);
}
else
{
return @delegate.FileLength(name);
}
}
}
public virtual string[] ListCachedFiles()
{
return cache.ListAll();
}
public override IndexOutput CreateOutput(string name, IOContext context)
{
if (VERBOSE)
{
Console.WriteLine("nrtdir.createOutput name=" + name);
}
if (DoCacheWrite(name, context))
{
if (VERBOSE)
{
Console.WriteLine(" to cache");
}
try
{
@delegate.DeleteFile(name);
}
#pragma warning disable 168
catch (IOException ioe)
#pragma warning restore 168
{
// this is fine: file may not exist
}
return cache.CreateOutput(name, context);
}
else
{
try
{
cache.DeleteFile(name);
}
#pragma warning disable 168
catch (IOException ioe)
#pragma warning restore 168
{
// this is fine: file may not exist
}
return @delegate.CreateOutput(name, context);
}
}
public override void Sync(ICollection<string> fileNames)
{
if (VERBOSE)
{
Console.WriteLine("nrtdir.sync files=" + fileNames);
}
foreach (string fileName in fileNames)
{
UnCache(fileName);
}
@delegate.Sync(fileNames);
}
public override IndexInput OpenInput(string name, IOContext context)
{
lock (this)
{
if (VERBOSE)
{
Console.WriteLine("nrtdir.openInput name=" + name);
}
#pragma warning disable 612, 618
if (cache.FileExists(name))
#pragma warning restore 612, 618
{
if (VERBOSE)
{
Console.WriteLine(" from cache");
}
return cache.OpenInput(name, context);
}
else
{
return @delegate.OpenInput(name, context);
}
}
}
public override IndexInputSlicer CreateSlicer(string name, IOContext context)
{
lock (this)
{
EnsureOpen();
if (VERBOSE)
{
Console.WriteLine("nrtdir.openInput name=" + name);
}
#pragma warning disable 612, 618
if (cache.FileExists(name))
#pragma warning restore 612, 618
{
if (VERBOSE)
{
Console.WriteLine(" from cache");
}
return cache.CreateSlicer(name, context);
}
else
{
return @delegate.CreateSlicer(name, context);
}
}
}
/// <summary>
/// Dispose this directory, which flushes any cached files
/// to the delegate and then disposes the delegate.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
// NOTE: technically we shouldn't have to do this, ie,
// IndexWriter should have sync'd all files, but we do
// it for defensive reasons... or in case the app is
// doing something custom (creating outputs directly w/o
// using IndexWriter):
foreach (string fileName in cache.ListAll())
{
UnCache(fileName);
}
cache.Dispose();
@delegate.Dispose();
}
}
/// <summary>
/// Subclass can override this to customize logic; return
/// <c>true</c> if this file should be written to the <see cref="RAMDirectory"/>.
/// </summary>
protected virtual bool DoCacheWrite(string name, IOContext context)
{
//System.out.println(Thread.currentThread().getName() + ": CACHE check merge=" + merge + " size=" + (merge==null ? 0 : merge.estimatedMergeBytes));
long bytes = 0;
if (context.MergeInfo != null)
{
bytes = context.MergeInfo.EstimatedMergeBytes;
}
else if (context.FlushInfo != null)
{
bytes = context.FlushInfo.EstimatedSegmentSize;
}
return !name.Equals(IndexFileNames.SEGMENTS_GEN, StringComparison.Ordinal) && (bytes <= maxMergeSizeBytes) && (bytes + cache.GetSizeInBytes()) <= maxCachedBytes;
}
private readonly object uncacheLock = new object();
private void UnCache(string fileName)
{
// Only let one thread uncache at a time; this only
// happens during commit() or close():
lock (uncacheLock)
{
if (VERBOSE)
{
Console.WriteLine("nrtdir.unCache name=" + fileName);
}
#pragma warning disable 612, 618
if (!cache.FileExists(fileName))
#pragma warning restore 612, 618
{
// Another thread beat us...
return;
}
IOContext context = IOContext.DEFAULT;
IndexOutput @out = @delegate.CreateOutput(fileName, context);
IndexInput @in = null;
try
{
@in = cache.OpenInput(fileName, context);
@out.CopyBytes(@in, @in.Length);
}
finally
{
IOUtils.Dispose(@in, @out);
}
// Lock order: uncacheLock -> this
lock (this)
{
// Must sync here because other sync methods have
// if (cache.fileExists(name)) { ... } else { ... }:
cache.DeleteFile(fileName);
}
}
}
}
}
| |
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using ByteMatrix = com.google.zxing.common.ByteMatrix;
using ErrorCorrectionLevel = com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
using Mode = com.google.zxing.qrcode.decoder.Mode;
namespace com.google.zxing.qrcode.encoder
{
/// <author> [email protected] (Satoru Takabayashi) - creator
/// </author>
/// <author> [email protected] (Daniel Switkin) - ported from C++
/// </author>
/// <author>www.Redivivus.in ([email protected]) - Ported from ZXING Java Source
/// </author>
public sealed class QRCode
{
public Mode Mode
{
// Mode of the QR Code.
get
{
return mode;
}
set
{
mode = value;
}
}
public ErrorCorrectionLevel ECLevel
{
// Error correction level of the QR Code.
get
{
return ecLevel;
}
set
{
ecLevel = value;
}
}
public int Version
{
// Version of the QR Code. The bigger size, the bigger version.
get
{
return version;
}
set
{
version = value;
}
}
public int MatrixWidth
{
// ByteMatrix width of the QR Code.
get
{
return matrixWidth;
}
set
{
matrixWidth = value;
}
}
public int MaskPattern
{
// Mask pattern of the QR Code.
get
{
return maskPattern;
}
set
{
maskPattern = value;
}
}
public int NumTotalBytes
{
// Number of total bytes in the QR Code.
get
{
return numTotalBytes;
}
set
{
numTotalBytes = value;
}
}
public int NumDataBytes
{
// Number of data bytes in the QR Code.
get
{
return numDataBytes;
}
set
{
numDataBytes = value;
}
}
public int NumECBytes
{
// Number of error correction bytes in the QR Code.
get
{
return numECBytes;
}
set
{
numECBytes = value;
}
}
public int NumRSBlocks
{
// Number of Reedsolomon blocks in the QR Code.
get
{
return numRSBlocks;
}
set
{
numRSBlocks = value;
}
}
public ByteMatrix Matrix
{
// ByteMatrix data of the QR Code.
get
{
return matrix;
}
// This takes ownership of the 2D array.
set
{
matrix = value;
}
}
public bool Valid
{
// Checks all the member variables are set properly. Returns true on success. Otherwise, returns
// false.
get
{
return mode != null && ecLevel != null && version != - 1 && matrixWidth != - 1 && maskPattern != - 1 && numTotalBytes != - 1 && numDataBytes != - 1 && numECBytes != - 1 && numRSBlocks != - 1 && isValidMaskPattern(maskPattern) && numTotalBytes == numDataBytes + numECBytes && matrix != null && matrixWidth == matrix.Width && matrix.Width == matrix.Height; // Must be square.
}
}
public const int NUM_MASK_PATTERNS = 8;
private Mode mode;
private ErrorCorrectionLevel ecLevel;
private int version;
private int matrixWidth;
private int maskPattern;
private int numTotalBytes;
private int numDataBytes;
private int numECBytes;
private int numRSBlocks;
private ByteMatrix matrix;
public QRCode()
{
mode = null;
ecLevel = null;
version = - 1;
matrixWidth = - 1;
maskPattern = - 1;
numTotalBytes = - 1;
numDataBytes = - 1;
numECBytes = - 1;
numRSBlocks = - 1;
matrix = null;
}
// Return the value of the module (cell) pointed by "x" and "y" in the matrix of the QR Code. They
// call cells in the matrix "modules". 1 represents a black cell, and 0 represents a white cell.
public int at(int x, int y)
{
// The value must be zero or one.
int value_Renamed = matrix.get_Renamed(x, y);
if (!(value_Renamed == 0 || value_Renamed == 1))
{
// this is really like an assert... not sure what better exception to use?
throw new System.SystemException("Bad value");
}
return value_Renamed;
}
// Return debug String.
public override System.String ToString()
{
System.Text.StringBuilder result = new System.Text.StringBuilder(200);
result.Append("<<\n");
result.Append(" mode: ");
result.Append(mode);
result.Append("\n ecLevel: ");
result.Append(ecLevel);
result.Append("\n version: ");
result.Append(version);
result.Append("\n matrixWidth: ");
result.Append(matrixWidth);
result.Append("\n maskPattern: ");
result.Append(maskPattern);
result.Append("\n numTotalBytes: ");
result.Append(numTotalBytes);
result.Append("\n numDataBytes: ");
result.Append(numDataBytes);
result.Append("\n numECBytes: ");
result.Append(numECBytes);
result.Append("\n numRSBlocks: ");
result.Append(numRSBlocks);
if (matrix == null)
{
result.Append("\n matrix: null\n");
}
else
{
result.Append("\n matrix:\n");
result.Append(matrix.ToString());
}
result.Append(">>\n");
return result.ToString();
}
// Check if "mask_pattern" is valid.
public static bool isValidMaskPattern(int maskPattern)
{
return maskPattern >= 0 && maskPattern < NUM_MASK_PATTERNS;
}
// Return true if the all values in the matrix are binary numbers.
//
// JAVAPORT: This is going to be super expensive and unnecessary, we should not call this in
// production. I'm leaving it because it may be useful for testing. It should be removed entirely
// if ByteMatrix is changed never to contain a -1.
/*
private static boolean EverythingIsBinary(final ByteMatrix matrix) {
for (int y = 0; y < matrix.height(); ++y) {
for (int x = 0; x < matrix.width(); ++x) {
int value = matrix.get(y, x);
if (!(value == 0 || value == 1)) {
// Found non zero/one value.
return false;
}
}
}
return true;
}
*/
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.Store;
using Microsoft.WindowsAzure.Management.Store.Models;
namespace Microsoft.WindowsAzure.Management.Store
{
/// <summary>
/// Provides REST operations for working with Store add-ins from the
/// Windows Azure store service.
/// </summary>
internal partial class AddOnOperations : IServiceOperations<StoreManagementClient>, IAddOnOperations
{
/// <summary>
/// Initializes a new instance of the AddOnOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal AddOnOperations(StoreManagementClient client)
{
this._client = client;
}
private StoreManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Store.StoreManagementClient.
/// </summary>
public StoreManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// The Create Store Item operation creates Windows Azure Store entries
/// in a Windows Azure subscription.
/// </summary>
/// <param name='cloudServiceName'>
/// The name of the cloud service to which this store item will be
/// assigned.
/// </param>
/// <param name='resourceName'>
/// The name of this resource.
/// </param>
/// <param name='addOnName'>
/// The add on name.
/// </param>
/// <param name='parameters'>
/// Parameters used to specify how the Create procedure will function.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<AddOnOperationStatusResponse> BeginCreatingAsync(string cloudServiceName, string resourceName, string addOnName, AddOnCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
if (addOnName == null)
{
throw new ArgumentNullException("addOnName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Plan == null)
{
throw new ArgumentNullException("parameters.Plan");
}
if (parameters.Type == null)
{
throw new ArgumentNullException("parameters.Type");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("resourceName", resourceName);
tracingParameters.Add("addOnName", addOnName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "BeginCreatingAsync", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/CloudServices/" + cloudServiceName + "/resources/" + parameters.Type + "/" + resourceName + "/" + addOnName;
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2013-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement resourceElement = new XElement(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(resourceElement);
XElement typeElement = new XElement(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
typeElement.Value = parameters.Type;
resourceElement.Add(typeElement);
XElement planElement = new XElement(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure"));
planElement.Value = parameters.Plan;
resourceElement.Add(planElement);
if (parameters.PromotionCode != null)
{
XElement promotionCodeElement = new XElement(XName.Get("PromotionCode", "http://schemas.microsoft.com/windowsazure"));
promotionCodeElement.Value = parameters.PromotionCode;
resourceElement.Add(promotionCodeElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml);
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AddOnOperationStatusResponse result = null;
result = new AddOnOperationStatusResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Delete Store Item operation deletes Windows Azure Store entries
/// that re provisioned for a subscription.
/// </summary>
/// <param name='cloudServiceName'>
/// The name of the cloud service to which this store item will be
/// assigned.
/// </param>
/// <param name='resourceProviderNamespace'>
/// The namespace in which this store item resides.
/// </param>
/// <param name='resourceProviderType'>
/// The type of store item to be deleted.
/// </param>
/// <param name='resourceProviderName'>
/// The name of this resource provider.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<AddOnOperationStatusResponse> BeginDeletingAsync(string cloudServiceName, string resourceProviderNamespace, string resourceProviderType, string resourceProviderName, CancellationToken cancellationToken)
{
// Validate
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (resourceProviderNamespace == null)
{
throw new ArgumentNullException("resourceProviderNamespace");
}
if (resourceProviderType == null)
{
throw new ArgumentNullException("resourceProviderType");
}
if (resourceProviderName == null)
{
throw new ArgumentNullException("resourceProviderName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace);
tracingParameters.Add("resourceProviderType", resourceProviderType);
tracingParameters.Add("resourceProviderName", resourceProviderName);
Tracing.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/CloudServices/" + cloudServiceName + "/resources/" + resourceProviderNamespace + "/" + resourceProviderType + "/" + resourceProviderName;
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2013-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml);
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AddOnOperationStatusResponse result = null;
result = new AddOnOperationStatusResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Create Store Item operation creates Windows Azure Store entries
/// in a Windows Azure subscription.
/// </summary>
/// <param name='cloudServiceName'>
/// The name of the cloud service to which this store item will be
/// assigned.
/// </param>
/// <param name='resourceName'>
/// The name of this resource.
/// </param>
/// <param name='addOnName'>
/// The add on name.
/// </param>
/// <param name='parameters'>
/// Parameters used to specify how the Create procedure will function.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<AddOnOperationStatusResponse> CreateAsync(string cloudServiceName, string resourceName, string addOnName, AddOnCreateParameters parameters, CancellationToken cancellationToken)
{
StoreManagementClient client = this.Client;
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("resourceName", resourceName);
tracingParameters.Add("addOnName", addOnName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
try
{
if (shouldTrace)
{
client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
}
cancellationToken.ThrowIfCancellationRequested();
AddOnOperationStatusResponse response = await client.AddOns.BeginCreatingAsync(cloudServiceName, resourceName, addOnName, parameters, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
AddOnOperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
while ((result.Status != OperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.ErrorCode = result.Error.Code;
ex.ErrorMessage = result.Error.Message;
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
return result;
}
finally
{
if (client != null && shouldTrace)
{
client.Dispose();
}
}
}
/// <summary>
/// The Delete Store Item operation deletes Windows Azure Storeentries
/// that are provisioned for a subscription.
/// </summary>
/// <param name='cloudServiceName'>
/// The name of the cloud service to which this store item will be
/// assigned.
/// </param>
/// <param name='resourceProviderNamespace'>
/// The namespace in which this store item resides.
/// </param>
/// <param name='resourceProviderType'>
/// The type of store item to be deleted.
/// </param>
/// <param name='resourceProviderName'>
/// The name of this resource provider.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<AddOnOperationStatusResponse> DeleteAsync(string cloudServiceName, string resourceProviderNamespace, string resourceProviderType, string resourceProviderName, CancellationToken cancellationToken)
{
StoreManagementClient client = this.Client;
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace);
tracingParameters.Add("resourceProviderType", resourceProviderType);
tracingParameters.Add("resourceProviderName", resourceProviderName);
Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
try
{
if (shouldTrace)
{
client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
}
cancellationToken.ThrowIfCancellationRequested();
AddOnOperationStatusResponse response = await client.AddOns.BeginDeletingAsync(cloudServiceName, resourceProviderNamespace, resourceProviderType, resourceProviderName, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
AddOnOperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
while ((result.Status != OperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.ErrorCode = result.Error.Code;
ex.ErrorMessage = result.Error.Message;
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
return result;
}
finally
{
if (client != null && shouldTrace)
{
client.Dispose();
}
}
}
/// <summary>
/// The Update Store Item operation creates Windows Azure Store entries
/// in a Windows Azure subscription.
/// </summary>
/// <param name='cloudServiceName'>
/// The name of the cloud service to which this store item will be
/// assigned.
/// </param>
/// <param name='resourceName'>
/// The name of this resource.
/// </param>
/// <param name='addOnName'>
/// The addon name.
/// </param>
/// <param name='parameters'>
/// Parameters used to specify how the Create procedure will function.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<AddOnOperationStatusResponse> UpdateAsync(string cloudServiceName, string resourceName, string addOnName, AddOnUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
if (addOnName == null)
{
throw new ArgumentNullException("addOnName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Plan == null)
{
throw new ArgumentNullException("parameters.Plan");
}
if (parameters.Type == null)
{
throw new ArgumentNullException("parameters.Type");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("resourceName", resourceName);
tracingParameters.Add("addOnName", addOnName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "UpdateAsync", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/CloudServices/" + cloudServiceName + "/resources/" + parameters.Type + "/" + resourceName + "/" + addOnName;
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("If-Match", "*");
httpRequest.Headers.Add("x-ms-version", "2013-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement resourceElement = new XElement(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(resourceElement);
XElement typeElement = new XElement(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
typeElement.Value = parameters.Type;
resourceElement.Add(typeElement);
XElement planElement = new XElement(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure"));
planElement.Value = parameters.Plan;
resourceElement.Add(planElement);
if (parameters.PromotionCode != null)
{
XElement promotionCodeElement = new XElement(XName.Get("PromotionCode", "http://schemas.microsoft.com/windowsazure"));
promotionCodeElement.Value = parameters.PromotionCode;
resourceElement.Add(promotionCodeElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml);
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AddOnOperationStatusResponse result = null;
result = new AddOnOperationStatusResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// 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.
/*============================================================
**
**
**
** Implementation details of CLR Contracts.
**
===========================================================*/
#define DEBUG // The behavior of this contract library should be consistent regardless of build type.
#if SILVERLIGHT
#define FEATURE_UNTRUSTED_CALLERS
#elif REDHAWK_RUNTIME
#elif BARTOK_RUNTIME
#else // CLR
#define FEATURE_UNTRUSTED_CALLERS
#define FEATURE_RELIABILITY_CONTRACTS
#endif
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Reflection;
#if FEATURE_RELIABILITY_CONTRACTS
using System.Runtime.ConstrainedExecution;
#endif
#if FEATURE_UNTRUSTED_CALLERS
using System.Security;
#endif
namespace System.Diagnostics.Contracts
{
public static partial class Contract
{
#region Private Methods
[ThreadStatic]
private static bool _assertingMustUseRewriter;
/// <summary>
/// This method is used internally to trigger a failure indicating to the "programmer" that he is using the interface incorrectly.
/// It is NEVER used to indicate failure of actual contracts at runtime.
/// </summary>
static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind)
{
if (_assertingMustUseRewriter)
System.Diagnostics.Assert.Fail("Asserting that we must use the rewriter went reentrant.", "Didn't rewrite this mscorlib?");
_assertingMustUseRewriter = true;
// For better diagnostics, report which assembly is at fault. Walk up stack and
// find the first non-mscorlib assembly.
Assembly thisAssembly = typeof(Contract).Assembly; // In case we refactor mscorlib, use Contract class instead of Object.
StackTrace stack = new StackTrace();
Assembly probablyNotRewritten = null;
for (int i = 0; i < stack.FrameCount; i++)
{
Assembly caller = stack.GetFrame(i).GetMethod().DeclaringType.Assembly;
if (caller != thisAssembly)
{
probablyNotRewritten = caller;
break;
}
}
if (probablyNotRewritten == null)
probablyNotRewritten = thisAssembly;
String simpleName = probablyNotRewritten.GetName().Name;
System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, SR.Format(SR.MustUseCCRewrite, contractKind, simpleName), null, null, null);
_assertingMustUseRewriter = false;
}
#endregion Private Methods
#region Failure Behavior
/// <summary>
/// Without contract rewriting, failing Assert/Assumes end up calling this method.
/// Code going through the contract rewriter never calls this method. Instead, the rewriter produced failures call
/// System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent, followed by
/// System.Runtime.CompilerServices.ContractHelper.TriggerFailure.
/// </summary>
[SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework", MessageId = "System.Security.SecuritySafeCriticalAttribute")]
[System.Diagnostics.DebuggerNonUserCode]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
static partial void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException)
{
if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume)
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind));
Contract.EndContractBlock();
// displayMessage == null means: yes we handled it. Otherwise it is the localized failure message
var displayMessage = System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException);
if (displayMessage == null) return;
System.Runtime.CompilerServices.ContractHelper.TriggerFailure(failureKind, displayMessage, userMessage, conditionText, innerException);
}
/// <summary>
/// Allows a managed application environment such as an interactive interpreter (IronPython)
/// to be notified of contract failures and
/// potentially "handle" them, either by throwing a particular exception type, etc. If any of the
/// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will
/// not pop up an assert dialog box or trigger escalation policy. Hooking this event requires
/// full trust, because it will inform you of bugs in the appdomain and because the event handler
/// could allow you to continue execution.
/// </summary>
public static event EventHandler<ContractFailedEventArgs> ContractFailed
{
#if FEATURE_UNTRUSTED_CALLERS
#endif
add
{
System.Runtime.CompilerServices.ContractHelper.InternalContractFailed += value;
}
#if FEATURE_UNTRUSTED_CALLERS
#endif
remove
{
System.Runtime.CompilerServices.ContractHelper.InternalContractFailed -= value;
}
}
#endregion FailureBehavior
}
public sealed class ContractFailedEventArgs : EventArgs
{
private ContractFailureKind _failureKind;
private String _message;
private String _condition;
private Exception _originalException;
private bool _handled;
private bool _unwind;
internal Exception thrownDuringHandler;
#if FEATURE_RELIABILITY_CONTRACTS
#endif
public ContractFailedEventArgs(ContractFailureKind failureKind, String message, String condition, Exception originalException)
{
Contract.Requires(originalException == null || failureKind == ContractFailureKind.PostconditionOnException);
_failureKind = failureKind;
_message = message;
_condition = condition;
_originalException = originalException;
}
public String Message { get { return _message; } }
public String Condition { get { return _condition; } }
public ContractFailureKind FailureKind { get { return _failureKind; } }
public Exception OriginalException { get { return _originalException; } }
// Whether the event handler "handles" this contract failure, or to fail via escalation policy.
public bool Handled
{
get { return _handled; }
}
#if FEATURE_UNTRUSTED_CALLERS
#endif
public void SetHandled()
{
_handled = true;
}
public bool Unwind
{
get { return _unwind; }
}
#if FEATURE_UNTRUSTED_CALLERS
#endif
public void SetUnwind()
{
_unwind = true;
}
}
[Serializable]
[SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic")]
internal sealed class ContractException : Exception
{
private readonly ContractFailureKind _Kind;
private readonly string _UserMessage;
private readonly string _Condition;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public ContractFailureKind Kind { get { return _Kind; } }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string Failure { get { return this.Message; } }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string UserMessage { get { return _UserMessage; } }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string Condition { get { return _Condition; } }
// Called by COM Interop, if we see COR_E_CODECONTRACTFAILED as an HRESULT.
private ContractException()
{
HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED;
}
public ContractException(ContractFailureKind kind, string failure, string userMessage, string condition, Exception innerException)
: base(failure, innerException)
{
HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED;
_Kind = kind;
_UserMessage = userMessage;
_Condition = condition;
}
private ContractException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
_Kind = (ContractFailureKind)info.GetInt32("Kind");
_UserMessage = info.GetString("UserMessage");
_Condition = info.GetString("Condition");
}
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("Kind", _Kind);
info.AddValue("UserMessage", _UserMessage);
info.AddValue("Condition", _Condition);
}
}
}
namespace System.Runtime.CompilerServices
{
public static partial class ContractHelper
{
#region Private fields
private static volatile EventHandler<ContractFailedEventArgs> contractFailedEvent;
private static readonly Object lockObject = new Object();
internal const int COR_E_CODECONTRACTFAILED = unchecked((int)0x80131542);
#endregion
/// <summary>
/// Allows a managed application environment such as an interactive interpreter (IronPython) or a
/// web browser host (Jolt hosting Silverlight in IE) to be notified of contract failures and
/// potentially "handle" them, either by throwing a particular exception type, etc. If any of the
/// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will
/// not pop up an assert dialog box or trigger escalation policy. Hooking this event requires
/// full trust.
/// </summary>
internal static event EventHandler<ContractFailedEventArgs> InternalContractFailed
{
#if FEATURE_UNTRUSTED_CALLERS
#endif
add
{
// Eagerly prepare each event handler _marked with a reliability contract_, to
// attempt to reduce out of memory exceptions while reporting contract violations.
// This only works if the new handler obeys the constraints placed on
// constrained execution regions. Eagerly preparing non-reliable event handlers
// would be a perf hit and wouldn't significantly improve reliability.
// UE: Please mention reliable event handlers should also be marked with the
// PrePrepareMethodAttribute to avoid CER eager preparation work when ngen'ed.
System.Runtime.CompilerServices.RuntimeHelpers.PrepareContractedDelegate(value);
lock (lockObject)
{
contractFailedEvent += value;
}
}
#if FEATURE_UNTRUSTED_CALLERS
#endif
remove
{
lock (lockObject)
{
contractFailedEvent -= value;
}
}
}
/// <summary>
/// Rewriter will call this method on a contract failure to allow listeners to be notified.
/// The method should not perform any failure (assert/throw) itself.
/// This method has 3 functions:
/// 1. Call any contract hooks (such as listeners to Contract failed events)
/// 2. Determine if the listeneres deem the failure as handled (then resultFailureMessage should be set to null)
/// 3. Produce a localized resultFailureMessage used in advertising the failure subsequently.
/// </summary>
/// <param name="resultFailureMessage">Should really be out (or the return value), but partial methods are not flexible enough.
/// On exit: null if the event was handled and should not trigger a failure.
/// Otherwise, returns the localized failure message</param>
[SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[System.Diagnostics.DebuggerNonUserCode]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException, ref string resultFailureMessage)
{
if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume)
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind));
Contract.EndContractBlock();
string returnValue;
String displayMessage = "contract failed."; // Incomplete, but in case of OOM during resource lookup...
ContractFailedEventArgs eventArgs = null; // In case of OOM.
#if FEATURE_RELIABILITY_CONTRACTS
System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions();
#endif
try
{
displayMessage = GetDisplayMessage(failureKind, userMessage, conditionText);
EventHandler<ContractFailedEventArgs> contractFailedEventLocal = contractFailedEvent;
if (contractFailedEventLocal != null)
{
eventArgs = new ContractFailedEventArgs(failureKind, displayMessage, conditionText, innerException);
foreach (EventHandler<ContractFailedEventArgs> handler in contractFailedEventLocal.GetInvocationList())
{
try
{
handler(null, eventArgs);
}
catch (Exception e)
{
eventArgs.thrownDuringHandler = e;
eventArgs.SetUnwind();
}
}
if (eventArgs.Unwind)
{
// unwind
if (innerException == null) { innerException = eventArgs.thrownDuringHandler; }
throw new ContractException(failureKind, displayMessage, userMessage, conditionText, innerException);
}
}
}
finally
{
if (eventArgs != null && eventArgs.Handled)
{
returnValue = null; // handled
}
else
{
returnValue = displayMessage;
}
}
resultFailureMessage = returnValue;
}
/// <summary>
/// Rewriter calls this method to get the default failure behavior.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "conditionText")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "userMessage")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "kind")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "innerException")]
[System.Diagnostics.DebuggerNonUserCode]
static partial void TriggerFailureImplementation(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException)
{
// If we're here, our intent is to pop up a dialog box (if we can). For developers
// interacting live with a debugger, this is a good experience. For Silverlight
// hosted in Internet Explorer, the assert window is great. If we cannot
// pop up a dialog box, throw an exception (consider a library compiled with
// "Assert On Failure" but used in a process that can't pop up asserts, like an
// NT Service).
if (!Environment.UserInteractive)
{
throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException);
}
// May need to rethink Assert.Fail w/ TaskDialogIndirect as a model. Window title. Main instruction. Content. Expanded info.
// Optional info like string for collapsed text vs. expanded text.
String windowTitle = SR.GetResourceString(GetResourceNameForFailure(kind));
const int numStackFramesToSkip = 2; // To make stack traces easier to read
System.Diagnostics.Assert.Fail(conditionText, displayMessage, windowTitle, COR_E_CODECONTRACTFAILED, StackTrace.TraceFormat.Normal, numStackFramesToSkip);
// If we got here, the user selected Ignore. Continue.
}
private static String GetResourceNameForFailure(ContractFailureKind failureKind)
{
String resourceName = null;
switch (failureKind)
{
case ContractFailureKind.Assert:
resourceName = "AssertionFailed";
break;
case ContractFailureKind.Assume:
resourceName = "AssumptionFailed";
break;
case ContractFailureKind.Precondition:
resourceName = "PreconditionFailed";
break;
case ContractFailureKind.Postcondition:
resourceName = "PostconditionFailed";
break;
case ContractFailureKind.Invariant:
resourceName = "InvariantFailed";
break;
case ContractFailureKind.PostconditionOnException:
resourceName = "PostconditionOnExceptionFailed";
break;
default:
Contract.Assume(false, "Unreachable code");
resourceName = "AssumptionFailed";
break;
}
return resourceName;
}
#if FEATURE_RELIABILITY_CONTRACTS
#endif
private static String GetDisplayMessage(ContractFailureKind failureKind, String userMessage, String conditionText)
{
String resourceName = GetResourceNameForFailure(failureKind);
// Well-formatted English messages will take one of four forms. A sentence ending in
// either a period or a colon, the condition string, then the message tacked
// on to the end with two spaces in front.
// Note that both the conditionText and userMessage may be null. Also,
// on Silverlight we may not be able to look up a friendly string for the
// error message. Let's leverage Silverlight's default error message there.
String failureMessage;
if (!String.IsNullOrEmpty(conditionText))
{
resourceName += "_Cnd";
failureMessage = SR.Format(SR.GetResourceString(resourceName), conditionText);
}
else
{
failureMessage = SR.GetResourceString(resourceName);
}
// Now add in the user message, if present.
if (!String.IsNullOrEmpty(userMessage))
{
return failureMessage + " " + userMessage;
}
else
{
return failureMessage;
}
}
}
} // namespace System.Runtime.CompilerServices
| |
/******************************************************************************
* Spine Runtimes Software License
* Version 2.1
*
* Copyright (c) 2013, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable and
* non-transferable license to install, execute and perform the Spine Runtimes
* Software (the "Software") solely for internal use. Without the written
* permission of Esoteric Software (typically granted by licensing Spine), you
* may not (a) modify, translate, adapt or otherwise create derivative works,
* improvements of the Software or develop new applications using the Software
* or (b) remove, delete, alter or obscure any trademarks or any copyright,
* trademark, patent or other intellectual property or proprietary rights
* notices on or in the Software, including any copy thereof. Redistributions
* in binary or source form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL ESOTERIC SOFTARE 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.
*****************************************************************************/
/*****************************************************************************
* Skeleton Utility created by Mitch Thompson
* Full irrevocable rights and permissions granted to Esoteric Software
*****************************************************************************/
using System;
using System.IO;
using System.Collections.Generic;
using UnityEngine;
using Spine;
/// <summary>Sets a GameObject's transform to match a bone on a Spine skeleton.</summary>
[ExecuteInEditMode]
[AddComponentMenu("Spine/SkeletonUtilityBone")]
public class SkeletonUtilityBone : MonoBehaviour {
public enum Mode {
Follow,
Override
}
[System.NonSerialized]
public bool valid;
[System.NonSerialized]
public SkeletonUtility skeletonUtility;
[System.NonSerialized]
public Bone bone;
public Mode mode;
public bool zPosition = true;
public bool position;
public bool rotation;
public bool scale;
public bool flip;
public bool flipX;
[Range(0f,1f)]
public float overrideAlpha = 1;
/// <summary>If a bone isn't set, boneName is used to find the bone.</summary>
public String boneName;
public Transform parentReference;
[HideInInspector]
public bool transformLerpComplete;
protected Transform cachedTransform;
protected Transform skeletonTransform;
public bool NonUniformScaleWarning {
get {
return nonUniformScaleWarning;
}
}
private bool nonUniformScaleWarning;
public void Reset () {
bone = null;
cachedTransform = transform;
valid = skeletonUtility != null && skeletonUtility.skeletonRenderer != null && skeletonUtility.skeletonRenderer.valid;
if (!valid)
return;
skeletonTransform = skeletonUtility.transform;
skeletonUtility.OnReset -= HandleOnReset;
skeletonUtility.OnReset += HandleOnReset;
DoUpdate();
}
void OnEnable () {
skeletonUtility = SkeletonUtility.GetInParent<SkeletonUtility>(transform);
if (skeletonUtility == null)
return;
skeletonUtility.RegisterBone(this);
skeletonUtility.OnReset += HandleOnReset;
}
void HandleOnReset () {
Reset();
}
void OnDisable () {
if (skeletonUtility != null) {
skeletonUtility.OnReset -= HandleOnReset;
skeletonUtility.UnregisterBone(this);
}
}
public void DoUpdate () {
if (!valid) {
Reset();
return;
}
Spine.Skeleton skeleton = skeletonUtility.skeletonRenderer.skeleton;
if (bone == null) {
if (boneName == null || boneName.Length == 0)
return;
bone = skeleton.FindBone(boneName);
if (bone == null) {
Debug.LogError("Bone not found: " + boneName, this);
return;
}
}
float skeletonFlipRotation = (skeleton.flipX ^ skeleton.flipY) ? -1f : 1f;
float flipCompensation = 0;
if (flip && (flipX || (flipX != bone.flipX)) && bone.parent != null) {
flipCompensation = bone.parent.WorldRotation * -2;
}
if (mode == Mode.Follow) {
if (flip) {
flipX = bone.flipX;
}
if (position) {
cachedTransform.localPosition = new Vector3(bone.x, bone.y, 0);
}
if (rotation) {
if (bone.Data.InheritRotation) {
if (bone.FlipX) {
cachedTransform.localRotation = Quaternion.Euler(0, 180, bone.rotationIK - flipCompensation);
} else {
cachedTransform.localRotation = Quaternion.Euler(0, 0, bone.rotationIK);
}
} else {
Vector3 euler = skeletonTransform.rotation.eulerAngles;
cachedTransform.rotation = Quaternion.Euler(euler.x, euler.y, skeletonTransform.rotation.eulerAngles.z + (bone.worldRotation * skeletonFlipRotation));
}
}
if (scale) {
cachedTransform.localScale = new Vector3(bone.scaleX, bone.scaleY, 1);
nonUniformScaleWarning = (bone.scaleX != bone.scaleY);
}
} else if (mode == Mode.Override) {
if (transformLerpComplete)
return;
if (parentReference == null) {
if (position) {
bone.x = Mathf.Lerp(bone.x, cachedTransform.localPosition.x, overrideAlpha);
bone.y = Mathf.Lerp(bone.y, cachedTransform.localPosition.y, overrideAlpha);
}
if (rotation) {
float angle = Mathf.LerpAngle(bone.Rotation, cachedTransform.localRotation.eulerAngles.z, overrideAlpha) + flipCompensation;
if (flip) {
if ((!flipX && bone.flipX)) {
angle -= flipCompensation;
}
//TODO fix this...
if (angle >= 360)
angle -= 360;
else if (angle <= -360)
angle += 360;
}
bone.Rotation = angle;
}
if (scale) {
bone.scaleX = Mathf.Lerp(bone.scaleX, cachedTransform.localScale.x, overrideAlpha);
bone.scaleY = Mathf.Lerp(bone.scaleY, cachedTransform.localScale.y, overrideAlpha);
nonUniformScaleWarning = (bone.scaleX != bone.scaleY);
}
if (flip) {
bone.flipX = flipX;
}
} else {
if (transformLerpComplete)
return;
if (position) {
Vector3 pos = parentReference.InverseTransformPoint(cachedTransform.position);
bone.x = Mathf.Lerp(bone.x, pos.x, overrideAlpha);
bone.y = Mathf.Lerp(bone.y, pos.y, overrideAlpha);
}
if (rotation) {
float angle = Mathf.LerpAngle(bone.Rotation, Quaternion.LookRotation(flipX ? Vector3.forward * -1 : Vector3.forward, parentReference.InverseTransformDirection(cachedTransform.up)).eulerAngles.z, overrideAlpha) + flipCompensation;
if (flip) {
if ((!flipX && bone.flipX)) {
angle -= flipCompensation;
}
//TODO fix this...
if (angle >= 360)
angle -= 360;
else if (angle <= -360)
angle += 360;
}
bone.Rotation = angle;
}
//TODO: Something about this
if (scale) {
bone.scaleX = Mathf.Lerp(bone.scaleX, cachedTransform.localScale.x, overrideAlpha);
bone.scaleY = Mathf.Lerp(bone.scaleY, cachedTransform.localScale.y, overrideAlpha);
nonUniformScaleWarning = (bone.scaleX != bone.scaleY);
}
if (flip) {
bone.flipX = flipX;
}
}
transformLerpComplete = true;
}
}
public void FlipX (bool state) {
if (state != flipX) {
flipX = state;
if (flipX && Mathf.Abs(transform.localRotation.eulerAngles.y) > 90) {
skeletonUtility.skeletonAnimation.LateUpdate();
return;
} else if (!flipX && Mathf.Abs(transform.localRotation.eulerAngles.y) < 90) {
skeletonUtility.skeletonAnimation.LateUpdate();
return;
}
}
bone.FlipX = state;
transform.RotateAround(transform.position, skeletonUtility.transform.up, 180);
Vector3 euler = transform.localRotation.eulerAngles;
euler.x = 0;
euler.y = bone.FlipX ? 180 : 0;
transform.localRotation = Quaternion.Euler(euler);
}
void OnDrawGizmos () {
if (NonUniformScaleWarning) {
Gizmos.DrawIcon(transform.position + new Vector3(0, 0.128f, 0), "icon-warning");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.Versioning;
using NuGet.Resources;
using NuGet.V3Interop;
namespace NuGet
{
public static class PackageRepositoryExtensions
{
public static IDisposable StartOperation(this IPackageRepository self, string operation, string mainPackageId, string mainPackageVersion)
{
IOperationAwareRepository repo = self as IOperationAwareRepository;
if (repo != null)
{
return repo.StartOperation(operation, mainPackageId, mainPackageVersion);
}
return DisposableAction.NoOp;
}
public static bool Exists(this IPackageRepository repository, IPackageName package)
{
return repository.Exists(package.Id, package.Version);
}
public static bool Exists(this IPackageRepository repository, string packageId)
{
return Exists(repository, packageId, version: null);
}
public static bool Exists(this IPackageRepository repository, string packageId, SemanticVersion version)
{
IPackageLookup packageLookup = repository as IPackageLookup;
if ((packageLookup != null) && !String.IsNullOrEmpty(packageId) && (version != null))
{
return packageLookup.Exists(packageId, version);
}
return repository.FindPackage(packageId, version) != null;
}
public static bool TryFindPackage(this IPackageRepository repository, string packageId, SemanticVersion version, out IPackage package)
{
package = repository.FindPackage(packageId, version);
return package != null;
}
public static IPackage FindPackage(this IPackageRepository repository, string packageId)
{
return repository.FindPackage(packageId, version: null);
}
public static IPackage FindPackage(this IPackageRepository repository, string packageId, SemanticVersion version)
{
// Default allow pre release versions to true here because the caller typically wants to find all packages in this scenario for e.g when checking if a
// a package is already installed in the local repository. The same applies to allowUnlisted.
return FindPackage(repository, packageId, version, NullConstraintProvider.Instance, allowPrereleaseVersions: true, allowUnlisted: true);
}
public static IPackage FindPackage(this IPackageRepository repository, string packageId, SemanticVersion version, bool allowPrereleaseVersions, bool allowUnlisted)
{
return FindPackage(repository, packageId, version, NullConstraintProvider.Instance, allowPrereleaseVersions, allowUnlisted);
}
public static IPackage FindPackage(
this IPackageRepository repository,
string packageId,
SemanticVersion version,
IPackageConstraintProvider constraintProvider,
bool allowPrereleaseVersions,
bool allowUnlisted)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
if (packageId == null)
{
throw new ArgumentNullException("packageId");
}
// if an explicit version is specified, disregard the 'allowUnlisted' argument
// and always allow unlisted packages.
if (version != null)
{
allowUnlisted = true;
}
else if (!allowUnlisted && (constraintProvider == null || constraintProvider == NullConstraintProvider.Instance))
{
var packageLatestLookup = repository as ILatestPackageLookup;
if (packageLatestLookup != null)
{
IPackage package;
if (packageLatestLookup.TryFindLatestPackageById(packageId, allowPrereleaseVersions, out package))
{
return package;
}
}
}
// If the repository implements it's own lookup then use that instead.
// This is an optimization that we use so we don't have to enumerate packages for
// sources that don't need to.
var packageLookup = repository as IPackageLookup;
if (packageLookup != null && version != null)
{
return packageLookup.FindPackage(packageId, version);
}
IEnumerable<IPackage> packages = repository.FindPackagesById(packageId);
packages = packages.ToList()
.OrderByDescending(p => p.Version);
if (!allowUnlisted)
{
packages = packages.Where(PackageExtensions.IsListed);
}
if (version != null)
{
packages = packages.Where(p => p.Version == version);
}
else if (constraintProvider != null)
{
packages = DependencyResolveUtility.FilterPackagesByConstraints(constraintProvider, packages, packageId, allowPrereleaseVersions);
}
return packages.FirstOrDefault();
}
public static IPackage FindPackage(this IPackageRepository repository, string packageId, IVersionSpec versionSpec,
IPackageConstraintProvider constraintProvider, bool allowPrereleaseVersions, bool allowUnlisted)
{
var packages = repository.FindPackages(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted);
if (constraintProvider != null)
{
packages = DependencyResolveUtility.FilterPackagesByConstraints(constraintProvider, packages, packageId, allowPrereleaseVersions);
}
return packages.FirstOrDefault();
}
public static IEnumerable<IPackage> FindPackages(this IPackageRepository repository, IEnumerable<string> packageIds)
{
if (packageIds == null)
{
throw new ArgumentNullException("packageIds");
}
// If we're in V3-land, find packages using that API
var v3Repo = repository as IV3InteropRepository;
if (v3Repo != null)
{
return packageIds.SelectMany(id => v3Repo.FindPackagesById(id)).ToList();
}
else
{
return FindPackages(repository, packageIds, GetFilterExpression);
}
}
public static IEnumerable<IPackage> FindPackagesById(this IPackageRepository repository, string packageId)
{
var directRepo = repository as IV3InteropRepository;
if (directRepo != null)
{
return directRepo.FindPackagesById(packageId);
}
var serviceBasedRepository = repository as IPackageLookup;
if (serviceBasedRepository != null)
{
return serviceBasedRepository.FindPackagesById(packageId).ToList();
}
else
{
return FindPackagesByIdCore(repository, packageId);
}
}
internal static IEnumerable<IPackage> FindPackagesByIdCore(IPackageRepository repository, string packageId)
{
var cultureRepository = repository as ICultureAwareRepository;
if (cultureRepository != null)
{
packageId = packageId.ToLower(cultureRepository.Culture);
}
else
{
packageId = packageId.ToLower(CultureInfo.CurrentCulture);
}
return (from p in repository.GetPackages()
where p.Id.ToLower() == packageId
orderby p.Id
select p).ToList();
}
/// <summary>
/// Since Odata dies when our query for updates is too big. We query for updates 10 packages at a time
/// and return the full list of packages.
/// </summary>
private static IEnumerable<IPackage> FindPackages<T>(
this IPackageRepository repository,
IEnumerable<T> items,
Func<IEnumerable<T>, Expression<Func<IPackage, bool>>> filterSelector)
{
const int batchSize = 10;
while (items.Any())
{
IEnumerable<T> currentItems = items.Take(batchSize);
Expression<Func<IPackage, bool>> filterExpression = filterSelector(currentItems);
var query = repository.GetPackages()
.Where(filterExpression)
.OrderBy(p => p.Id);
foreach (var package in query)
{
yield return package;
}
items = items.Skip(batchSize);
}
}
public static IEnumerable<IPackage> FindPackages(
this IPackageRepository repository,
string packageId,
IVersionSpec versionSpec,
bool allowPrereleaseVersions,
bool allowUnlisted)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
if (packageId == null)
{
throw new ArgumentNullException("packageId");
}
IEnumerable<IPackage> packages = repository.FindPackagesById(packageId)
.OrderByDescending(p => p.Version);
if (!allowUnlisted)
{
packages = packages.Where(PackageExtensions.IsListed);
}
if (versionSpec != null)
{
packages = packages.FindByVersion(versionSpec);
}
packages = DependencyResolveUtility.FilterPackagesByConstraints(NullConstraintProvider.Instance, packages, packageId, allowPrereleaseVersions);
return packages;
}
public static IPackage FindPackage(
this IPackageRepository repository,
string packageId,
IVersionSpec versionSpec,
bool allowPrereleaseVersions,
bool allowUnlisted)
{
return repository.FindPackages(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted).FirstOrDefault();
}
public static PackageDependency FindDependency(this IPackageMetadata package, string packageId, FrameworkName targetFramework)
{
return (from dependency in package.GetCompatiblePackageDependencies(targetFramework)
where dependency.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase)
select dependency).FirstOrDefault();
}
public static IQueryable<IPackage> Search(this IPackageRepository repository, string searchTerm, bool allowPrereleaseVersions)
{
return Search(repository, searchTerm, targetFrameworks: Enumerable.Empty<string>(), allowPrereleaseVersions: allowPrereleaseVersions);
}
public static IQueryable<IPackage> Search(this IPackageRepository repository, string searchTerm, IEnumerable<string> targetFrameworks, bool allowPrereleaseVersions, bool includeDelisted = false)
{
if (targetFrameworks == null)
{
throw new ArgumentNullException("targetFrameworks");
}
var serviceBasedRepository = repository as IServiceBasedRepository;
if (serviceBasedRepository != null)
{
return serviceBasedRepository.Search(searchTerm, targetFrameworks, allowPrereleaseVersions, includeDelisted);
}
// Ignore the target framework if the repository doesn't support searching
var result = repository
.GetPackages()
.Find(searchTerm)
.FilterByPrerelease(allowPrereleaseVersions);
if (includeDelisted == false)
{
result = result.Where(p => p.IsListed());
}
return result.AsQueryable();
}
/// <summary>
/// Returns updates for packages from the repository
/// </summary>
/// <param name="repository">The repository to search for updates</param>
/// <param name="packages">Packages to look for updates</param>
/// <param name="includePrerelease">Indicates whether to consider prerelease updates.</param>
/// <param name="includeAllVersions">Indicates whether to include all versions of an update as opposed to only including the latest version.</param>
public static IEnumerable<IPackage> GetUpdates(
this IPackageRepository repository,
IEnumerable<IPackageName> packages,
bool includePrerelease,
bool includeAllVersions,
IEnumerable<FrameworkName> targetFrameworks = null,
IEnumerable<IVersionSpec> versionConstraints = null)
{
if (packages.IsEmpty())
{
return Enumerable.Empty<IPackage>();
}
var serviceBasedRepository = repository as IServiceBasedRepository;
return serviceBasedRepository != null ? serviceBasedRepository.GetUpdates(packages, includePrerelease, includeAllVersions, targetFrameworks, versionConstraints) :
repository.GetUpdatesCore(packages, includePrerelease, includeAllVersions, targetFrameworks, versionConstraints);
}
public static IEnumerable<IPackage> GetUpdatesCore(
this IPackageRepository repository,
IEnumerable<IPackageName> packages,
bool includePrerelease,
bool includeAllVersions,
IEnumerable<FrameworkName> targetFramework,
IEnumerable<IVersionSpec> versionConstraints)
{
List<IPackageName> packageList = packages.ToList();
if (!packageList.Any())
{
return Enumerable.Empty<IPackage>();
}
IList<IVersionSpec> versionConstraintList;
if (versionConstraints == null)
{
versionConstraintList = new IVersionSpec[packageList.Count];
}
else
{
versionConstraintList = versionConstraints.ToList();
}
if (packageList.Count != versionConstraintList.Count)
{
throw new ArgumentException(NuGetResources.GetUpdatesParameterMismatch);
}
// These are the packages that we need to look at for potential updates.
ILookup<string, IPackage> sourcePackages = GetUpdateCandidates(repository, packageList, includePrerelease)
.ToList()
.ToLookup(package => package.Id, StringComparer.OrdinalIgnoreCase);
var results = new List<IPackage>();
for (int i = 0; i < packageList.Count; i++)
{
var package = packageList[i];
var constraint = versionConstraintList[i];
var updates = from candidate in sourcePackages[package.Id]
where (candidate.Version > package.Version) &&
SupportsTargetFrameworks(targetFramework, candidate) &&
(constraint == null || constraint.Satisfies(candidate.Version))
select candidate;
results.AddRange(updates);
}
if (!includeAllVersions)
{
return results.CollapseById();
}
return results;
}
private static bool SupportsTargetFrameworks(IEnumerable<FrameworkName> targetFramework, IPackage package)
{
return targetFramework.IsEmpty() || targetFramework.Any(t => VersionUtility.IsCompatible(t, package.GetSupportedFrameworks()));
}
public static IPackageRepository Clone(this IPackageRepository repository)
{
var cloneableRepository = repository as ICloneableRepository;
if (cloneableRepository != null)
{
return cloneableRepository.Clone();
}
return repository;
}
/// <summary>
/// Since odata dies when our query for updates is too big. We query for updates 10 packages at a time
/// and return the full list of candidates for updates.
/// </summary>
private static IEnumerable<IPackage> GetUpdateCandidates(
IPackageRepository repository,
IEnumerable<IPackageName> packages,
bool includePrerelease)
{
var query = FindPackages(repository, packages, GetFilterExpression);
if (!includePrerelease)
{
query = query.Where(p => p.IsReleaseVersion());
}
// for updates, we never consider unlisted packages
query = query.Where(PackageExtensions.IsListed);
return query;
}
/// <summary>
/// For the list of input packages generate an expression like:
/// p => p.Id == 'package1id' or p.Id == 'package2id' or p.Id == 'package3id'... up to package n
/// </summary>
private static Expression<Func<IPackage, bool>> GetFilterExpression(IEnumerable<IPackageName> packages)
{
return GetFilterExpression(packages.Select(p => p.Id));
}
[SuppressMessage("Microsoft.Globalization", "CA1304:SpecifyCultureInfo", MessageId = "System.String.ToLower", Justification = "This is for a linq query")]
private static Expression<Func<IPackage, bool>> GetFilterExpression(IEnumerable<string> ids)
{
ParameterExpression parameterExpression = Expression.Parameter(typeof(IPackageName));
Expression expressionBody = ids.Select(id => GetCompareExpression(parameterExpression, id.ToLower()))
.Aggregate(Expression.OrElse);
return Expression.Lambda<Func<IPackage, bool>>(expressionBody, parameterExpression);
}
/// <summary>
/// Builds the expression: package.Id.ToLower() == "somepackageid"
/// </summary>
private static Expression GetCompareExpression(Expression parameterExpression, object value)
{
// package.Id
Expression propertyExpression = Expression.Property(parameterExpression, "Id");
// .ToLower()
Expression toLowerExpression = Expression.Call(propertyExpression, typeof(string).GetMethod("ToLower", Type.EmptyTypes));
// == localPackage.Id
return Expression.Equal(toLowerExpression, Expression.Constant(value));
}
/// <summary>
/// Selects the dependency package from the list of candidate packages
/// according to <paramref name="dependencyVersion"/>.
/// </summary>
/// <param name="packages">The list of candidate packages.</param>
/// <param name="dependencyVersion">The rule used to select the package from
/// <paramref name="packages"/> </param>
/// <returns>The selected package.</returns>
/// <remarks>Precondition: <paramref name="packages"/> are ordered by ascending version.</remarks>
internal static IPackage SelectDependency(this IEnumerable<IPackage> packages, DependencyVersion dependencyVersion)
{
if (packages == null || !packages.Any())
{
return null;
}
if (dependencyVersion == DependencyVersion.Lowest)
{
return packages.FirstOrDefault();
}
else if (dependencyVersion == DependencyVersion.Highest)
{
return packages.LastOrDefault();
}
else if (dependencyVersion == DependencyVersion.HighestPatch)
{
var groups = from p in packages
group p by new { p.Version.Version.Major, p.Version.Version.Minor } into g
orderby g.Key.Major, g.Key.Minor
select g;
return (from p in groups.First()
orderby p.Version descending
select p).FirstOrDefault();
}
else if (dependencyVersion == DependencyVersion.HighestMinor)
{
var groups = from p in packages
group p by new { p.Version.Version.Major } into g
orderby g.Key.Major
select g;
return (from p in groups.First()
orderby p.Version descending
select p).FirstOrDefault();
}
throw new ArgumentOutOfRangeException("dependencyVersion");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.AspNetCore.Server.IntegrationTesting;
using Microsoft.AspNetCore.Server.IntegrationTesting.IIS;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Net.Http.Headers;
using Xunit;
using Xunit.Abstractions;
using Xunit.Sdk;
namespace ServerComparison.FunctionalTests
{
public class ResponseCompressionTests : LoggedTest
{
// NGinx's default min size is 20 bytes
private static readonly string HelloWorldBody = "Hello World;" + new string('a', 20);
public ResponseCompressionTests(ITestOutputHelper output) : base(output)
{
}
public static TestMatrix NoCompressionTestVariants
=> TestMatrix.ForServers(ServerType.IISExpress, ServerType.Kestrel, ServerType.Nginx, ServerType.HttpSys)
.WithTfms(Tfm.Default)
.WithAllHostingModels();
[ConditionalTheory]
[MemberData(nameof(NoCompressionTestVariants))]
public Task ResponseCompression_NoCompression(TestVariant variant)
{
return ResponseCompression(variant, CheckNoCompressionAsync, hostCompression: false);
}
public static TestMatrix HostCompressionTestVariants
=> TestMatrix.ForServers(ServerType.IISExpress, ServerType.Nginx)
.WithTfms(Tfm.Default)
.WithAllHostingModels();
[ConditionalTheory]
[MemberData(nameof(HostCompressionTestVariants))]
public Task ResponseCompression_HostCompression(TestVariant variant)
{
return ResponseCompression(variant, CheckHostCompressionAsync, hostCompression: true);
}
public static TestMatrix AppCompressionTestVariants
=> TestMatrix.ForServers(ServerType.IISExpress, ServerType.Kestrel, ServerType.HttpSys) // No pass-through compression for nginx
.WithTfms(Tfm.Default)
.WithAllHostingModels();
[ConditionalTheory]
[MemberData(nameof(AppCompressionTestVariants))]
public Task ResponseCompression_AppCompression(TestVariant variant)
{
return ResponseCompression(variant, CheckAppCompressionAsync, hostCompression: false);
}
public static TestMatrix HostAndAppCompressionTestVariants
=> TestMatrix.ForServers(ServerType.IISExpress, ServerType.Kestrel, ServerType.Nginx, ServerType.HttpSys)
.WithTfms(Tfm.Default)
.WithAllHostingModels();
[ConditionalTheory]
[MemberData(nameof(HostAndAppCompressionTestVariants))]
public Task ResponseCompression_AppAndHostCompression(TestVariant variant)
{
return ResponseCompression(variant, CheckAppCompressionAsync, hostCompression: true);
}
private async Task ResponseCompression(TestVariant variant,
Func<HttpClient, ILogger, Task> scenario,
bool hostCompression,
[CallerMemberName] string testName = null)
{
testName = $"{testName}_{variant.Server}_{variant.Tfm}_{variant.Architecture}_{variant.ApplicationType}";
using (StartLog(out var loggerFactory,
variant.Server == ServerType.Nginx ? LogLevel.Trace : LogLevel.Debug, // https://github.com/aspnet/ServerTests/issues/144
testName))
{
var logger = loggerFactory.CreateLogger("ResponseCompression");
var deploymentParameters = new DeploymentParameters(variant)
{
ApplicationPath = Helpers.GetApplicationPath(),
EnvironmentName = "ResponseCompression",
};
if (variant.Server == ServerType.Nginx)
{
deploymentParameters.ServerConfigTemplateContent = hostCompression
? Helpers.GetNginxConfigContent("nginx.conf")
: Helpers.GetNginxConfigContent("NoCompression.conf");
}
else if (variant.Server == ServerType.IISExpress && !hostCompression)
{
var iisDeploymentParameters = new IISDeploymentParameters(deploymentParameters);
iisDeploymentParameters.ServerConfigActionList.Add(
(element, _) => {
var compressionElement = element
.RequiredElement("system.webServer")
.RequiredElement("httpCompression");
compressionElement
.RequiredElement("dynamicTypes")
.Elements()
.SkipLast(1)
.Remove();
compressionElement
.RequiredElement("staticTypes")
.Elements()
.SkipLast(1)
.Remove();
// last element in both dynamicTypes and staticTypes disables compression
// <add mimeType="*/*" enabled="false" />
});
deploymentParameters = iisDeploymentParameters;
}
using (var deployer = IISApplicationDeployerFactory.Create(deploymentParameters, loggerFactory))
{
var deploymentResult = await deployer.DeployAsync();
var httpClientHandler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.None };
Assert.True(httpClientHandler.SupportsAutomaticDecompression);
var httpClient = deploymentResult.CreateHttpClient(httpClientHandler);
// Request to base address and check if various parts of the body are rendered & measure the cold startup time.
var response = await RetryHelper.RetryRequest(() =>
{
return httpClient.GetAsync(string.Empty);
}, logger, deploymentResult.HostShutdownToken);
var responseText = await response.Content.ReadAsStringAsync();
try
{
Assert.Equal("Running", responseText);
}
catch (XunitException)
{
logger.LogWarning(response.ToString());
logger.LogWarning(responseText);
throw;
}
await scenario(httpClient, logger);
}
}
}
private static async Task CheckNoCompressionAsync(HttpClient client, ILogger logger)
{
logger.LogInformation("Testing /NoAppCompression");
var request = new HttpRequestMessage(HttpMethod.Get, "NoAppCompression");
request.Headers.AcceptEncoding.ParseAdd("gzip,deflate");
var response = await client.SendAsync(request);
var responseText = await response.Content.ReadAsStringAsync();
try
{
Assert.Equal(HelloWorldBody, responseText);
Assert.Equal(HelloWorldBody.Length.ToString(CultureInfo.InvariantCulture), GetContentLength(response));
Assert.Equal(0, response.Content.Headers.ContentEncoding.Count);
}
catch (XunitException)
{
logger.LogWarning(response.ToString());
logger.LogWarning(responseText);
throw;
}
}
private static Task CheckHostCompressionAsync(HttpClient client, ILogger logger)
{
return CheckCompressionAsync(client, "NoAppCompression", logger);
}
private static Task CheckAppCompressionAsync(HttpClient client, ILogger logger)
{
return CheckCompressionAsync(client, "AppCompression", logger);
}
private static async Task CheckCompressionAsync(HttpClient client, string url, ILogger logger)
{
// Manage the compression manually because HttpClient removes the Content-Encoding header when decompressing.
logger.LogInformation($"Testing /{url}");
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.AcceptEncoding.ParseAdd("gzip,deflate");
var response = await client.SendAsync(request);
var responseText = await response.Content.ReadAsStringAsync();
try
{
responseText = await ReadCompressedAsStringAsync(response.Content);
Assert.Equal(HelloWorldBody, responseText);
Assert.Equal(1, response.Content.Headers.ContentEncoding.Count);
Assert.Equal("gzip", response.Content.Headers.ContentEncoding.First());
}
catch (XunitException)
{
logger.LogWarning(response.ToString());
logger.LogWarning(responseText);
throw;
}
}
private static string GetContentLength(HttpResponseMessage response)
{
// Don't use response.Content.Headers.ContentLength, it will dynamically calculate the value if it can.
return response.Content.Headers.TryGetValues(HeaderNames.ContentLength, out var values) ? values.FirstOrDefault() : null;
}
private static async Task<string> ReadCompressedAsStringAsync(HttpContent content)
{
using (var stream = await content.ReadAsStreamAsync())
using (var compressStream = new GZipStream(stream, CompressionMode.Decompress))
using (var reader = new StreamReader(compressStream))
{
return await reader.ReadToEndAsync();
}
}
}
}
| |
using System.Security.Principal;
using System.Windows.Media.Imaging;
using Microsoft.Deployment.WindowsInstaller;
using Caliburn.Micro;
using WixSharp.CommonTasks;
using WixSharp.UI.Forms;
namespace WixSharp.UI.WPF
{
/// <summary>
/// The standard ProgressDialog.
/// <para>Follows the design of the canonical Caliburn.Micro View (MVVM).</para>
/// <para>See https://caliburnmicro.com/documentation/cheat-sheet</para>
/// </summary>
/// <seealso cref="WixSharp.UI.WPF.WpfDialog" />
/// <seealso cref="WixSharp.IWpfDialog" />
/// <seealso cref="System.Windows.Markup.IComponentConnector" />
public partial class ProgressDialog : WpfDialog, IWpfDialog, IProgressDialog
{
/// <summary>
/// Initializes a new instance of the <see cref="ProgressDialog" /> class.
/// </summary>
public ProgressDialog()
{
InitializeComponent();
}
/// <summary>
/// This method is invoked by WixSHarp runtime when the custom dialog content is internally fully initialized.
/// This is a convenient place to do further initialization activities (e.g. localization).
/// </summary>
public void Init()
{
UpdateTitles(ManagedFormHost.Runtime.Session);
model = new ProgressDialogModel { Host = ManagedFormHost };
ViewModelBinder.Bind(model, this, null);
model.StartExecute();
}
/// <summary>
/// Updates the titles of the dialog depending on what type of installation action MSI is performing.
/// </summary>
/// <param name="session">The session.</param>
public void UpdateTitles(ISession session)
{
if (session.IsUninstalling())
{
DialogTitleLabel.Text = "[ProgressDlgTitleRemoving]";
DialogDescription.Text = "[ProgressDlgTextRemoving]";
}
else if (session.IsRepairing())
{
DialogTitleLabel.Text = "[ProgressDlgTextRepairing]";
DialogDescription.Text = "[ProgressDlgTitleRepairing]";
}
else if (session.IsInstalling())
{
DialogTitleLabel.Text = "[ProgressDlgTitleInstalling]";
DialogDescription.Text = "[ProgressDlgTextInstalling]";
}
// `Localize` resolves [...] titles and descriptions into the localized strings stored in MSI resources tables
this.Localize();
}
ProgressDialogModel model;
/// <summary>
/// Processes information and progress messages sent to the user interface.
/// <para> This method directly mapped to the
/// <see cref="T:Microsoft.Deployment.WindowsInstaller.IEmbeddedUI.ProcessMessage" />.</para>
/// </summary>
/// <param name="messageType">Type of the message.</param>
/// <param name="messageRecord">The message record.</param>
/// <param name="buttons">The buttons.</param>
/// <param name="icon">The icon.</param>
/// <param name="defaultButton">The default button.</param>
/// <returns></returns>
public override MessageResult ProcessMessage(InstallMessage messageType, Record messageRecord, MessageButtons buttons, MessageIcon icon, MessageDefaultButton defaultButton)
=> model?.ProcessMessage(messageType, messageRecord, CurrentStatus.Text) ?? MessageResult.None;
/// <summary>
/// Called when MSI execution is complete.
/// </summary>
public override void OnExecuteComplete()
=> model?.OnExecuteComplete();
/// <summary>
/// Called when MSI execution progress is changed.
/// </summary>
/// <param name="progressPercentage">The progress percentage.</param>
public override void OnProgress(int progressPercentage)
{
if (model != null)
model.ProgressValue = progressPercentage;
}
}
/// <summary>
/// ViewModel for standard ProgressDialog.
/// <para>Follows the design of the canonical Caliburn.Micro ViewModel (MVVM).</para>
/// <para>See https://caliburnmicro.com/documentation/cheat-sheet</para>
/// </summary>
/// <seealso cref="Caliburn.Micro.Screen" />
class ProgressDialogModel : Caliburn.Micro.Screen
{
public ManagedForm Host;
ISession session => Host?.Runtime.Session;
IManagedUIShell shell => Host?.Shell;
public BitmapImage Banner => session?.GetResourceBitmap("WixUI_Bmp_Banner").ToImageSource();
public bool UacPromptIsVisible => (!WindowsIdentity.GetCurrent().IsAdmin() && Uac.IsEnabled() && !uacPromptActioned);
public string CurrentAction { get => currentAction; set { currentAction = value; base.NotifyOfPropertyChange(() => CurrentAction); } }
public int ProgressValue { get => progressValue; set { progressValue = value; base.NotifyOfPropertyChange(() => ProgressValue); } }
bool uacPromptActioned = false;
string currentAction;
int progressValue;
public string UacPrompt
{
get
{
if (Uac.IsEnabled())
{
var prompt = session?.Property("UAC_WARNING");
if (prompt.IsNotEmpty())
return prompt;
else
return
"Please wait for UAC prompt to appear. " +
"If it appears minimized then activate it from the taskbar.";
}
else
return null;
}
}
public void StartExecute()
=> shell?.StartExecute();
public void Cancel()
{
if (shell.IsDemoMode)
shell.GoNext();
else
shell.Cancel();
}
public MessageResult ProcessMessage(InstallMessage messageType, Record messageRecord, string currentStatus)
{
switch (messageType)
{
case InstallMessage.InstallStart:
case InstallMessage.InstallEnd:
{
uacPromptActioned = true;
base.NotifyOfPropertyChange(() => UacPromptIsVisible);
}
break;
case InstallMessage.ActionStart:
{
try
{
//messageRecord[0] - is reserved for FormatString value
/*
messageRecord[2] unconditionally contains the string to display
Examples:
messageRecord[0] "Action 23:14:50: [1]. [2]"
messageRecord[1] "InstallFiles"
messageRecord[2] "Copying new files"
messageRecord[3] "File: [1], Directory: [9], Size: [6]"
messageRecord[0] "Action 23:15:21: [1]. [2]"
messageRecord[1] "RegisterUser"
messageRecord[2] "Registering user"
messageRecord[3] "[1]"
*/
if (messageRecord.FieldCount >= 3)
CurrentAction = messageRecord[2].ToString();
else
CurrentAction = null;
}
catch
{
//Catch all, we don't want the installer to crash in an attempt to process message.
}
}
break;
}
return MessageResult.OK;
}
public void OnExecuteComplete()
{
CurrentAction = null;
shell?.GoNext();
}
}
}
| |
// This source file is adapted from the Windows Presentation Foundation project.
// (https://github.com/dotnet/wpf/)
//
// Licensed to The Avalonia Project under MIT License, courtesy of The .NET Foundation.
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Utilities;
using static System.Math;
namespace Avalonia.Controls
{
/// <summary>
/// Positions child elements in sequential position from left to right,
/// breaking content to the next line at the edge of the containing box.
/// Subsequent ordering happens sequentially from top to bottom or from right to left,
/// depending on the value of the <see cref="Orientation"/> property.
/// </summary>
public class WrapPanel : Panel, INavigableContainer
{
/// <summary>
/// Defines the <see cref="Orientation"/> property.
/// </summary>
public static readonly StyledProperty<Orientation> OrientationProperty =
AvaloniaProperty.Register<WrapPanel, Orientation>(nameof(Orientation), defaultValue: Orientation.Horizontal);
/// <summary>
/// Defines the <see cref="ItemWidth"/> property.
/// </summary>
public static readonly StyledProperty<double> ItemWidthProperty =
AvaloniaProperty.Register<WrapPanel, double>(nameof(ItemWidth), double.NaN);
/// <summary>
/// Defines the <see cref="ItemHeight"/> property.
/// </summary>
public static readonly StyledProperty<double> ItemHeightProperty =
AvaloniaProperty.Register<WrapPanel, double>(nameof(ItemHeight), double.NaN);
/// <summary>
/// Initializes static members of the <see cref="WrapPanel"/> class.
/// </summary>
static WrapPanel()
{
AffectsMeasure<WrapPanel>(OrientationProperty, ItemWidthProperty, ItemHeightProperty);
}
/// <summary>
/// Gets or sets the orientation in which child controls will be layed out.
/// </summary>
public Orientation Orientation
{
get { return GetValue(OrientationProperty); }
set { SetValue(OrientationProperty, value); }
}
/// <summary>
/// Gets or sets the width of all items in the WrapPanel.
/// </summary>
public double ItemWidth
{
get { return GetValue(ItemWidthProperty); }
set { SetValue(ItemWidthProperty, value); }
}
/// <summary>
/// Gets or sets the height of all items in the WrapPanel.
/// </summary>
public double ItemHeight
{
get { return GetValue(ItemHeightProperty); }
set { SetValue(ItemHeightProperty, value); }
}
/// <summary>
/// Gets the next control in the specified direction.
/// </summary>
/// <param name="direction">The movement direction.</param>
/// <param name="from">The control from which movement begins.</param>
/// <param name="wrap">Whether to wrap around when the first or last item is reached.</param>
/// <returns>The control.</returns>
IInputElement? INavigableContainer.GetControl(NavigationDirection direction, IInputElement? from, bool wrap)
{
var orientation = Orientation;
var children = Children;
bool horiz = orientation == Orientation.Horizontal;
int index = from is not null ? Children.IndexOf((IControl)from) : -1;
switch (direction)
{
case NavigationDirection.First:
index = 0;
break;
case NavigationDirection.Last:
index = children.Count - 1;
break;
case NavigationDirection.Next:
++index;
break;
case NavigationDirection.Previous:
--index;
break;
case NavigationDirection.Left:
index = horiz ? index - 1 : -1;
break;
case NavigationDirection.Right:
index = horiz ? index + 1 : -1;
break;
case NavigationDirection.Up:
index = horiz ? -1 : index - 1;
break;
case NavigationDirection.Down:
index = horiz ? -1 : index + 1;
break;
}
if (index >= 0 && index < children.Count)
{
return children[index];
}
else
{
return null;
}
}
/// <inheritdoc/>
protected override Size MeasureOverride(Size constraint)
{
double itemWidth = ItemWidth;
double itemHeight = ItemHeight;
var orientation = Orientation;
var children = Children;
var curLineSize = new UVSize(orientation);
var panelSize = new UVSize(orientation);
var uvConstraint = new UVSize(orientation, constraint.Width, constraint.Height);
bool itemWidthSet = !double.IsNaN(itemWidth);
bool itemHeightSet = !double.IsNaN(itemHeight);
var childConstraint = new Size(
itemWidthSet ? itemWidth : constraint.Width,
itemHeightSet ? itemHeight : constraint.Height);
for (int i = 0, count = children.Count; i < count; i++)
{
var child = children[i];
if (child != null)
{
// Flow passes its own constraint to children
child.Measure(childConstraint);
// This is the size of the child in UV space
var sz = new UVSize(orientation,
itemWidthSet ? itemWidth : child.DesiredSize.Width,
itemHeightSet ? itemHeight : child.DesiredSize.Height);
if (MathUtilities.GreaterThan(curLineSize.U + sz.U, uvConstraint.U)) // Need to switch to another line
{
panelSize.U = Max(curLineSize.U, panelSize.U);
panelSize.V += curLineSize.V;
curLineSize = sz;
if (MathUtilities.GreaterThan(sz.U, uvConstraint.U)) // The element is wider then the constraint - give it a separate line
{
panelSize.U = Max(sz.U, panelSize.U);
panelSize.V += sz.V;
curLineSize = new UVSize(orientation);
}
}
else // Continue to accumulate a line
{
curLineSize.U += sz.U;
curLineSize.V = Max(sz.V, curLineSize.V);
}
}
}
// The last line size, if any should be added
panelSize.U = Max(curLineSize.U, panelSize.U);
panelSize.V += curLineSize.V;
// Go from UV space to W/H space
return new Size(panelSize.Width, panelSize.Height);
}
/// <inheritdoc/>
protected override Size ArrangeOverride(Size finalSize)
{
double itemWidth = ItemWidth;
double itemHeight = ItemHeight;
var orientation = Orientation;
var children = Children;
int firstInLine = 0;
double accumulatedV = 0;
double itemU = orientation == Orientation.Horizontal ? itemWidth : itemHeight;
var curLineSize = new UVSize(orientation);
var uvFinalSize = new UVSize(orientation, finalSize.Width, finalSize.Height);
bool itemWidthSet = !double.IsNaN(itemWidth);
bool itemHeightSet = !double.IsNaN(itemHeight);
bool useItemU = orientation == Orientation.Horizontal ? itemWidthSet : itemHeightSet;
for (int i = 0; i < children.Count; i++)
{
var child = children[i];
if (child != null)
{
var sz = new UVSize(orientation,
itemWidthSet ? itemWidth : child.DesiredSize.Width,
itemHeightSet ? itemHeight : child.DesiredSize.Height);
if (MathUtilities.GreaterThan(curLineSize.U + sz.U, uvFinalSize.U)) // Need to switch to another line
{
ArrangeLine(accumulatedV, curLineSize.V, firstInLine, i, useItemU, itemU);
accumulatedV += curLineSize.V;
curLineSize = sz;
if (MathUtilities.GreaterThan(sz.U, uvFinalSize.U)) // The element is wider then the constraint - give it a separate line
{
// Switch to next line which only contain one element
ArrangeLine(accumulatedV, sz.V, i, ++i, useItemU, itemU);
accumulatedV += sz.V;
curLineSize = new UVSize(orientation);
}
firstInLine = i;
}
else // Continue to accumulate a line
{
curLineSize.U += sz.U;
curLineSize.V = Max(sz.V, curLineSize.V);
}
}
}
// Arrange the last line, if any
if (firstInLine < children.Count)
{
ArrangeLine(accumulatedV, curLineSize.V, firstInLine, children.Count, useItemU, itemU);
}
return finalSize;
}
private void ArrangeLine(double v, double lineV, int start, int end, bool useItemU, double itemU)
{
var orientation = Orientation;
var children = Children;
double u = 0;
bool isHorizontal = orientation == Orientation.Horizontal;
for (int i = start; i < end; i++)
{
var child = children[i];
if (child != null)
{
var childSize = new UVSize(orientation, child.DesiredSize.Width, child.DesiredSize.Height);
double layoutSlotU = useItemU ? itemU : childSize.U;
child.Arrange(new Rect(
isHorizontal ? u : v,
isHorizontal ? v : u,
isHorizontal ? layoutSlotU : lineV,
isHorizontal ? lineV : layoutSlotU));
u += layoutSlotU;
}
}
}
private struct UVSize
{
internal UVSize(Orientation orientation, double width, double height)
{
U = V = 0d;
_orientation = orientation;
Width = width;
Height = height;
}
internal UVSize(Orientation orientation)
{
U = V = 0d;
_orientation = orientation;
}
internal double U;
internal double V;
private Orientation _orientation;
internal double Width
{
get { return _orientation == Orientation.Horizontal ? U : V; }
set { if (_orientation == Orientation.Horizontal) U = value; else V = value; }
}
internal double Height
{
get { return _orientation == Orientation.Horizontal ? V : U; }
set { if (_orientation == Orientation.Horizontal) V = value; else U = value; }
}
}
}
}
| |
/**
* This source file is a part of the Dictionariosaur application.
* For full copyright and license information, please view the LICENSE file
* which should be distributed with this source code.
*
* @license MIT License
* @copyright Copyright (c) 2013, Steven Velozo
*
* A base class for all List memory data structures.
*
* Prototype and logging information that would be considered "standard" will start
* here.
*
* This should allow us to reuse comparators for multiple data structures.
*
* TODO: Consider putting saving and loading crap into this
*/
using System;
using MutiUtility;
namespace MutiDataStructures
{
public class DataStructureBase : PassThroughLoggedClass
{
//This is so we can override the current node business
protected DataNode _CurrentNode;
//The overridable property
public virtual DataNode CurrentNode
{
get { return this._CurrentNode; }
set {/*Nothing now, but we want to be able to override it. */}
}
public long CurrentItemKey
{
get
{
if (this._NodeCount > 0)
return this.CurrentNode.Index;
else
return 0;
}
}
// The number of items in the data structure
protected long _NodeCount;
//Default statistics for a data structure
protected long _SearchCount; //Number of searches
protected long _SearchMatchCount; //Number of matches resulting from searches
protected long _NavigationCount; //Number of navigation calls made (movefirst, etc)
//Extended statistics
protected long _AddCount; //Number of inserts
protected long _DeleteCount; //Number of deletes
//Logging options
protected bool _LogSearches; //Time and log each search
protected bool _LogNavigation; //Log each navigation function (WAY HUGE log files)
//Extended logging options
protected bool _LogAdds; //Log each add (can make log files HUGE)
protected bool _LogDeletes; //Log each delete operation
// The Auto Incriment key
protected long _LastGivenKey;
public DataStructureBase ()
{
//Initialize the list count
this._NodeCount = 0;
//Reset the statistics
this._SearchCount = 0;
this._SearchMatchCount = 0;
this._NavigationCount = 0;
this._AddCount = 0;
this._DeleteCount = 0;
this._LogSearches = false;
this._LogNavigation = false;
this._LogAdds = false;
this._LogDeletes = false;
//The list is empty. Zero everything out!
this._LastGivenKey = 0;
}
#region Data Access Functions
/// <summary>
/// The list count
/// </summary>
public long Count
{
get { return this._NodeCount; }
}
public long StatisticSearchCount
{
get { return this._SearchCount; }
}
public long StatisticSearchMatchCount
{
get { return this._SearchMatchCount; }
}
public long StatisticNavigationCount
{
get { return this._NavigationCount; }
}
public long StatisticAddCount
{
get { return this._AddCount; }
}
public long StatisticDeleteCount
{
get { return this._DeleteCount; }
}
public bool LogAllSearches
{
get { return this._LogSearches; }
set {this._LogSearches = value; }
}
public bool LogAllNavigation
{
get { return this._LogNavigation; }
set {this._LogNavigation = value; }
}
public bool LogAllAdds
{
get { return this._LogAdds; }
set {this._LogAdds = value; }
}
public bool LogAllDeletes
{
get { return this._LogDeletes; }
set {this._LogDeletes = value; }
}
#endregion
}
public class DataNode
{
//The primary key
private long _Index;
//The data gram
private object _Data;
//The constructor
public DataNode (object pNewDataGram)
{
this._Data = pNewDataGram;
}
#region Data Access Functions
/// <summary>
/// The primary key for the list node.
/// </summary>
public long Index
{
get { return this._Index; }
set {this._Index = value; }
}
public object Data
{
get { return this._Data; }
set {this._Data = value; }
}
#endregion
}
public class NodeMatch
{
//The key to match
private long _Index;
public NodeMatch ()
{
//Do nothing
this._Index = 0;
}
public NodeMatch (long pIndexToFind)
{
this._Index = pIndexToFind;
}
/// <summary>
/// Compare two nodes.
/// Return -1 for Left < Right
/// Return 0 for Left = Right
/// Return 1 for Left > Right
/// </summary>
/// <param name="LeftNodeValue">Left Comparator</param>
/// <param name="RightNodeValue">Right Comparator</param>
/// <returns>-1 for L less than R, 0 for L equal to R, 1 for L greater than R</returns>
public virtual int Compare (DataNode pLeftNodeValue, DataNode pRightNodeValue)
{
if (pLeftNodeValue.Index < pRightNodeValue.Index)
return -1;
else if (pLeftNodeValue.Index == pRightNodeValue.Index)
return 0;
else
return 1;
}
public virtual bool Match (DataNode pNodeToVerify)
{
//See if it matches. This is extremely straightforward.
if (pNodeToVerify.Index == this._Index)
return true;
else
return false;
}
}
}
| |
// Copyright (c) 2012-2015 Sharpex2D - Kevin Scholz (ThuCommix)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the 'Software'), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace Sharpex2D.Input
{
[Developer("ThuCommix", "[email protected]")]
[TestState(TestState.Tested)]
public enum Keys
{
KeyCode = 65535,
Modifiers = -65536,
None = 0,
LButton = 1,
RButton = 2,
Cancel = RButton | LButton,
MButton = 4,
XButton1 = MButton | LButton,
XButton2 = MButton | RButton,
Back = 8,
Tab = Back | LButton,
LineFeed = Back | RButton,
Clear = Back | MButton,
Return = Clear | LButton,
Enter = Return,
ShiftKey = 16,
ControlKey = ShiftKey | LButton,
Menu = ShiftKey | RButton,
Pause = Menu | LButton,
Capital = ShiftKey | MButton,
CapsLock = Capital,
KanaMode = CapsLock | LButton,
HanguelMode = KanaMode,
HangulMode = HanguelMode,
JunjaMode = HangulMode | RButton,
FinalMode = ShiftKey | Back,
HanjaMode = FinalMode | LButton,
KanjiMode = HanjaMode,
Escape = KanjiMode | RButton,
IMEConvert = FinalMode | MButton,
IMENonconvert = IMEConvert | LButton,
IMEAccept = IMEConvert | RButton,
IMEAceept = IMEAccept,
IMEModeChange = IMEAceept | LButton,
Space = 32,
Prior = Space | LButton,
PageUp = Prior,
Next = Space | RButton,
PageDown = Next,
End = PageDown | LButton,
Home = Space | MButton,
Left = Home | LButton,
Up = Home | RButton,
Right = Up | LButton,
Down = Space | Back,
Select = Down | LButton,
Print = Down | RButton,
Execute = Print | LButton,
Snapshot = Down | MButton,
PrintScreen = Snapshot,
Insert = PrintScreen | LButton,
Delete = PrintScreen | RButton,
Help = Delete | LButton,
D0 = Space | ShiftKey,
D1 = D0 | LButton,
D2 = D0 | RButton,
D3 = D2 | LButton,
D4 = D0 | MButton,
D5 = D4 | LButton,
D6 = D4 | RButton,
D7 = D6 | LButton,
D8 = D0 | Back,
D9 = D8 | LButton,
A = 65,
B = 66,
C = B | LButton,
D = 68,
E = D | LButton,
F = D | RButton,
G = F | LButton,
H = 72,
I = H | LButton,
J = H | RButton,
K = J | LButton,
L = H | MButton,
M = L | LButton,
N = L | RButton,
O = N | LButton,
P = 80,
Q = P | LButton,
R = P | RButton,
S = R | LButton,
T = P | MButton,
U = T | LButton,
V = T | RButton,
W = V | LButton,
X = P | Back,
Y = X | LButton,
Z = X | RButton,
LWin = Z | LButton,
RWin = X | MButton,
Apps = RWin | LButton,
Sleep = Apps | RButton,
NumPad0 = 96,
NumPad1 = NumPad0 | LButton,
NumPad2 = NumPad0 | RButton,
NumPad3 = NumPad2 | LButton,
NumPad4 = NumPad0 | MButton,
NumPad5 = NumPad4 | LButton,
NumPad6 = NumPad4 | RButton,
NumPad7 = NumPad6 | LButton,
NumPad8 = NumPad0 | Back,
NumPad9 = NumPad8 | LButton,
Multiply = NumPad8 | RButton,
Add = Multiply | LButton,
Separator = NumPad8 | MButton,
Subtract = Separator | LButton,
Decimal = Separator | RButton,
Divide = Decimal | LButton,
F1 = NumPad0 | ShiftKey,
F2 = F1 | LButton,
F3 = F1 | RButton,
F4 = F3 | LButton,
F5 = F1 | MButton,
F6 = F5 | LButton,
F7 = F5 | RButton,
F8 = F7 | LButton,
F9 = F1 | Back,
F10 = F9 | LButton,
F11 = F9 | RButton,
F12 = F11 | LButton,
F13 = F9 | MButton,
F14 = F13 | LButton,
F15 = F13 | RButton,
F16 = F15 | LButton,
F17 = 128,
F18 = F17 | LButton,
F19 = F17 | RButton,
F20 = F19 | LButton,
F21 = F17 | MButton,
F22 = F21 | LButton,
F23 = F21 | RButton,
F24 = F23 | LButton,
NumLock = F17 | ShiftKey,
Scroll = NumLock | LButton,
LShiftKey = F17 | Space,
RShiftKey = LShiftKey | LButton,
LControlKey = LShiftKey | RButton,
RControlKey = LControlKey | LButton,
LMenu = LShiftKey | MButton,
RMenu = LMenu | LButton,
BrowserBack = LMenu | RButton,
BrowserForward = BrowserBack | LButton,
BrowserRefresh = LShiftKey | Back,
BrowserStop = BrowserRefresh | LButton,
BrowserSearch = BrowserRefresh | RButton,
BrowserFavorites = BrowserSearch | LButton,
BrowserHome = BrowserRefresh | MButton,
VolumeMute = BrowserHome | LButton,
VolumeDown = BrowserHome | RButton,
VolumeUp = VolumeDown | LButton,
MediaNextTrack = LShiftKey | ShiftKey,
MediaPreviousTrack = MediaNextTrack | LButton,
MediaStop = MediaNextTrack | RButton,
MediaPlayPause = MediaStop | LButton,
LaunchMail = MediaNextTrack | MButton,
SelectMedia = LaunchMail | LButton,
LaunchApplication1 = LaunchMail | RButton,
LaunchApplication2 = LaunchApplication1 | LButton,
OemSemicolon = MediaStop | Back,
Oem1 = OemSemicolon,
Oemplus = Oem1 | LButton,
Oemcomma = LaunchMail | Back,
OemMinus = Oemcomma | LButton,
OemPeriod = Oemcomma | RButton,
OemQuestion = OemPeriod | LButton,
Oem2 = OemQuestion,
Oemtilde = 192,
Oem3 = Oemtilde,
OemOpenBrackets = Oem3 | Escape,
Oem4 = OemOpenBrackets,
OemPipe = Oem3 | IMEConvert,
Oem5 = OemPipe,
OemCloseBrackets = Oem5 | LButton,
Oem6 = OemCloseBrackets,
OemQuotes = Oem5 | RButton,
Oem7 = OemQuotes,
Oem8 = Oem7 | LButton,
OemBackslash = Oem3 | PageDown,
Oem102 = OemBackslash,
ProcessKey = Oem3 | Left,
Packet = ProcessKey | RButton,
Attn = Oem102 | CapsLock,
Crsel = Attn | LButton,
Exsel = Oem3 | D8,
EraseEof = Exsel | LButton,
Play = Exsel | RButton,
Zoom = Play | LButton,
NoName = Exsel | MButton,
Pa1 = NoName | LButton,
OemClear = NoName | RButton,
Shift = 65536,
Control = 131072,
Alt = 262144,
LeftMouse = 524288,
RightMouse = 1048576,
MouseWheel = 2097152
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Text;
namespace System.Net.Http.Headers
{
// This type is used to store a collection of headers in 'headerStore':
// - A header can have multiple values.
// - A header can have an associated parser which is able to parse the raw string value into a strongly typed object.
// - If a header has an associated parser and the provided raw value can't be parsed, the value is considered
// invalid. Invalid values are stored if added using TryAddWithoutValidation(). If the value was added using Add(),
// Add() will throw FormatException.
// - Since parsing header values is expensive and users usually only care about a few headers, header values are
// lazily initialized.
//
// Given the properties above, a header value can have three states:
// - 'raw': The header value was added using TryAddWithoutValidation() and it wasn't parsed yet.
// - 'parsed': The header value was successfully parsed. It was either added using Add() where the value was parsed
// immediately, or if added using TryAddWithoutValidation() a user already accessed a property/method triggering the
// value to be parsed.
// - 'invalid': The header value was parsed, but parsing failed because the value is invalid. Storing invalid values
// allows users to still retrieve the value (by calling GetValues()), but it will not be exposed as strongly typed
// object. E.g. the client receives a response with the following header: 'Via: 1.1 proxy, invalid'
// - HttpHeaders.GetValues() will return "1.1 proxy", "invalid"
// - HttpResponseHeaders.Via collection will only contain one ViaHeaderValue object with value "1.1 proxy"
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix",
Justification = "This is not a collection")]
public abstract class HttpHeaders : IEnumerable<KeyValuePair<string, IEnumerable<string>>>
{
private Dictionary<string, HeaderStoreItemInfo> _headerStore;
private Dictionary<string, HttpHeaderParser> _parserStore;
private HashSet<string> _invalidHeaders;
private enum StoreLocation
{
Raw,
Invalid,
Parsed
}
protected HttpHeaders()
{
}
public void Add(string name, string value)
{
CheckHeaderName(name);
// We don't use GetOrCreateHeaderInfo() here, since this would create a new header in the store. If parsing
// the value then throws, we would have to remove the header from the store again. So just get a
// HeaderStoreItemInfo object and try to parse the value. If it works, we'll add the header.
HeaderStoreItemInfo info;
bool addToStore;
PrepareHeaderInfoForAdd(name, out info, out addToStore);
ParseAndAddValue(name, info, value);
// If we get here, then the value could be parsed correctly. If we created a new HeaderStoreItemInfo, add
// it to the store if we added at least one value.
if (addToStore && (info.ParsedValue != null))
{
AddHeaderToStore(name, info);
}
}
public void Add(string name, IEnumerable<string> values)
{
if (values == null)
{
throw new ArgumentNullException(nameof(values));
}
CheckHeaderName(name);
HeaderStoreItemInfo info;
bool addToStore;
PrepareHeaderInfoForAdd(name, out info, out addToStore);
try
{
// Note that if the first couple of values are valid followed by an invalid value, the valid values
// will be added to the store before the exception for the invalid value is thrown.
foreach (string value in values)
{
ParseAndAddValue(name, info, value);
}
}
finally
{
// Even if one of the values was invalid, make sure we add the header for the valid ones. We need to be
// consistent here: If values get added to an _existing_ header, then all values until the invalid one
// get added. Same here: If multiple values get added to a _new_ header, make sure the header gets added
// with the valid values.
// However, if all values for a _new_ header were invalid, then don't add the header.
if (addToStore && (info.ParsedValue != null))
{
AddHeaderToStore(name, info);
}
}
}
public bool TryAddWithoutValidation(string name, string value)
{
if (!TryCheckHeaderName(name))
{
return false;
}
if (value == null)
{
// We allow empty header values. (e.g. "My-Header: "). If the user adds multiple null/empty
// values, we'll just add them to the collection. This will result in delimiter-only values:
// E.g. adding two null-strings (or empty, or whitespace-only) results in "My-Header: ,".
value = string.Empty;
}
HeaderStoreItemInfo info = GetOrCreateHeaderInfo(name, false);
AddValue(info, value, StoreLocation.Raw);
return true;
}
public bool TryAddWithoutValidation(string name, IEnumerable<string> values)
{
if (values == null)
{
throw new ArgumentNullException(nameof(values));
}
if (!TryCheckHeaderName(name))
{
return false;
}
HeaderStoreItemInfo info = GetOrCreateHeaderInfo(name, false);
foreach (string value in values)
{
// We allow empty header values. (e.g. "My-Header: "). If the user adds multiple null/empty
// values, we'll just add them to the collection. This will result in delimiter-only values:
// E.g. adding two null-strings (or empty, or whitespace-only) results in "My-Header: ,".
AddValue(info, value ?? string.Empty, StoreLocation.Raw);
}
return true;
}
public void Clear()
{
if (_headerStore != null)
{
_headerStore.Clear();
}
}
public bool Remove(string name)
{
CheckHeaderName(name);
if (_headerStore == null)
{
return false;
}
return _headerStore.Remove(name);
}
public IEnumerable<string> GetValues(string name)
{
CheckHeaderName(name);
IEnumerable<string> values;
if (!TryGetValues(name, out values))
{
throw new InvalidOperationException("The given header was not found.");
}
return values;
}
public bool TryGetValues(string name, out IEnumerable<string> values)
{
if (!TryCheckHeaderName(name))
{
values = null;
return false;
}
if (_headerStore == null)
{
values = null;
return false;
}
HeaderStoreItemInfo info = null;
if (TryGetAndParseHeaderInfo(name, out info))
{
values = GetValuesAsStrings(info);
return true;
}
values = null;
return false;
}
public bool Contains(string name)
{
CheckHeaderName(name);
if (_headerStore == null)
{
return false;
}
// We can't just call headerStore.ContainsKey() since after parsing the value the header may not exist
// anymore (if the value contains invalid newline chars, we remove the header). So try to parse the
// header value.
HeaderStoreItemInfo info = null;
return TryGetAndParseHeaderInfo(name, out info);
}
public override string ToString()
{
if (_headerStore == null || _headerStore.Count == 0)
{
return string.Empty;
}
// Return all headers as string similar to:
// HeaderName1: Value1, Value2
// HeaderName2: Value1
// ...
StringBuilder sb = new StringBuilder();
foreach (var header in this)
{
sb.Append(header.Key);
sb.Append(": ");
sb.Append(this.GetHeaderString(header.Key));
sb.Append("\r\n");
}
return sb.ToString();
}
internal IEnumerable<KeyValuePair<string, string>> GetHeaderStrings()
{
if (_headerStore == null)
{
yield break;
}
foreach (var header in _headerStore)
{
HeaderStoreItemInfo info = header.Value;
string stringValue = GetHeaderString(info);
yield return new KeyValuePair<string, string>(header.Key, stringValue);
}
}
internal string GetHeaderString(string headerName)
{
return GetHeaderString(headerName, null);
}
internal string GetHeaderString(string headerName, object exclude)
{
HeaderStoreItemInfo info;
if (!TryGetHeaderInfo(headerName, out info))
{
return string.Empty;
}
return GetHeaderString(info, exclude);
}
private string GetHeaderString(HeaderStoreItemInfo info)
{
return GetHeaderString(info, null);
}
private string GetHeaderString(HeaderStoreItemInfo info, object exclude)
{
string stringValue = string.Empty; // returned if values.Length == 0
string[] values = GetValuesAsStrings(info, exclude);
if (values.Length == 1)
{
stringValue = values[0];
}
else
{
// Note that if we get multiple values for a header that doesn't support multiple values, we'll
// just separate the values using a comma (default separator).
string separator = HttpHeaderParser.DefaultSeparator;
if ((info.Parser != null) && (info.Parser.SupportsMultipleValues))
{
separator = info.Parser.Separator;
}
stringValue = string.Join(separator, values);
}
return stringValue;
}
#region IEnumerable<KeyValuePair<string, IEnumerable<string>>> Members
public IEnumerator<KeyValuePair<string, IEnumerable<string>>> GetEnumerator()
{
return _headerStore != null && _headerStore.Count > 0 ?
GetEnumeratorCore() :
Linq.Enumerable.Empty<KeyValuePair<string, IEnumerable<string>>>().GetEnumerator();
}
private IEnumerator<KeyValuePair<string, IEnumerable<string>>> GetEnumeratorCore()
{
List<string> invalidHeaders = null;
foreach (var header in _headerStore)
{
HeaderStoreItemInfo info = header.Value;
// Make sure we parse all raw values before returning the result. Note that this has to be
// done before we calculate the array length (next line): A raw value may contain a list of
// values.
if (!ParseRawHeaderValues(header.Key, info, false))
{
// We have an invalid header value (contains invalid newline chars). Mark it as "to-be-deleted"
// and skip this header.
if (invalidHeaders == null)
{
invalidHeaders = new List<string>();
}
invalidHeaders.Add(header.Key);
}
else
{
string[] values = GetValuesAsStrings(info);
yield return new KeyValuePair<string, IEnumerable<string>>(header.Key, values);
}
}
// While we were enumerating headers, we also parsed header values. If during parsing it turned out that
// the header value was invalid (contains invalid newline chars), remove the header from the store after
// completing the enumeration.
if (invalidHeaders != null)
{
Debug.Assert(_headerStore != null);
foreach (string invalidHeader in invalidHeaders)
{
_headerStore.Remove(invalidHeader);
}
}
}
#endregion
#region IEnumerable Members
Collections.IEnumerator Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
internal void SetConfiguration(Dictionary<string, HttpHeaderParser> parserStore,
HashSet<string> invalidHeaders)
{
Debug.Assert(_parserStore == null, "Parser store was already set.");
_parserStore = parserStore;
_invalidHeaders = invalidHeaders;
}
internal void AddParsedValue(string name, object value)
{
Debug.Assert((name != null) && (name.Length > 0));
Debug.Assert(HttpRuleParser.GetTokenLength(name, 0) == name.Length);
Debug.Assert(value != null);
HeaderStoreItemInfo info = GetOrCreateHeaderInfo(name, true);
Debug.Assert(info.Parser != null, "Can't add parsed value if there is no parser available.");
// If the current header has only one value, we can't add another value. The strongly typed property
// must not call AddParsedValue(), but SetParsedValue(). E.g. for headers like 'Date', 'Host'.
Debug.Assert(info.CanAddValue, "Header '" + name + "' doesn't support multiple values");
AddValue(info, value, StoreLocation.Parsed);
}
internal void SetParsedValue(string name, object value)
{
Debug.Assert((name != null) && (name.Length > 0));
Debug.Assert(HttpRuleParser.GetTokenLength(name, 0) == name.Length);
Debug.Assert(value != null);
// This method will first clear all values. This is used e.g. when setting the 'Date' or 'Host' header.
// I.e. headers not supporting collections.
HeaderStoreItemInfo info = GetOrCreateHeaderInfo(name, true);
Debug.Assert(info.Parser != null, "Can't add parsed value if there is no parser available.");
info.InvalidValue = null;
info.ParsedValue = null;
info.RawValue = null;
AddValue(info, value, StoreLocation.Parsed);
}
internal void SetOrRemoveParsedValue(string name, object value)
{
if (value == null)
{
Remove(name);
}
else
{
SetParsedValue(name, value);
}
}
internal bool RemoveParsedValue(string name, object value)
{
Debug.Assert((name != null) && (name.Length > 0));
Debug.Assert(HttpRuleParser.GetTokenLength(name, 0) == name.Length);
Debug.Assert(value != null);
if (_headerStore == null)
{
return false;
}
// If we have a value for this header, then verify if we have a single value. If so, compare that
// value with 'item'. If we have a list of values, then remove 'item' from the list.
HeaderStoreItemInfo info = null;
if (TryGetAndParseHeaderInfo(name, out info))
{
Debug.Assert(info.Parser != null, "Can't add parsed value if there is no parser available.");
Debug.Assert(info.Parser.SupportsMultipleValues,
"This method should not be used for single-value headers. Use Remove(string) instead.");
bool result = false;
// If there is no entry, just return.
if (info.ParsedValue == null)
{
return false;
}
IEqualityComparer comparer = info.Parser.Comparer;
List<object> parsedValues = info.ParsedValue as List<object>;
if (parsedValues == null)
{
Debug.Assert(info.ParsedValue.GetType() == value.GetType(),
"Stored value does not have the same type as 'value'.");
if (AreEqual(value, info.ParsedValue, comparer))
{
info.ParsedValue = null;
result = true;
}
}
else
{
foreach (object item in parsedValues)
{
Debug.Assert(item.GetType() == value.GetType(),
"One of the stored values does not have the same type as 'value'.");
if (AreEqual(value, item, comparer))
{
// Remove 'item' rather than 'value', since the 'comparer' may consider two values
// equal even though the default obj.Equals() may not (e.g. if 'comparer' does
// case-insensitive comparison for strings, but string.Equals() is case-sensitive).
result = parsedValues.Remove(item);
break;
}
}
// If we removed the last item in a list, remove the list.
if (parsedValues.Count == 0)
{
info.ParsedValue = null;
}
}
// If there is no value for the header left, remove the header.
if (info.IsEmpty)
{
bool headerRemoved = Remove(name);
Debug.Assert(headerRemoved, "Existing header '" + name + "' couldn't be removed.");
}
return result;
}
return false;
}
internal bool ContainsParsedValue(string name, object value)
{
Debug.Assert((name != null) && (name.Length > 0));
Debug.Assert(HttpRuleParser.GetTokenLength(name, 0) == name.Length);
Debug.Assert(value != null);
if (_headerStore == null)
{
return false;
}
// If we have a value for this header, then verify if we have a single value. If so, compare that
// value with 'item'. If we have a list of values, then compare each item in the list with 'item'.
HeaderStoreItemInfo info = null;
if (TryGetAndParseHeaderInfo(name, out info))
{
Debug.Assert(info.Parser != null, "Can't add parsed value if there is no parser available.");
Debug.Assert(info.Parser.SupportsMultipleValues,
"This method should not be used for single-value headers. Use equality comparer instead.");
// If there is no entry, just return.
if (info.ParsedValue == null)
{
return false;
}
List<object> parsedValues = info.ParsedValue as List<object>;
IEqualityComparer comparer = info.Parser.Comparer;
if (parsedValues == null)
{
Debug.Assert(info.ParsedValue.GetType() == value.GetType(),
"Stored value does not have the same type as 'value'.");
return AreEqual(value, info.ParsedValue, comparer);
}
else
{
foreach (object item in parsedValues)
{
Debug.Assert(item.GetType() == value.GetType(),
"One of the stored values does not have the same type as 'value'.");
if (AreEqual(value, item, comparer))
{
return true;
}
}
return false;
}
}
return false;
}
internal virtual void AddHeaders(HttpHeaders sourceHeaders)
{
Debug.Assert(sourceHeaders != null);
Debug.Assert(_parserStore == sourceHeaders._parserStore,
"Can only copy headers from an instance with the same header parsers.");
if (sourceHeaders._headerStore == null)
{
return;
}
List<string> invalidHeaders = null;
foreach (var header in sourceHeaders._headerStore)
{
// Only add header values if they're not already set on the message. Note that we don't merge
// collections: If both the default headers and the message have set some values for a certain
// header, then we don't try to merge the values.
if ((_headerStore == null) || (!_headerStore.ContainsKey(header.Key)))
{
HeaderStoreItemInfo sourceInfo = header.Value;
// If DefaultRequestHeaders values are copied to multiple messages, it is useful to parse these
// default header values only once. This is what we're doing here: By parsing raw headers in
// 'sourceHeaders' before copying values to our header store.
if (!sourceHeaders.ParseRawHeaderValues(header.Key, sourceInfo, false))
{
// If after trying to parse source header values no value is left (i.e. all values contain
// invalid newline chars), mark this header as 'to-be-deleted' and skip to the next header.
if (invalidHeaders == null)
{
invalidHeaders = new List<string>();
}
invalidHeaders.Add(header.Key);
}
else
{
AddHeaderInfo(header.Key, sourceInfo);
}
}
}
if (invalidHeaders != null)
{
Debug.Assert(sourceHeaders._headerStore != null);
foreach (string invalidHeader in invalidHeaders)
{
sourceHeaders._headerStore.Remove(invalidHeader);
}
}
}
private void AddHeaderInfo(string headerName, HeaderStoreItemInfo sourceInfo)
{
HeaderStoreItemInfo destinationInfo = CreateAndAddHeaderToStore(headerName);
Debug.Assert(sourceInfo.Parser == destinationInfo.Parser,
"Expected same parser on both source and destination header store for header '" + headerName +
"'.");
// We have custom header values. The parsed values are strings.
if (destinationInfo.Parser == null)
{
Debug.Assert((sourceInfo.RawValue == null) && (sourceInfo.InvalidValue == null),
"No raw or invalid values expected for custom headers.");
// Custom header values are always stored as string or list of strings.
destinationInfo.ParsedValue = CloneStringHeaderInfoValues(sourceInfo.ParsedValue);
}
else
{
// We have a parser, so we have to copy invalid values and clone parsed values.
// Invalid values are always strings. Strings are immutable. So we only have to clone the
// collection (if there is one).
destinationInfo.InvalidValue = CloneStringHeaderInfoValues(sourceInfo.InvalidValue);
// Now clone and add parsed values (if any).
if (sourceInfo.ParsedValue != null)
{
List<object> sourceValues = sourceInfo.ParsedValue as List<object>;
if (sourceValues == null)
{
CloneAndAddValue(destinationInfo, sourceInfo.ParsedValue);
}
else
{
foreach (object item in sourceValues)
{
CloneAndAddValue(destinationInfo, item);
}
}
}
}
}
private static void CloneAndAddValue(HeaderStoreItemInfo destinationInfo, object source)
{
// We only have one value. Clone it and assign it to the store.
ICloneable cloneableValue = source as ICloneable;
if (cloneableValue != null)
{
AddValue(destinationInfo, cloneableValue.Clone(), StoreLocation.Parsed);
}
else
{
// If it doesn't implement ICloneable, it's a value type or an immutable type like String/Uri.
AddValue(destinationInfo, source, StoreLocation.Parsed);
}
}
private static object CloneStringHeaderInfoValues(object source)
{
if (source == null)
{
return null;
}
List<object> sourceValues = source as List<object>;
if (sourceValues == null)
{
// If we just have one value, return the reference to the string (strings are immutable so it's OK
// to use the reference).
return source;
}
else
{
// If we have a list of strings, create a new list and copy all strings to the new list.
return new List<object>(sourceValues);
}
}
private HeaderStoreItemInfo GetOrCreateHeaderInfo(string name, bool parseRawValues)
{
Debug.Assert((name != null) && (name.Length > 0));
Debug.Assert(HttpRuleParser.GetTokenLength(name, 0) == name.Length);
HeaderStoreItemInfo result = null;
bool found = false;
if (parseRawValues)
{
found = TryGetAndParseHeaderInfo(name, out result);
}
else
{
found = TryGetHeaderInfo(name, out result);
}
if (!found)
{
result = CreateAndAddHeaderToStore(name);
}
return result;
}
private HeaderStoreItemInfo CreateAndAddHeaderToStore(string name)
{
// If we don't have the header in the store yet, add it now.
HeaderStoreItemInfo result = new HeaderStoreItemInfo(GetParser(name));
AddHeaderToStore(name, result);
return result;
}
private void AddHeaderToStore(string name, HeaderStoreItemInfo info)
{
if (_headerStore == null)
{
_headerStore = new Dictionary<string, HeaderStoreItemInfo>(
StringComparer.OrdinalIgnoreCase);
}
_headerStore.Add(name, info);
}
private bool TryGetHeaderInfo(string name, out HeaderStoreItemInfo info)
{
if (_headerStore == null)
{
info = null;
return false;
}
return _headerStore.TryGetValue(name, out info);
}
private bool TryGetAndParseHeaderInfo(string name, out HeaderStoreItemInfo info)
{
if (TryGetHeaderInfo(name, out info))
{
return ParseRawHeaderValues(name, info, true);
}
return false;
}
private bool ParseRawHeaderValues(string name, HeaderStoreItemInfo info, bool removeEmptyHeader)
{
// Prevent multiple threads from parsing the raw value at the same time, or else we would get
// false duplicates or false nulls.
lock (info)
{
// Unlike TryGetHeaderInfo() this method tries to parse all non-validated header values (if any)
// before returning to the caller.
if (info.RawValue != null)
{
List<string> rawValues = info.RawValue as List<string>;
if (rawValues == null)
{
ParseSingleRawHeaderValue(name, info);
}
else
{
ParseMultipleRawHeaderValues(name, info, rawValues);
}
// At this point all values are either in info.ParsedValue, info.InvalidValue, or were removed since they
// contain invalid newline chars. Reset RawValue.
info.RawValue = null;
// During parsing, we removed the value since it contains invalid newline chars. Return false to indicate that
// this is an empty header. If the caller specified to remove empty headers, we'll remove the header before
// returning.
if ((info.InvalidValue == null) && (info.ParsedValue == null))
{
if (removeEmptyHeader)
{
// After parsing the raw value, no value is left because all values contain invalid newline
// chars.
Debug.Assert(_headerStore != null);
_headerStore.Remove(name);
}
return false;
}
}
}
return true;
}
private static void ParseMultipleRawHeaderValues(string name, HeaderStoreItemInfo info, List<string> rawValues)
{
if (info.Parser == null)
{
foreach (string rawValue in rawValues)
{
if (!ContainsInvalidNewLine(rawValue, name))
{
AddValue(info, rawValue, StoreLocation.Parsed);
}
}
}
else
{
foreach (string rawValue in rawValues)
{
if (!TryParseAndAddRawHeaderValue(name, info, rawValue, true))
{
}
}
}
}
private static void ParseSingleRawHeaderValue(string name, HeaderStoreItemInfo info)
{
string rawValue = info.RawValue as string;
Debug.Assert(rawValue != null, "RawValue must either be List<string> or string.");
if (info.Parser == null)
{
if (!ContainsInvalidNewLine(rawValue, name))
{
AddValue(info, rawValue, StoreLocation.Parsed);
}
}
else
{
if (!TryParseAndAddRawHeaderValue(name, info, rawValue, true))
{
}
}
}
// See Add(name, string)
internal bool TryParseAndAddValue(string name, string value)
{
// We don't use GetOrCreateHeaderInfo() here, since this would create a new header in the store. If parsing
// the value then throws, we would have to remove the header from the store again. So just get a
// HeaderStoreItemInfo object and try to parse the value. If it works, we'll add the header.
HeaderStoreItemInfo info;
bool addToStore;
PrepareHeaderInfoForAdd(name, out info, out addToStore);
bool result = TryParseAndAddRawHeaderValue(name, info, value, false);
if (result && addToStore && (info.ParsedValue != null))
{
// If we get here, then the value could be parsed correctly. If we created a new HeaderStoreItemInfo, add
// it to the store if we added at least one value.
AddHeaderToStore(name, info);
}
return result;
}
// See ParseAndAddValue
private static bool TryParseAndAddRawHeaderValue(string name, HeaderStoreItemInfo info, string value, bool addWhenInvalid)
{
Debug.Assert(info != null);
Debug.Assert(info.Parser != null);
// Values are added as 'invalid' if we either can't parse the value OR if we already have a value
// and the current header doesn't support multiple values: e.g. trying to add a date/time value
// to the 'Date' header if we already have a date/time value will result in the second value being
// added to the 'invalid' header values.
if (!info.CanAddValue)
{
if (addWhenInvalid)
{
AddValue(info, value ?? string.Empty, StoreLocation.Invalid);
}
return false;
}
int index = 0;
object parsedValue = null;
if (info.Parser.TryParseValue(value, info.ParsedValue, ref index, out parsedValue))
{
// The raw string only represented one value (which was successfully parsed). Add the value and return.
if ((value == null) || (index == value.Length))
{
if (parsedValue != null)
{
AddValue(info, parsedValue, StoreLocation.Parsed);
}
return true;
}
Debug.Assert(index < value.Length, "Parser must return an index value within the string length.");
// If we successfully parsed a value, but there are more left to read, store the results in a temp
// list. Only when all values are parsed successfully write the list to the store.
List<object> parsedValues = new List<object>();
if (parsedValue != null)
{
parsedValues.Add(parsedValue);
}
while (index < value.Length)
{
if (info.Parser.TryParseValue(value, info.ParsedValue, ref index, out parsedValue))
{
if (parsedValue != null)
{
parsedValues.Add(parsedValue);
}
}
else
{
if (!ContainsInvalidNewLine(value, name) && addWhenInvalid)
{
AddValue(info, value, StoreLocation.Invalid);
}
return false;
}
}
// All values were parsed correctly. Copy results to the store.
foreach (object item in parsedValues)
{
AddValue(info, item, StoreLocation.Parsed);
}
return true;
}
if (!ContainsInvalidNewLine(value, name) && addWhenInvalid)
{
AddValue(info, value ?? string.Empty, StoreLocation.Invalid);
}
return false;
}
private static void AddValue(HeaderStoreItemInfo info, object value, StoreLocation location)
{
// Since we have the same pattern for all three store locations (raw, invalid, parsed), we use
// this helper method to deal with adding values:
// - if 'null' just set the store property to 'value'
// - if 'List<T>' append 'value' to the end of the list
// - if 'T', i.e. we have already a value stored (but no list), create a list, add the stored value
// to the list and append 'value' at the end of the newly created list.
Debug.Assert((info.Parser != null) || ((info.Parser == null) && (value.GetType() == typeof(string))),
"If no parser is defined, then the value must be string.");
object currentStoreValue = null;
switch (location)
{
case StoreLocation.Raw:
currentStoreValue = info.RawValue;
AddValueToStoreValue<string>(info, value, ref currentStoreValue);
info.RawValue = currentStoreValue;
break;
case StoreLocation.Invalid:
currentStoreValue = info.InvalidValue;
AddValueToStoreValue<string>(info, value, ref currentStoreValue);
info.InvalidValue = currentStoreValue;
break;
case StoreLocation.Parsed:
Debug.Assert((value == null) || (!(value is List<object>)),
"Header value types must not derive from List<object> since this type is used internally to store " +
"lists of values. So we would not be able to distinguish between a single value and a list of values.");
currentStoreValue = info.ParsedValue;
AddValueToStoreValue<object>(info, value, ref currentStoreValue);
info.ParsedValue = currentStoreValue;
break;
default:
Debug.Assert(false, "Unknown StoreLocation value: " + location.ToString());
break;
}
}
private static void AddValueToStoreValue<T>(HeaderStoreItemInfo info, object value,
ref object currentStoreValue) where T : class
{
// If there is no value set yet, then add current item as value (we don't create a list
// if not required). If 'info.Value' is already assigned then make sure 'info.Value' is a
// List<T> and append 'item' to the list.
if (currentStoreValue == null)
{
currentStoreValue = value;
}
else
{
List<T> storeValues = currentStoreValue as List<T>;
if (storeValues == null)
{
storeValues = new List<T>(2);
Debug.Assert(value is T);
storeValues.Add(currentStoreValue as T);
currentStoreValue = storeValues;
}
Debug.Assert(value is T);
storeValues.Add(value as T);
}
}
// Since most of the time we just have 1 value, we don't create a List<object> for one value, but we change
// the return type to 'object'. The caller has to deal with the return type (object vs. List<object>). This
// is to optimize the most common scenario where a header has only one value.
internal object GetParsedValues(string name)
{
Debug.Assert((name != null) && (name.Length > 0));
Debug.Assert(HttpRuleParser.GetTokenLength(name, 0) == name.Length);
HeaderStoreItemInfo info = null;
if (!TryGetAndParseHeaderInfo(name, out info))
{
return null;
}
return info.ParsedValue;
}
private void PrepareHeaderInfoForAdd(string name, out HeaderStoreItemInfo info, out bool addToStore)
{
info = null;
addToStore = false;
if (!TryGetAndParseHeaderInfo(name, out info))
{
info = new HeaderStoreItemInfo(GetParser(name));
addToStore = true;
}
}
private void ParseAndAddValue(string name, HeaderStoreItemInfo info, string value)
{
Debug.Assert(info != null);
if (info.Parser == null)
{
// If we don't have a parser for the header, we consider the value valid if it doesn't contains
// invalid newline characters. We add the values as "parsed value". Note that we allow empty values.
CheckInvalidNewLine(value);
AddValue(info, value ?? string.Empty, StoreLocation.Parsed);
return;
}
// If the header only supports 1 value, we can add the current value only if there is no
// value already set.
if (!info.CanAddValue)
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, "Cannot add value because header '{0}' does not support multiple values.", name));
}
int index = 0;
object parsedValue = info.Parser.ParseValue(value, info.ParsedValue, ref index);
// The raw string only represented one value (which was successfully parsed). Add the value and return.
// If value is null we still have to first call ParseValue() to allow the parser to decide whether null is
// a valid value. If it is (i.e. no exception thrown), we set the parsed value (if any) and return.
if ((value == null) || (index == value.Length))
{
// If the returned value is null, then it means the header accepts empty values. I.e. we don't throw
// but we don't add 'null' to the store either.
if (parsedValue != null)
{
AddValue(info, parsedValue, StoreLocation.Parsed);
}
return;
}
Debug.Assert(index < value.Length, "Parser must return an index value within the string length.");
// If we successfully parsed a value, but there are more left to read, store the results in a temp
// list. Only when all values are parsed successfully write the list to the store.
List<object> parsedValues = new List<object>();
if (parsedValue != null)
{
parsedValues.Add(parsedValue);
}
while (index < value.Length)
{
parsedValue = info.Parser.ParseValue(value, info.ParsedValue, ref index);
if (parsedValue != null)
{
parsedValues.Add(parsedValue);
}
}
// All values were parsed correctly. Copy results to the store.
foreach (object item in parsedValues)
{
AddValue(info, item, StoreLocation.Parsed);
}
}
private HttpHeaderParser GetParser(string name)
{
if (_parserStore == null)
{
return null;
}
HttpHeaderParser parser = null;
if (_parserStore.TryGetValue(name, out parser))
{
return parser;
}
return null;
}
private void CheckHeaderName(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException("The value cannot be null or empty.", nameof(name));
}
if (HttpRuleParser.GetTokenLength(name, 0) != name.Length)
{
throw new FormatException("The header name format is invalid.");
}
if ((_invalidHeaders != null) && (_invalidHeaders.Contains(name)))
{
throw new InvalidOperationException("Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.");
}
}
private bool TryCheckHeaderName(string name)
{
if (string.IsNullOrEmpty(name))
{
return false;
}
if (HttpRuleParser.GetTokenLength(name, 0) != name.Length)
{
return false;
}
if ((_invalidHeaders != null) && (_invalidHeaders.Contains(name)))
{
return false;
}
return true;
}
private static void CheckInvalidNewLine(string value)
{
if (value == null)
{
return;
}
if (HttpRuleParser.ContainsInvalidNewLine(value))
{
throw new FormatException("New-line characters in header values must be followed by a white-space character.");
}
}
private static bool ContainsInvalidNewLine(string value, string name)
{
if (HttpRuleParser.ContainsInvalidNewLine(value))
{
return true;
}
return false;
}
private static string[] GetValuesAsStrings(HeaderStoreItemInfo info)
{
return GetValuesAsStrings(info, null);
}
// When doing exclusion comparison, assume raw values have been parsed.
private static string[] GetValuesAsStrings(HeaderStoreItemInfo info, object exclude)
{
int length = GetValueCount(info);
string[] values = new string[length];
if (length > 0)
{
int currentIndex = 0;
ReadStoreValues<string>(values, info.RawValue, null, null, ref currentIndex);
ReadStoreValues<object>(values, info.ParsedValue, info.Parser, exclude, ref currentIndex);
// Set parser parameter to 'null' for invalid values: The invalid values is always a string so we
// don't need the parser to "serialize" the value to a string.
ReadStoreValues<string>(values, info.InvalidValue, null, null, ref currentIndex);
// The values array may not be full because some values were excluded
if (currentIndex < length)
{
string[] trimmedValues = new string[currentIndex];
Array.Copy(values, 0, trimmedValues, 0, currentIndex);
values = trimmedValues;
}
}
return values;
}
private static int GetValueCount(HeaderStoreItemInfo info)
{
Debug.Assert(info != null);
int valueCount = 0;
UpdateValueCount<string>(info.RawValue, ref valueCount);
UpdateValueCount<string>(info.InvalidValue, ref valueCount);
UpdateValueCount<object>(info.ParsedValue, ref valueCount);
return valueCount;
}
private static void UpdateValueCount<T>(object valueStore, ref int valueCount)
{
if (valueStore == null)
{
return;
}
List<T> values = valueStore as List<T>;
if (values != null)
{
valueCount += values.Count;
}
else
{
valueCount++;
}
}
private static void ReadStoreValues<T>(string[] values, object storeValue, HttpHeaderParser parser,
T exclude, ref int currentIndex)
{
Debug.Assert(values != null);
if (storeValue != null)
{
List<T> storeValues = storeValue as List<T>;
if (storeValues == null)
{
if (ShouldAdd<T>(storeValue, parser, exclude))
{
values[currentIndex] = parser == null ? storeValue.ToString() : parser.ToString(storeValue);
currentIndex++;
}
}
else
{
foreach (object item in storeValues)
{
if (ShouldAdd<T>(item, parser, exclude))
{
values[currentIndex] = parser == null ? item.ToString() : parser.ToString(item);
currentIndex++;
}
}
}
}
}
private static bool ShouldAdd<T>(object storeValue, HttpHeaderParser parser, T exclude)
{
bool add = true;
if (parser != null && exclude != null)
{
if (parser.Comparer != null)
{
add = !parser.Comparer.Equals(exclude, storeValue);
}
else
{
add = !exclude.Equals(storeValue);
}
}
return add;
}
private bool AreEqual(object value, object storeValue, IEqualityComparer comparer)
{
Debug.Assert(value != null);
if (comparer != null)
{
return comparer.Equals(value, storeValue);
}
// We don't have a comparer, so use the Equals() method.
return value.Equals(storeValue);
}
#region Private Classes
private class HeaderStoreItemInfo
{
private object _rawValue;
private object _invalidValue;
private object _parsedValue;
private HttpHeaderParser _parser;
internal object RawValue
{
get { return _rawValue; }
set { _rawValue = value; }
}
internal object InvalidValue
{
get { return _invalidValue; }
set { _invalidValue = value; }
}
internal object ParsedValue
{
get { return _parsedValue; }
set { _parsedValue = value; }
}
internal HttpHeaderParser Parser
{
get { return _parser; }
}
internal bool CanAddValue
{
get
{
Debug.Assert(_parser != null,
"There should be no reason to call CanAddValue if there is no parser for the current header.");
// If the header only supports one value, and we have already a value set, then we can't add
// another value. E.g. the 'Date' header only supports one value. We can't add multiple timestamps
// to 'Date'.
// So if this is a known header, ask the parser if it supports multiple values and check whether
// we already have a (valid or invalid) value.
// Note that we ignore the rawValue by purpose: E.g. we are parsing 2 raw values for a header only
// supporting 1 value. When the first value gets parsed, CanAddValue returns true and we add the
// parsed value to ParsedValue. When the second value is parsed, CanAddValue returns false, because
// we have already a parsed value.
return ((_parser.SupportsMultipleValues) || ((_invalidValue == null) && (_parsedValue == null)));
}
}
internal bool IsEmpty
{
get { return ((_rawValue == null) && (_invalidValue == null) && (_parsedValue == null)); }
}
internal HeaderStoreItemInfo(HttpHeaderParser parser)
{
// Can be null.
_parser = parser;
}
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Datastream
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Apache.Ignite.Core.Datastream;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Unmanaged;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
/// <summary>
/// Data streamer internal interface to get rid of generics.
/// </summary>
internal interface IDataStreamer
{
/// <summary>
/// Callback invoked on topology size change.
/// </summary>
/// <param name="topVer">New topology version.</param>
/// <param name="topSize">New topology size.</param>
void TopologyChange(long topVer, int topSize);
}
/// <summary>
/// Data streamer implementation.
/// </summary>
internal class DataStreamerImpl<TK, TV> : PlatformDisposableTarget, IDataStreamer, IDataStreamer<TK, TV>
{
#pragma warning disable 0420
/** Policy: continue. */
internal const int PlcContinue = 0;
/** Policy: close. */
internal const int PlcClose = 1;
/** Policy: cancel and close. */
internal const int PlcCancelClose = 2;
/** Policy: flush. */
internal const int PlcFlush = 3;
/** Operation: update. */
private const int OpUpdate = 1;
/** Operation: set receiver. */
private const int OpReceiver = 2;
/** Cache name. */
private readonly string _cacheName;
/** Lock. */
private readonly ReaderWriterLockSlim _rwLock = new ReaderWriterLockSlim();
/** Closed event. */
private readonly ManualResetEventSlim _closedEvt = new ManualResetEventSlim(false);
/** Close future. */
private readonly Future<object> _closeFut = new Future<object>();
/** GC handle to this streamer. */
private readonly long _hnd;
/** Topology version. */
private long _topVer;
/** Topology size. */
private int _topSize;
/** Buffer send size. */
private volatile int _bufSndSize;
/** Current data streamer batch. */
private volatile DataStreamerBatch<TK, TV> _batch;
/** Flusher. */
private readonly Flusher<TK, TV> _flusher;
/** Receiver. */
private volatile IStreamReceiver<TK, TV> _rcv;
/** Receiver handle. */
private long _rcvHnd;
/** Receiver binary mode. */
private readonly bool _keepBinary;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="cacheName">Cache name.</param>
/// <param name="keepBinary">Binary flag.</param>
public DataStreamerImpl(IUnmanagedTarget target, Marshaller marsh, string cacheName, bool keepBinary)
: base(target, marsh)
{
_cacheName = cacheName;
_keepBinary = keepBinary;
// Create empty batch.
_batch = new DataStreamerBatch<TK, TV>();
// Allocate GC handle so that this data streamer could be easily dereferenced from native code.
WeakReference thisRef = new WeakReference(this);
_hnd = marsh.Ignite.HandleRegistry.Allocate(thisRef);
// Start topology listening. This call will ensure that buffer size member is updated.
UU.DataStreamerListenTopology(target, _hnd);
// Membar to ensure fields initialization before leaving constructor.
Thread.MemoryBarrier();
// Start flusher after everything else is initialized.
_flusher = new Flusher<TK, TV>(thisRef);
_flusher.RunThread();
}
/** <inheritDoc /> */
public string CacheName
{
get { return _cacheName; }
}
/** <inheritDoc /> */
public bool AllowOverwrite
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return UU.DataStreamerAllowOverwriteGet(Target);
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
UU.DataStreamerAllowOverwriteSet(Target, value);
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public bool SkipStore
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return UU.DataStreamerSkipStoreGet(Target);
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
UU.DataStreamerSkipStoreSet(Target, value);
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public int PerNodeBufferSize
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return UU.DataStreamerPerNodeBufferSizeGet(Target);
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
UU.DataStreamerPerNodeBufferSizeSet(Target, value);
_bufSndSize = _topSize * value;
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public int PerNodeParallelOperations
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return UU.DataStreamerPerNodeParallelOperationsGet(Target);
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
UU.DataStreamerPerNodeParallelOperationsSet(Target, value);
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public long AutoFlushFrequency
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return _flusher.Frequency;
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
_flusher.Frequency = value;
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public Task Task
{
get
{
ThrowIfDisposed();
return _closeFut.Task;
}
}
/** <inheritDoc /> */
public IStreamReceiver<TK, TV> Receiver
{
get
{
ThrowIfDisposed();
return _rcv;
}
set
{
IgniteArgumentCheck.NotNull(value, "value");
var handleRegistry = Marshaller.Ignite.HandleRegistry;
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
if (_rcv == value)
return;
var rcvHolder = new StreamReceiverHolder(value,
(rec, grid, cache, stream, keepBinary) =>
StreamReceiverHolder.InvokeReceiver((IStreamReceiver<TK, TV>) rec, grid, cache, stream,
keepBinary));
var rcvHnd0 = handleRegistry.Allocate(rcvHolder);
try
{
DoOutOp(OpReceiver, w =>
{
w.WriteLong(rcvHnd0);
w.WriteObject(rcvHolder);
});
}
catch (Exception)
{
handleRegistry.Release(rcvHnd0);
throw;
}
if (_rcv != null)
handleRegistry.Release(_rcvHnd);
_rcv = value;
_rcvHnd = rcvHnd0;
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public Task AddData(TK key, TV val)
{
ThrowIfDisposed();
IgniteArgumentCheck.NotNull(key, "key");
return Add0(new DataStreamerEntry<TK, TV>(key, val), 1);
}
/** <inheritDoc /> */
public Task AddData(KeyValuePair<TK, TV> pair)
{
ThrowIfDisposed();
return Add0(new DataStreamerEntry<TK, TV>(pair.Key, pair.Value), 1);
}
/** <inheritDoc /> */
public Task AddData(ICollection<KeyValuePair<TK, TV>> entries)
{
ThrowIfDisposed();
IgniteArgumentCheck.NotNull(entries, "entries");
return Add0(entries, entries.Count);
}
/** <inheritDoc /> */
public Task RemoveData(TK key)
{
ThrowIfDisposed();
IgniteArgumentCheck.NotNull(key, "key");
return Add0(new DataStreamerRemoveEntry<TK>(key), 1);
}
/** <inheritDoc /> */
public void TryFlush()
{
ThrowIfDisposed();
DataStreamerBatch<TK, TV> batch0 = _batch;
if (batch0 != null)
Flush0(batch0, false, PlcFlush);
}
/** <inheritDoc /> */
public void Flush()
{
ThrowIfDisposed();
DataStreamerBatch<TK, TV> batch0 = _batch;
if (batch0 != null)
Flush0(batch0, true, PlcFlush);
else
{
// Batch is null, i.e. data streamer is closing. Wait for close to complete.
_closedEvt.Wait();
}
}
/** <inheritDoc /> */
public void Close(bool cancel)
{
_flusher.Stop();
while (true)
{
DataStreamerBatch<TK, TV> batch0 = _batch;
if (batch0 == null)
{
// Wait for concurrent close to finish.
_closedEvt.Wait();
return;
}
if (Flush0(batch0, true, cancel ? PlcCancelClose : PlcClose))
{
_closeFut.OnDone(null, null);
_rwLock.EnterWriteLock();
try
{
base.Dispose(true);
if (_rcv != null)
Marshaller.Ignite.HandleRegistry.Release(_rcvHnd);
_closedEvt.Set();
}
finally
{
_rwLock.ExitWriteLock();
}
Marshaller.Ignite.HandleRegistry.Release(_hnd);
break;
}
}
}
/** <inheritDoc /> */
public IDataStreamer<TK1, TV1> WithKeepBinary<TK1, TV1>()
{
if (_keepBinary)
{
var result = this as IDataStreamer<TK1, TV1>;
if (result == null)
throw new InvalidOperationException(
"Can't change type of binary streamer. WithKeepBinary has been called on an instance of " +
"binary streamer with incompatible generic arguments.");
return result;
}
return new DataStreamerImpl<TK1, TV1>(UU.ProcessorDataStreamer(Marshaller.Ignite.InteropProcessor,
_cacheName, true), Marshaller, _cacheName, true);
}
/** <inheritDoc /> */
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
protected override void Dispose(bool disposing)
{
if (disposing)
Close(false); // Normal dispose: do not cancel
else
{
// Finalizer: just close Java streamer
try
{
if (_batch != null)
_batch.Send(this, PlcCancelClose);
}
// ReSharper disable once EmptyGeneralCatchClause
catch (Exception)
{
// Finalizers should never throw
}
Marshaller.Ignite.HandleRegistry.Release(_hnd, true);
Marshaller.Ignite.HandleRegistry.Release(_rcvHnd, true);
}
base.Dispose(false);
}
/** <inheritDoc /> */
~DataStreamerImpl()
{
Dispose(false);
}
/** <inheritDoc /> */
public void TopologyChange(long topVer, int topSize)
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
if (_topVer < topVer)
{
_topVer = topVer;
_topSize = topSize;
_bufSndSize = topSize * UU.DataStreamerPerNodeBufferSizeGet(Target);
}
}
finally
{
_rwLock.ExitWriteLock();
}
}
/// <summary>
/// Internal add/remove routine.
/// </summary>
/// <param name="val">Value.</param>
/// <param name="cnt">Items count.</param>
/// <returns>Future.</returns>
private Task Add0(object val, int cnt)
{
int bufSndSize0 = _bufSndSize;
while (true)
{
var batch0 = _batch;
if (batch0 == null)
throw new InvalidOperationException("Data streamer is stopped.");
int size = batch0.Add(val, cnt);
if (size == -1)
{
// Batch is blocked, perform CAS.
Interlocked.CompareExchange(ref _batch,
new DataStreamerBatch<TK, TV>(batch0), batch0);
continue;
}
if (size >= bufSndSize0)
// Batch is too big, schedule flush.
Flush0(batch0, false, PlcContinue);
return batch0.Task;
}
}
/// <summary>
/// Internal flush routine.
/// </summary>
/// <param name="curBatch"></param>
/// <param name="wait">Whether to wait for flush to complete.</param>
/// <param name="plc">Whether this is the last batch.</param>
/// <returns>Whether this call was able to CAS previous batch</returns>
private bool Flush0(DataStreamerBatch<TK, TV> curBatch, bool wait, int plc)
{
// 1. Try setting new current batch to help further adders.
bool res = Interlocked.CompareExchange(ref _batch,
(plc == PlcContinue || plc == PlcFlush) ?
new DataStreamerBatch<TK, TV>(curBatch) : null, curBatch) == curBatch;
// 2. Perform actual send.
curBatch.Send(this, plc);
if (wait)
// 3. Wait for all futures to finish.
curBatch.AwaitCompletion();
return res;
}
/// <summary>
/// Start write.
/// </summary>
/// <returns>Writer.</returns>
internal void Update(Action<BinaryWriter> action)
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
DoOutOp(OpUpdate, action);
}
finally
{
_rwLock.ExitReadLock();
}
}
/// <summary>
/// Flusher.
/// </summary>
private class Flusher<TK1, TV1>
{
/** State: running. */
private const int StateRunning = 0;
/** State: stopping. */
private const int StateStopping = 1;
/** State: stopped. */
private const int StateStopped = 2;
/** Data streamer. */
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields",
Justification = "Incorrect warning")]
private readonly WeakReference _ldrRef;
/** Finish flag. */
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields",
Justification = "Incorrect warning")]
private int _state;
/** Flush frequency. */
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields",
Justification = "Incorrect warning")]
private long _freq;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="ldrRef">Data streamer weak reference..</param>
public Flusher(WeakReference ldrRef)
{
_ldrRef = ldrRef;
lock (this)
{
_state = StateRunning;
}
}
/// <summary>
/// Main flusher routine.
/// </summary>
private void Run()
{
bool force = false;
long curFreq = 0;
try
{
while (true)
{
if (curFreq > 0 || force)
{
var ldr = _ldrRef.Target as DataStreamerImpl<TK1, TV1>;
if (ldr == null)
return;
ldr.TryFlush();
force = false;
}
lock (this)
{
// Stop immediately.
if (_state == StateStopping)
return;
if (curFreq == _freq)
{
// Frequency is unchanged
if (curFreq == 0)
// Just wait for a second and re-try.
Monitor.Wait(this, 1000);
else
{
// Calculate remaining time.
DateTime now = DateTime.Now;
long ticks;
try
{
ticks = now.AddMilliseconds(curFreq).Ticks - now.Ticks;
if (ticks > int.MaxValue)
ticks = int.MaxValue;
}
catch (ArgumentOutOfRangeException)
{
// Handle possible overflow.
ticks = int.MaxValue;
}
Monitor.Wait(this, TimeSpan.FromTicks(ticks));
}
}
else
{
if (curFreq != 0)
force = true;
curFreq = _freq;
}
}
}
}
finally
{
// Let streamer know about stop.
lock (this)
{
_state = StateStopped;
Monitor.PulseAll(this);
}
}
}
/// <summary>
/// Frequency.
/// </summary>
public long Frequency
{
get
{
return Interlocked.Read(ref _freq);
}
set
{
lock (this)
{
if (_freq != value)
{
_freq = value;
Monitor.PulseAll(this);
}
}
}
}
/// <summary>
/// Stop flusher.
/// </summary>
public void Stop()
{
lock (this)
{
if (_state == StateRunning)
{
_state = StateStopping;
Monitor.PulseAll(this);
}
while (_state != StateStopped)
Monitor.Wait(this);
}
}
/// <summary>
/// Runs the flusher thread.
/// </summary>
public void RunThread()
{
new Thread(Run).Start();
}
}
#pragma warning restore 0420
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.Background;
using Windows.ApplicationModel.Store;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;
using AppStudio.Common;
using AppStudio.Common.Services;
using AppStudio.Common.Navigation;
using DJNanoShow.Services;
#if WINDOWS_APP
using Windows.System;
using Windows.UI.Core;
using Windows.UI.ApplicationSettings;
using DJNanoShow.AppFlyouts;
#endif
#if WINDOWS_PHONE_APP
using Windows.Phone.UI.Input;
#endif
namespace DJNanoShow
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
public sealed partial class App : Windows.UI.Xaml.Application
{
private Guid APP_ID = new Guid("2a4aecfd-7ef0-487a-b45f-785033404119");
public const string APP_NAME = "DJNano Show";
#if WINDOWS_PHONE_APP
private TransitionCollection transitions;
#endif
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
Microsoft.ApplicationInsights.WindowsCollectors.Session |
Microsoft.ApplicationInsights.WindowsCollectors.PageView |
Microsoft.ApplicationInsights.WindowsCollectors.UnhandledException);
this.InitializeComponent();
this.Suspending += this.OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used when the application is launched to open a specific file, to display
/// search results, and so forth.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
GetAppData();
UpdateAppTiles();
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
// TODO: change this value to a cache size that is appropriate for your application
rootFrame.CacheSize = 1;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
// TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
NavigationService.Initialize(this.GetType(), rootFrame);
if (rootFrame.Content == null)
{
#if WINDOWS_PHONE_APP
// Removes the turnstile navigation for startup.
if (rootFrame.ContentTransitions != null)
{
this.transitions = new TransitionCollection();
foreach (var c in rootFrame.ContentTransitions)
{
this.transitions.Add(c);
}
}
rootFrame.ContentTransitions = null;
rootFrame.Navigated += this.RootFrame_FirstNavigated;
#endif
#if WINDOWS_PHONE_APP
Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
#else
//// Keyboard and mouse navigation only apply when occupying the entire window
//if (Page.ActualHeight == Window.Current.Bounds.Height &&
// Page.ActualWidth == Window.Current.Bounds.Width)
//{
// Listen to the window directly so focus isn't required
Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated += CoreDispatcher_AcceleratorKeyActivated;
Window.Current.CoreWindow.PointerPressed += this.CoreWindow_PointerPressed;
//}
#endif
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
if (!rootFrame.Navigate(typeof(MainPage), e.Arguments))
{
throw new Exception("Failed to create initial page");
}
}
// Ensure the current window is active
Window.Current.Activate();
}
#if WINDOWS_PHONE_APP
/// <summary>
/// Restores the content transitions after the app has launched.
/// </summary>
/// <param name="sender">The object where the handler is attached.</param>
/// <param name="e">Details about the navigation event.</param>
private void RootFrame_FirstNavigated(object sender, NavigationEventArgs e)
{
var rootFrame = sender as Frame;
rootFrame.ContentTransitions = this.transitions ?? new TransitionCollection() { new NavigationThemeTransition() };
rootFrame.Navigated -= this.RootFrame_FirstNavigated;
}
#endif
private void GetAppData()
{
#if WINDOWS_PHONE_APP
string deviceType = LocalSettingNames.PhoneValue;
#else
string deviceType = LocalSettingNames.WindowsValue;
#endif
ApplicationData.Current.LocalSettings.Values[LocalSettingNames.DeviceType] = deviceType;
ApplicationData.Current.LocalSettings.Values[LocalSettingNames.StoreId] = ValidateStoreId();
}
private Guid ValidateStoreId()
{
try
{
Guid storeId = CurrentApp.AppId;
if (storeId != Guid.Empty && storeId != APP_ID)
{
return storeId;
}
return Guid.Empty;
}
catch (Exception)
{
return Guid.Empty;
}
}
private void UpdateAppTiles()
{
var init = ApplicationData.Current.LocalSettings.Values[LocalSettingNames.TilesInitialized];
if (init == null || (init is bool && !(bool)init))
{
Dictionary<string, string> tiles = new Dictionary<string, string>();
tiles.Add("9f187f0a90da337f", "DataImages/Tile1.jpg");
tiles.Add("9f187f0a90da3380", "DataImages/Tile2.jpg");
tiles.Add("9f187f0a90da3381", "DataImages/Tile3.jpg");
tiles.Add("9f187f0a90da3382", "DataImages/Tile4.jpg");
tiles.Add("9f187f0a90da3383", "DataImages/Tile5.jpg");
TileServices.CreateCycleTile(tiles);
ApplicationData.Current.LocalSettings.Values[LocalSettingNames.TilesInitialized] = true;
}
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
// TODO: Save application state and stop any background activity
deferral.Complete();
}
#if WINDOWS_APP
protected override void OnWindowCreated(WindowCreatedEventArgs args)
{
SettingsPane.GetForCurrentView().CommandsRequested += OnCommandsRequested;
base.OnWindowCreated(args);
}
private void OnCommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
{
args.Request.ApplicationCommands.Add(new SettingsCommand("Privacy", "Privacy", (handler) => ShowPrivacySettingFlyout()));
args.Request.ApplicationCommands.Add(new SettingsCommand("About", "About", (handler) => ShowAboutSettingFlyout()));
}
private void ShowPrivacySettingFlyout()
{
var flyout = new PrivacyFlyout();
flyout.Show();
}
private void ShowAboutSettingFlyout()
{
var flyout = new AboutFlyout();
flyout.Show();
}
#endif
#if WINDOWS_PHONE_APP
/// <summary>
/// Invoked when the hardware back button is pressed. For Windows Phone only.
/// </summary>
/// <param name="sender">Instance that triggered the event.</param>
/// <param name="e">Event data describing the conditions that led to the event.</param>
private void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
{
if (NavigationService.CanGoBack())
{
e.Handled = true;
NavigationService.GoBack();
}
}
#else
/// <summary>
/// Invoked on every keystroke, including system keys such as Alt key combinations, when
/// this page is active and occupies the entire window. Used to detect keyboard navigation
/// between pages even when the page itself doesn't have focus.
/// </summary>
/// <param name="sender">Instance that triggered the event.</param>
/// <param name="e">Event data describing the conditions that led to the event.</param>
private void CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher sender, AcceleratorKeyEventArgs e)
{
var virtualKey = e.VirtualKey;
// Only investigate further when Left, Right, or the dedicated Previous or Next keys
// are pressed
if ((e.EventType == CoreAcceleratorKeyEventType.SystemKeyDown ||
e.EventType == CoreAcceleratorKeyEventType.KeyDown) &&
(virtualKey == VirtualKey.Left || virtualKey == VirtualKey.Right ||
(int)virtualKey == 166 || (int)virtualKey == 167))
{
var coreWindow = Window.Current.CoreWindow;
var downState = CoreVirtualKeyStates.Down;
bool menuKey = (coreWindow.GetKeyState(VirtualKey.Menu) & downState) == downState;
bool controlKey = (coreWindow.GetKeyState(VirtualKey.Control) & downState) == downState;
bool shiftKey = (coreWindow.GetKeyState(VirtualKey.Shift) & downState) == downState;
bool noModifiers = !menuKey && !controlKey && !shiftKey;
bool onlyAlt = menuKey && !controlKey && !shiftKey;
if (((int)virtualKey == 166 && noModifiers) ||
(virtualKey == VirtualKey.Left && onlyAlt))
{
// When the previous key or Alt+Left are pressed navigate back
e.Handled = true;
NavigationService.GoBack();
}
else if (((int)virtualKey == 167 && noModifiers) ||
(virtualKey == VirtualKey.Right && onlyAlt))
{
// When the next key or Alt+Right are pressed navigate forward
e.Handled = true;
NavigationService.GoForward();
}
}
}
/// <summary>
/// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
/// page is active and occupies the entire window. Used to detect browser-style next and
/// previous mouse button clicks to navigate between pages.
/// </summary>
/// <param name="sender">Instance that triggered the event.</param>
/// <param name="e">Event data describing the conditions that led to the event.</param>
private void CoreWindow_PointerPressed(CoreWindow sender, PointerEventArgs e)
{
var properties = e.CurrentPoint.Properties;
// Ignore button chords with the left, right, and middle buttons
if (properties.IsLeftButtonPressed || properties.IsRightButtonPressed ||
properties.IsMiddleButtonPressed) return;
// If back or foward are pressed (but not both) navigate appropriately
bool backPressed = properties.IsXButton1Pressed;
bool forwardPressed = properties.IsXButton2Pressed;
if (backPressed ^ forwardPressed)
{
e.Handled = true;
if (backPressed) NavigationService.GoBack();
if (forwardPressed) NavigationService.GoForward();
}
}
#endif
}
}
| |
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Collections;
namespace Org.BouncyCastle.Bcpg.OpenPgp
{
/// <remarks>
/// Often a PGP key ring file is made up of a succession of master/sub-key key rings.
/// If you want to read an entire public key file in one hit this is the class for you.
/// </remarks>
public class PgpPublicKeyRingBundle
{
private readonly IDictionary pubRings;
private readonly IList order;
private PgpPublicKeyRingBundle(
IDictionary pubRings,
IList order)
{
this.pubRings = pubRings;
this.order = order;
}
public PgpPublicKeyRingBundle(
byte[] encoding)
: this(new MemoryStream(encoding, false))
{
}
/// <summary>Build a PgpPublicKeyRingBundle from the passed in input stream.</summary>
/// <param name="inputStream">Input stream containing data.</param>
/// <exception cref="IOException">If a problem parsing the stream occurs.</exception>
/// <exception cref="PgpException">If an object is encountered which isn't a PgpPublicKeyRing.</exception>
public PgpPublicKeyRingBundle(
Stream inputStream)
: this(new PgpObjectFactory(inputStream).AllPgpObjects())
{
}
public PgpPublicKeyRingBundle(
IEnumerable e)
{
this.pubRings = Platform.CreateHashtable();
this.order = Platform.CreateArrayList();
foreach (object obj in e)
{
PgpPublicKeyRing pgpPub = obj as PgpPublicKeyRing;
if (pgpPub == null)
{
throw new PgpException(obj.GetType().FullName + " found where PgpPublicKeyRing expected");
}
long key = pgpPub.GetPublicKey().KeyId;
pubRings.Add(key, pgpPub);
order.Add(key);
}
}
[Obsolete("Use 'Count' property instead")]
public int Size
{
get { return order.Count; }
}
/// <summary>Return the number of key rings in this collection.</summary>
public int Count
{
get { return order.Count; }
}
/// <summary>Allow enumeration of the public key rings making up this collection.</summary>
public IEnumerable GetKeyRings()
{
return new EnumerableProxy(pubRings.Values);
}
/// <summary>Allow enumeration of the key rings associated with the passed in userId.</summary>
/// <param name="userId">The user ID to be matched.</param>
/// <returns>An <c>IEnumerable</c> of key rings which matched (possibly none).</returns>
public IEnumerable GetKeyRings(
string userId)
{
return GetKeyRings(userId, false, false);
}
/// <summary>Allow enumeration of the key rings associated with the passed in userId.</summary>
/// <param name="userId">The user ID to be matched.</param>
/// <param name="matchPartial">If true, userId need only be a substring of an actual ID string to match.</param>
/// <returns>An <c>IEnumerable</c> of key rings which matched (possibly none).</returns>
public IEnumerable GetKeyRings(
string userId,
bool matchPartial)
{
return GetKeyRings(userId, matchPartial, false);
}
/// <summary>Allow enumeration of the key rings associated with the passed in userId.</summary>
/// <param name="userId">The user ID to be matched.</param>
/// <param name="matchPartial">If true, userId need only be a substring of an actual ID string to match.</param>
/// <param name="ignoreCase">If true, case is ignored in user ID comparisons.</param>
/// <returns>An <c>IEnumerable</c> of key rings which matched (possibly none).</returns>
public IEnumerable GetKeyRings(
string userId,
bool matchPartial,
bool ignoreCase)
{
IList rings = Platform.CreateArrayList();
if (ignoreCase)
{
userId = Platform.StringToLower(userId);
}
foreach (PgpPublicKeyRing pubRing in GetKeyRings())
{
foreach (string nextUserID in pubRing.GetPublicKey().GetUserIds())
{
string next = nextUserID;
if (ignoreCase)
{
next = Platform.StringToLower(next);
}
if (matchPartial)
{
if (next.IndexOf(userId) > -1)
{
rings.Add(pubRing);
}
}
else
{
if (next.Equals(userId))
{
rings.Add(pubRing);
}
}
}
}
return new EnumerableProxy(rings);
}
/// <summary>Return the PGP public key associated with the given key id.</summary>
/// <param name="keyId">The ID of the public key to return.</param>
public IPgpPublicKey GetPublicKey(
long keyId)
{
foreach (PgpPublicKeyRing pubRing in GetKeyRings())
{
IPgpPublicKey pub = pubRing.GetPublicKey(keyId);
if (pub != null)
{
return pub;
}
}
return null;
}
/// <summary>Return the public key ring which contains the key referred to by keyId</summary>
/// <param name="keyId">key ID to match against</param>
public PgpPublicKeyRing GetPublicKeyRing(
long keyId)
{
if (pubRings.Contains(keyId))
{
return (PgpPublicKeyRing)pubRings[keyId];
}
foreach (PgpPublicKeyRing pubRing in GetKeyRings())
{
IPgpPublicKey pub = pubRing.GetPublicKey(keyId);
if (pub != null)
{
return pubRing;
}
}
return null;
}
/// <summary>
/// Return true if a key matching the passed in key ID is present, false otherwise.
/// </summary>
/// <param name="keyID">key ID to look for.</param>
public bool Contains(
long keyID)
{
return GetPublicKey(keyID) != null;
}
public byte[] GetEncoded()
{
using (var bOut = new MemoryStream())
{
Encode(bOut);
return bOut.ToArray();
}
}
public void Encode(
Stream outStr)
{
BcpgOutputStream bcpgOut = BcpgOutputStream.Wrap(outStr);
foreach (long key in order)
{
PgpPublicKeyRing sec = (PgpPublicKeyRing) pubRings[key];
sec.Encode(bcpgOut);
}
}
/// <summary>
/// Return a new bundle containing the contents of the passed in bundle and
/// the passed in public key ring.
/// </summary>
/// <param name="bundle">The <c>PgpPublicKeyRingBundle</c> the key ring is to be added to.</param>
/// <param name="publicKeyRing">The key ring to be added.</param>
/// <returns>A new <c>PgpPublicKeyRingBundle</c> merging the current one with the passed in key ring.</returns>
/// <exception cref="ArgumentException">If the keyId for the passed in key ring is already present.</exception>
public static PgpPublicKeyRingBundle AddPublicKeyRing(
PgpPublicKeyRingBundle bundle,
PgpPublicKeyRing publicKeyRing)
{
long key = publicKeyRing.GetPublicKey().KeyId;
if (bundle.pubRings.Contains(key))
{
throw new ArgumentException("Bundle already contains a key with a keyId for the passed in ring.");
}
IDictionary newPubRings = Platform.CreateHashtable(bundle.pubRings);
IList newOrder = Platform.CreateArrayList(bundle.order);
newPubRings[key] = publicKeyRing;
newOrder.Add(key);
return new PgpPublicKeyRingBundle(newPubRings, newOrder);
}
/// <summary>
/// Return a new bundle containing the contents of the passed in bundle with
/// the passed in public key ring removed.
/// </summary>
/// <param name="bundle">The <c>PgpPublicKeyRingBundle</c> the key ring is to be removed from.</param>
/// <param name="publicKeyRing">The key ring to be removed.</param>
/// <returns>A new <c>PgpPublicKeyRingBundle</c> not containing the passed in key ring.</returns>
/// <exception cref="ArgumentException">If the keyId for the passed in key ring is not present.</exception>
public static PgpPublicKeyRingBundle RemovePublicKeyRing(
PgpPublicKeyRingBundle bundle,
PgpPublicKeyRing publicKeyRing)
{
long key = publicKeyRing.GetPublicKey().KeyId;
if (!bundle.pubRings.Contains(key))
{
throw new ArgumentException("Bundle does not contain a key with a keyId for the passed in ring.");
}
IDictionary newPubRings = Platform.CreateHashtable(bundle.pubRings);
IList newOrder = Platform.CreateArrayList(bundle.order);
newPubRings.Remove(key);
newOrder.Remove(key);
return new PgpPublicKeyRingBundle(newPubRings, newOrder);
}
}
}
| |
using System;
using System.Data;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Diagnostics;
using WeifenLuo.WinFormsUI.Docking;
using MyMeta;
namespace MyGeneration
{
/// <summary>
/// Summary description for MetaProperties.
/// </summary>
public class MetaProperties : DockContent, IMyGenContent
{
private IMyGenerationMDI mdi;
private System.Windows.Forms.DataGrid Grid;
private System.Windows.Forms.DataGridTableStyle MyStyle;
private DataTable emptyTable;
private System.Windows.Forms.DataGridTextBoxColumn col_Property;
private System.Windows.Forms.DataGridTextBoxColumn col_Value;
private Type stringType = Type.GetType("System.String");
private System.Windows.Forms.LinkLabel lnkHELP;
private string helpInterface = "";
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public MetaProperties(IMyGenerationMDI mdi)
{
emptyTable = new DataTable("MyData");
emptyTable.Columns.Add("Property", stringType);
emptyTable.Columns.Add("Value", stringType);
InitializeComponent();
this.mdi = mdi;
this.ShowHint = DockState.DockRight;
}
protected override string GetPersistString()
{
return this.GetType().FullName;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MetaProperties));
this.Grid = new System.Windows.Forms.DataGrid();
this.MyStyle = new System.Windows.Forms.DataGridTableStyle();
this.col_Property = new System.Windows.Forms.DataGridTextBoxColumn();
this.col_Value = new System.Windows.Forms.DataGridTextBoxColumn();
this.lnkHELP = new System.Windows.Forms.LinkLabel();
((System.ComponentModel.ISupportInitialize)(this.Grid)).BeginInit();
this.SuspendLayout();
//
// Grid
//
this.Grid.AlternatingBackColor = System.Drawing.Color.Wheat;
this.Grid.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.Grid.BackColor = System.Drawing.SystemColors.Control;
this.Grid.BackgroundColor = System.Drawing.Color.Wheat;
this.Grid.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.Grid.CaptionBackColor = System.Drawing.SystemColors.Control;
this.Grid.CaptionVisible = false;
this.Grid.DataMember = "";
this.Grid.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold);
this.Grid.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.Grid.Location = new System.Drawing.Point(0, 0);
this.Grid.Name = "Grid";
this.Grid.PreferredColumnWidth = 200;
this.Grid.ReadOnly = true;
this.Grid.RowHeadersVisible = false;
this.Grid.RowHeaderWidth = 0;
this.Grid.Size = new System.Drawing.Size(431, 518);
this.Grid.TabIndex = 9;
this.Grid.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] {
this.MyStyle});
//
// MyStyle
//
this.MyStyle.AlternatingBackColor = System.Drawing.Color.PaleGoldenrod;
this.MyStyle.BackColor = System.Drawing.Color.Wheat;
this.MyStyle.DataGrid = this.Grid;
this.MyStyle.GridColumnStyles.AddRange(new System.Windows.Forms.DataGridColumnStyle[] {
this.col_Property,
this.col_Value});
this.MyStyle.GridLineColor = System.Drawing.Color.Goldenrod;
this.MyStyle.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.MyStyle.MappingName = "MyData";
this.MyStyle.ReadOnly = true;
this.MyStyle.RowHeadersVisible = false;
this.MyStyle.RowHeaderWidth = 0;
//
// col_Property
//
this.col_Property.Format = "";
this.col_Property.FormatInfo = null;
this.col_Property.HeaderText = "Property";
this.col_Property.MappingName = "Property";
this.col_Property.NullText = "";
this.col_Property.ReadOnly = true;
this.col_Property.Width = 75;
//
// col_Value
//
this.col_Value.Format = "";
this.col_Value.FormatInfo = null;
this.col_Value.HeaderText = "Value";
this.col_Value.MappingName = "Value";
this.col_Value.NullText = "";
this.col_Value.ReadOnly = true;
this.col_Value.Width = 75;
//
// lnkHELP
//
this.lnkHELP.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lnkHELP.Location = new System.Drawing.Point(8, 522);
this.lnkHELP.Name = "lnkHELP";
this.lnkHELP.Size = new System.Drawing.Size(416, 21);
this.lnkHELP.TabIndex = 10;
this.lnkHELP.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkHELP_LinkClicked);
//
// MetaProperties
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 13);
this.AutoScroll = true;
this.BackColor = System.Drawing.Color.Wheat;
this.ClientSize = new System.Drawing.Size(431, 550);
this.Controls.Add(this.lnkHELP);
this.Controls.Add(this.Grid);
this.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold);
this.HideOnClose = true;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "MetaProperties";
this.TabText = "MyMeta Properties";
this.Text = "MyMeta Properties";
this.ToolTipText = "MyMeta Properties";
this.Load += new System.EventHandler(this.MetaProperties_Load);
((System.ComponentModel.ISupportInitialize)(this.Grid)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void MetaProperties_Load(object sender, System.EventArgs e)
{
this.col_Property.TextBox.BorderStyle = BorderStyle.None;
this.col_Value.TextBox.BorderStyle = BorderStyle.None;
this.col_Property.TextBox.Move += new System.EventHandler(this.ColorTextBox);
this.col_Value.TextBox.Move += new System.EventHandler(this.ColorTextBox);
this.Clear();
}
/*public void DefaultSettingsChanged(DefaultSettings settings)
{
this.Clear();
}*/
public void MetaBrowserRefresh()
{
this.Clear();
}
public void Clear()
{
this.Grid.DataSource = emptyTable;
this.InitializeGrid();
this.Text = "MyMeta Properties";
this.lnkHELP.Text = "";
this.helpInterface = "";
}
//===============================================================================
// Properties
//===============================================================================
public void DisplayDatabaseProperties(IDatabase database, TreeNode tableNode)
{
DataTable dt = new DataTable("MyData");
dt.Columns.Add("Property", stringType);
dt.Columns.Add("Value", stringType);
dt.Rows.Add(new object[] {"Name", database.Name});
dt.Rows.Add(new object[] {"Alias", database.Alias});
dt.Rows.Add(new object[] {"Description", database.Description});
dt.Rows.Add(new object[] {"SchemaName", database.SchemaName});
dt.Rows.Add(new object[] {"SchemaOwner", database.SchemaOwner});
dt.Rows.Add(new object[] {"DefaultCharSetCatalog", database.DefaultCharSetCatalog});
dt.Rows.Add(new object[] {"DefaultCharSetSchema", database.DefaultCharSetSchema});
dt.Rows.Add(new object[] {"DefaultCharSetName", database.DefaultCharSetName});
this.Grid.DataSource = dt;
this.InitializeGrid();
this.Text = "IDatabase Properties";
this.lnkHELP.Text = "IDatabase Help ...";
this.helpInterface = "IDatabase";
}
public void DisplayColumnProperties(IColumn column, TreeNode columnNode)
{
DataTable dt = new DataTable("MyData");
dt.Columns.Add("Property", stringType);
dt.Columns.Add("Value", stringType);
dt.Rows.Add(new object[] {"Name", column.Name});
dt.Rows.Add(new object[] {"Alias", column.Alias});
dt.Rows.Add(new object[] {"Description", column.Description});
dt.Rows.Add(new object[] {"Ordinal", column.Ordinal.ToString()});
dt.Rows.Add(new object[] {"DataTypeName", column.DataTypeName});
dt.Rows.Add(new object[] {"DataTypeNameComplete", column.DataTypeNameComplete});
dt.Rows.Add(new object[] {"NumericPrecision", column.NumericPrecision.ToString()});
dt.Rows.Add(new object[] {"NumericScale", column.NumericScale.ToString()});
dt.Rows.Add(new object[] {"DateTimePrecision", column.DateTimePrecision.ToString()});
dt.Rows.Add(new object[] {"CharacterMaxLength", column.CharacterMaxLength.ToString()});
dt.Rows.Add(new object[] {"CharacterOctetLength", column.CharacterOctetLength.ToString()});
dt.Rows.Add(new object[] {"LanguageType", column.LanguageType});
dt.Rows.Add(new object[] {"DbTargetType", column.DbTargetType});
dt.Rows.Add(new object[] {"IsNullable", column.IsNullable ? "True" : "False"});
dt.Rows.Add(new object[] {"IsComputed", column.IsComputed ? "True" : "False"});
dt.Rows.Add(new object[] {"IsInPrimaryKey", column.IsInPrimaryKey ? "True" : "False"});
dt.Rows.Add(new object[] {"IsInForeignKey", column.IsInForeignKey ? "True" : "False"});
dt.Rows.Add(new object[] {"IsAutoKey", column.IsAutoKey ? "True" : "False"});
dt.Rows.Add(new object[] {"AutoKeySeed", column.AutoKeySeed});
dt.Rows.Add(new object[] {"AutoKeyIncrement", column.AutoKeyIncrement});
dt.Rows.Add(new object[] {"HasDefault", column.HasDefault ? "True" : "False"});
dt.Rows.Add(new object[] {"Default", column.Default});
dt.Rows.Add(new object[] {"Flags", column.Flags.ToString()});
dt.Rows.Add(new object[] {"PropID", column.PropID.ToString()});
dt.Rows.Add(new object[] {"Guid", column.Guid.ToString()});
dt.Rows.Add(new object[] {"TypeGuid", column.TypeGuid.ToString()});
dt.Rows.Add(new object[] {"LCID", column.LCID.ToString()});
dt.Rows.Add(new object[] {"SortID", column.SortID.ToString()});
dt.Rows.Add(new object[] {"CompFlags", column.CompFlags.ToString()});
dt.Rows.Add(new object[] {"DomainName", column.DomainName});
dt.Rows.Add(new object[] {"HasDomain", column.HasDomain ? "True" : "False"});
this.Grid.DataSource = dt;
this.InitializeGrid();
this.Text = "IColumn Properties";
this.lnkHELP.Text = "IColumn Help ...";
this.helpInterface = "IColumn";
}
public void DisplayTableProperties(ITable table, TreeNode tableNode)
{
DataTable dt = new DataTable("MyData");
dt.Columns.Add("Property", stringType);
dt.Columns.Add("Value", stringType);
dt.Rows.Add(new object[] {"Name", table.Name});
dt.Rows.Add(new object[] {"Alias", table.Alias});
dt.Rows.Add(new object[] {"Schema", table.Schema});
dt.Rows.Add(new object[] {"Description", table.Description});
dt.Rows.Add(new object[] {"Type", table.Type});
dt.Rows.Add(new object[] {"Guid", table.Guid.ToString()});
dt.Rows.Add(new object[] {"PropID", table.PropID.ToString()});
dt.Rows.Add(new object[] {"DateCreated", table.DateCreated.ToShortDateString()});
dt.Rows.Add(new object[] {"DateModified", table.DateModified.ToShortDateString()});
this.Grid.DataSource = dt;
this.InitializeGrid();
this.Text = "ITable Properties";
this.lnkHELP.Text = "ITable Help ...";
this.helpInterface = "ITable";
}
public void DisplayViewProperties(IView view, TreeNode tableNode)
{
DataTable dt = new DataTable("MyData");
dt.Columns.Add("Property", stringType);
dt.Columns.Add("Value", stringType);
dt.Rows.Add(new object[] {"Name", view.Name});
dt.Rows.Add(new object[] {"Alias", view.Alias});
dt.Rows.Add(new object[] {"Schema", view.Schema});
dt.Rows.Add(new object[] {"Description", view.Description});
dt.Rows.Add(new object[] {"Type", view.Type});
dt.Rows.Add(new object[] {"Guid", view.Guid.ToString()});
dt.Rows.Add(new object[] {"PropID", view.PropID.ToString()});
dt.Rows.Add(new object[] {"DateCreated", view.DateCreated.ToShortDateString()});
dt.Rows.Add(new object[] {"DateModified", view.DateModified.ToShortDateString()});
dt.Rows.Add(new object[] {"CheckOption", view.CheckOption ? "True" : "False"});
dt.Rows.Add(new object[] {"IsUpdateable", view.IsUpdateable? "True" : "False"});
dt.Rows.Add(new object[] {"ViewText", view.ViewText});
this.Grid.DataSource = dt;
this.InitializeGrid();
this.Text = "IView Properties";
this.lnkHELP.Text = "IView Help ...";
this.helpInterface = "IView";
}
public void DisplayProcedureProperties(IProcedure proc, TreeNode tableNode)
{
DataTable dt = new DataTable("MyData");
dt.Columns.Add("Property", stringType);
dt.Columns.Add("Value", stringType);
dt.Rows.Add(new object[] {"Name", proc.Name});
dt.Rows.Add(new object[] {"Alias", proc.Alias});
dt.Rows.Add(new object[] {"Schema", proc.Schema});
dt.Rows.Add(new object[] {"Description", proc.Description});
dt.Rows.Add(new object[] {"Type", proc.Type.ToString()});
dt.Rows.Add(new object[] {"DateCreated", proc.DateCreated.ToShortDateString()});
dt.Rows.Add(new object[] {"DateModified", proc.DateModified.ToShortDateString()});
dt.Rows.Add(new object[] {"ProcedureText", proc.ProcedureText});
this.Grid.DataSource = dt;
this.InitializeGrid();
this.Text = "IProcedure Properties";
this.lnkHELP.Text = "IProcedure Help ...";
this.helpInterface = "IProcedure";
}
public void DisplayDomainProperties(IDomain domain, TreeNode tableNode)
{
DataTable dt = new DataTable("MyData");
dt.Columns.Add("Property", stringType);
dt.Columns.Add("Value", stringType);
/*
if(metaData.Columns.Contains("DOMAIN_CATALOG")) f_DomainCatalog = metaData.Columns["DOMAIN_CATALOG"];
if(metaData.Columns.Contains("DOMAIN_SCHEMA")) f_DomainSchema = metaData.Columns["DOMAIN_SCHEMA"];
if(metaData.Columns.Contains("DOMAIN_NAME")) f_DomainName = metaData.Columns["DOMAIN_NAME"];
if(metaData.Columns.Contains("DATA_TYPE")) f_DataType = metaData.Columns["DATA_TYPE"];
if(metaData.Columns.Contains("CHARACTER_MAXIMUM_LENGTH")) f_MaxLength = metaData.Columns["CHARACTER_MAXIMUM_LENGTH"];
if(metaData.Columns.Contains("CHARACTER_OCTET_LENGTH")) f_OctetLength = metaData.Columns["CHARACTER_OCTET_LENGTH"];
if(metaData.Columns.Contains("COLLATION_CATALOG")) f_CollationCatalog = metaData.Columns["COLLATION_CATALOG"];
if(metaData.Columns.Contains("COLLATION_SCHEMA")) f_CollationSchema = metaData.Columns["COLLATION_SCHEMA"];
if(metaData.Columns.Contains("COLLATION_NAME")) f_CollationName = metaData.Columns["COLLATION_NAME"];
if(metaData.Columns.Contains("CHARACTER_SET_CATALOG")) f_CharSetCatalog = metaData.Columns["CHARACTER_SET_CATALOG"];
if(metaData.Columns.Contains("CHARACTER_SET_SCHEMA")) f_CharSetSchema = metaData.Columns["CHARACTER_SET_SCHEMA"];
if(metaData.Columns.Contains("CHARACTER_SET_NAME")) f_CharSetName = metaData.Columns["CHARACTER_SET_NAME"];
if(metaData.Columns.Contains("NUMERIC_PRECISION")) f_NumericPrecision = metaData.Columns["NUMERIC_PRECISION"];
if(metaData.Columns.Contains("NUMERIC_SCALE")) f_NumericScale = metaData.Columns["NUMERIC_SCALE"];
if(metaData.Columns.Contains("DATETIME_PRECISION")) f_DatetimePrecision = metaData.Columns["DATETIME_PRECISION"];
if(metaData.Columns.Contains("DOMAIN_DEFAULT")) f_Default = metaData.Columns["COLUMN_DEFAULT"];
if(metaData.Columns.Contains("IS_NULLABLE"))
*/
dt.Rows.Add(new object[] {"Name", domain.Name});
dt.Rows.Add(new object[] {"Alias", domain.Alias});
dt.Rows.Add(new object[] {"DataTypeName", domain.DataTypeName});
dt.Rows.Add(new object[] {"DataTypeNameComplete", domain.DataTypeNameComplete});
dt.Rows.Add(new object[] {"NumericPrecision", domain.NumericPrecision.ToString()});
dt.Rows.Add(new object[] {"NumericScale", domain.NumericScale.ToString()});
dt.Rows.Add(new object[] {"DateTimePrecision", domain.DateTimePrecision.ToString()});
dt.Rows.Add(new object[] {"CharacterMaxLength", domain.CharacterMaxLength.ToString()});
dt.Rows.Add(new object[] {"CharacterOctetLength", domain.CharacterOctetLength.ToString()});
dt.Rows.Add(new object[] {"LanguageType", domain.LanguageType});
dt.Rows.Add(new object[] {"DbTargetType", domain.DbTargetType});
dt.Rows.Add(new object[] {"IsNullable", domain.IsNullable ? "True" : "False"});
dt.Rows.Add(new object[] {"HasDefault", domain.HasDefault ? "True" : "False"});
dt.Rows.Add(new object[] {"Default", domain.Default});
this.Grid.DataSource = dt;
this.InitializeGrid();
this.Text = "IDomain Properties";
this.lnkHELP.Text = "IDomain Help ...";
this.helpInterface = "IDomain";
}
public void DisplayParameterProperties(IParameter parameter, TreeNode parameterNode)
{
DataTable dt = new DataTable("MyData");
dt.Columns.Add("Property", stringType);
dt.Columns.Add("Value", stringType);
string dir = "";
switch(parameter.Direction)
{
case ParamDirection.Input:
dir = "IN";
break;
case ParamDirection.InputOutput:
dir = "INOUT";
break;
case ParamDirection.Output:
dir = "OUT";
break;
case ParamDirection.ReturnValue:
dir = "RETURN";
break;
}
dt.Rows.Add(new object[] {"Name", parameter.Name});
dt.Rows.Add(new object[] {"Alias", parameter.Alias});
dt.Rows.Add(new object[] {"Description", parameter.Description});
dt.Rows.Add(new object[] {"Direction", dir});
dt.Rows.Add(new object[] {"Ordinal", parameter.Ordinal.ToString()});
dt.Rows.Add(new object[] {"TypeName", parameter.TypeName});
dt.Rows.Add(new object[] {"DataTypeNameComplete", parameter.DataTypeNameComplete});
dt.Rows.Add(new object[] {"NumericPrecision", parameter.NumericPrecision.ToString()});
dt.Rows.Add(new object[] {"NumericScale", parameter.NumericScale.ToString()});
dt.Rows.Add(new object[] {"CharacterMaxLength", parameter.CharacterMaxLength.ToString()});
dt.Rows.Add(new object[] {"CharacterOctetLength", parameter.CharacterOctetLength.ToString()});
dt.Rows.Add(new object[] {"LanguageType", parameter.LanguageType});
dt.Rows.Add(new object[] {"DbTargetType", parameter.DbTargetType});
dt.Rows.Add(new object[] {"HasDefault", parameter.HasDefault ? "True" : "False"});
dt.Rows.Add(new object[] {"Default", parameter.Default});
dt.Rows.Add(new object[] {"IsNullable", parameter.IsNullable ? "True" : "False"});
dt.Rows.Add(new object[] {"LocalTypeName", parameter.LocalTypeName});
this.Grid.DataSource = dt;
this.InitializeGrid();
this.Text = "IParameter Properties";
this.lnkHELP.Text = "IParameter Help ...";
this.helpInterface = "IParameter";
}
public void DisplayResultColumnProperties(IResultColumn resultColumn, TreeNode resultColumnNode)
{
DataTable dt = new DataTable("MyData");
dt.Columns.Add("Property", stringType);
dt.Columns.Add("Value", stringType);
dt.Rows.Add(new object[] {"Name", resultColumn.Name});
dt.Rows.Add(new object[] {"Alias", resultColumn.Alias});
dt.Rows.Add(new object[] {"Ordinal", resultColumn.Ordinal.ToString()});
dt.Rows.Add(new object[] {"DataTypeName", resultColumn.DataTypeName});
dt.Rows.Add(new object[] {"DataTypeNameComplete", resultColumn.DataTypeNameComplete});
dt.Rows.Add(new object[] {"LanguageType", resultColumn.LanguageType});
dt.Rows.Add(new object[] {"DbTargetType", resultColumn.DbTargetType});
this.Grid.DataSource = dt;
this.InitializeGrid();
this.Text = "IResultColumn Properties";
this.lnkHELP.Text = "IResultColumn Help ...";
this.helpInterface = "IResultColumn";
}
public void DisplayForeignKeyProperties(IForeignKey foreignKey, TreeNode foreignKeyNode)
{
DataTable dt = new DataTable("MyData");
dt.Columns.Add("Property", stringType);
dt.Columns.Add("Value", stringType);
dt.Rows.Add(new object[] {"Name", foreignKey.Name});
dt.Rows.Add(new object[] {"Alias", foreignKey.Alias});
// NOTE, THIS MUST USE INDIRECTION THROUGH THE TABLE
dt.Rows.Add(new object[] {"PrimaryTable", foreignKey.PrimaryTable.Name});
dt.Rows.Add(new object[] {"ForeignTable", foreignKey.ForeignTable.Name});
dt.Rows.Add(new object[] {"UpdateRule", foreignKey.UpdateRule});
dt.Rows.Add(new object[] {"DeleteRule", foreignKey.DeleteRule});
dt.Rows.Add(new object[] {"PrimaryKeyName", foreignKey.PrimaryKeyName});
dt.Rows.Add(new object[] {"Deferrability", foreignKey.Deferrability.ToString()});
this.Grid.DataSource = dt;
this.InitializeGrid();
this.Text = "IForeignKey Properties";
this.lnkHELP.Text = "IForeignKey Help ...";
this.helpInterface = "IForeignKey";
}
public void DisplayIndexProperties(IIndex index, TreeNode indexNode)
{
DataTable dt = new DataTable("MyData");
dt.Columns.Add("Property", stringType);
dt.Columns.Add("Value", stringType);
dt.Rows.Add(new object[] {"Name", index.Name});
dt.Rows.Add(new object[] {"Alias", index.Alias});
dt.Rows.Add(new object[] {"Schema", index.Schema});
dt.Rows.Add(new object[] {"Unique", index.Unique ? "True" : "False"});
dt.Rows.Add(new object[] {"Clustered", index.Clustered ? "True" : "False"});
dt.Rows.Add(new object[] {"Type", index.Type.ToString()});
dt.Rows.Add(new object[] {"FillFactor", index.FillFactor.ToString()});
dt.Rows.Add(new object[] {"InitialSize", index.InitialSize.ToString()});
dt.Rows.Add(new object[] {"SortBookmarks", index.SortBookmarks ? "True" : "False"});
dt.Rows.Add(new object[] {"AutoUpdate", index.AutoUpdate ? "True" : "False"});
dt.Rows.Add(new object[] {"NullCollation", index.NullCollation.ToString()});
dt.Rows.Add(new object[] {"Collation", index.Collation.ToString()});
dt.Rows.Add(new object[] {"Cardinality", index.Cardinality.ToString()});
dt.Rows.Add(new object[] {"Pages", index.Pages.ToString()});
dt.Rows.Add(new object[] {"FilterCondition", index.FilterCondition});
dt.Rows.Add(new object[] {"Integrated", index.Integrated ? "True" : "False"});
this.Grid.DataSource = dt;
this.InitializeGrid();
this.Text = "IIndex Properties";
this.lnkHELP.Text = "IIndex Help ...";
this.helpInterface = "IIndex";
}
public void DisplayProviderTypeProperties(IProviderType type, TreeNode indexNode)
{
DataTable dt = new DataTable("MyData");
dt.Columns.Add("Property", stringType);
dt.Columns.Add("Value", stringType);
dt.Rows.Add(new object[] {"Type", type.Type});
dt.Rows.Add(new object[] {"DataType", type.DataType.ToString()});
dt.Rows.Add(new object[] {"ColumnSize", type.ColumnSize.ToString()});
dt.Rows.Add(new object[] {"LiteralPrefix", type.LiteralPrefix});
dt.Rows.Add(new object[] {"LiteralSuffix", type.LiteralSuffix});
dt.Rows.Add(new object[] {"CreateParams", type.CreateParams});
dt.Rows.Add(new object[] {"IsNullable", type.IsNullable ? "True" : "False"});
dt.Rows.Add(new object[] {"IsCaseSensitive", type.IsCaseSensitive ? "True" : "False"});
// dt.Rows.Add(new object[] {"Searchable", type.Searchable});
dt.Rows.Add(new object[] {"IsUnsigned", type.IsUnsigned ? "True" : "False"});
dt.Rows.Add(new object[] {"HasFixedPrecScale", type.HasFixedPrecScale ? "True" : "False"});
dt.Rows.Add(new object[] {"CanBeAutoIncrement", type.CanBeAutoIncrement ? "True" : "False"});
dt.Rows.Add(new object[] {"LocalType", type.LocalType});
dt.Rows.Add(new object[] {"MinimumScale", type.MinimumScale.ToString()});
dt.Rows.Add(new object[] {"MaximumScale", type.MaximumScale.ToString()});
dt.Rows.Add(new object[] {"TypeGuid", type.TypeGuid.ToString()});
dt.Rows.Add(new object[] {"TypeLib", type.TypeLib});
dt.Rows.Add(new object[] {"Version", type.Version});
dt.Rows.Add(new object[] {"IsLong", type.IsLong ? "True" : "False"});
dt.Rows.Add(new object[] {"BestMatch", type.BestMatch ? "True" : "False"});
dt.Rows.Add(new object[] {"IsFixedLength", type.IsFixedLength ? "True" : "False"});
this.Grid.DataSource = dt;
this.InitializeGrid();
this.Text = "IProviderType Properties";
this.lnkHELP.Text = "IProviderType Help ...";
this.helpInterface = "IProviderType";
}
private void ColorTextBox(object sender, System.EventArgs e)
{
TextBox txtBox = (TextBox)sender;
// Bail if we're in la la land
Size size = txtBox.Size;
if(size.Width == 0 && size.Height == 0)
{
return;
}
int row = this.Grid.CurrentCell.RowNumber;
if(isEven(row))
txtBox.BackColor = Color.Wheat;
else
txtBox.BackColor = Color.PaleGoldenrod;
}
private bool isEven(int x)
{
return (x & 1) == 0;
}
private void InitializeGrid()
{
if(!gridInitialized)
{
if(MyStyle.GridColumnStyles.Count > 0)
{
gridInitialized = true;
gridHelper = new GridLayoutHelper(this.Grid, this.MyStyle,
new decimal[] { 0.50M, 0.50M }, new int[] { 130, 130 });
}
}
}
private GridLayoutHelper gridHelper;
private bool gridInitialized = false;
private void lnkHELP_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
try
{
if(this.helpInterface != "")
{
Process myProcess = new Process();
myProcess.StartInfo.FileName = "mk:@MSITStore:" + Application.StartupPath +
@"\MyMeta.chm::/html/T_MyMeta_" + this.helpInterface + ".htm";
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
myProcess.Start();
}
}
catch {}
}
#region IMyGenContent Members
public ToolStrip ToolStrip
{
get { return null; }
}
public void ProcessAlert(IMyGenContent sender, string command, params object[] args)
{
if (command == "UpdateDefaultSettings")
{
this.Clear();
}
}
public bool CanClose(bool allowPrevent)
{
return true;
}
public void ResetMenu()
{
//
}
public DockContent DockContent
{
get { return this; }
}
#endregion
}
}
| |
using WixSharp;
using WixSharp.UI.Forms;
namespace WixSharpSetup.Dialogs
{
partial class MaintenanceTypeDialog
{
/// <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.topBorder = new System.Windows.Forms.Panel();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.remove = new System.Windows.Forms.Button();
this.repair = new System.Windows.Forms.Button();
this.change = new System.Windows.Forms.Button();
this.topPanel = new System.Windows.Forms.Panel();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.banner = new System.Windows.Forms.PictureBox();
this.bottomPanel = new System.Windows.Forms.Panel();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.back = new System.Windows.Forms.Button();
this.next = new System.Windows.Forms.Button();
this.cancel = new System.Windows.Forms.Button();
this.border1 = new System.Windows.Forms.Panel();
this.middlePanel = new System.Windows.Forms.TableLayoutPanel();
this.panel3 = new System.Windows.Forms.Panel();
this.panel4 = new System.Windows.Forms.Panel();
this.panel5 = new System.Windows.Forms.Panel();
this.topPanel.SuspendLayout();
( (System.ComponentModel.ISupportInitialize)( this.banner ) ).BeginInit();
this.bottomPanel.SuspendLayout();
this.tableLayoutPanel1.SuspendLayout();
this.middlePanel.SuspendLayout();
this.panel3.SuspendLayout();
this.panel4.SuspendLayout();
this.panel5.SuspendLayout();
this.SuspendLayout();
//
// topBorder
//
this.topBorder.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left )
| System.Windows.Forms.AnchorStyles.Right ) ) );
this.topBorder.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.topBorder.Location = new System.Drawing.Point( 0, 58 );
this.topBorder.Name = "topBorder";
this.topBorder.Size = new System.Drawing.Size( 494, 1 );
this.topBorder.TabIndex = 18;
//
// label5
//
this.label5.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right ) ) );
this.label5.AutoEllipsis = true;
this.label5.BackColor = System.Drawing.SystemColors.Control;
this.label5.Location = new System.Drawing.Point( 28, 40 );
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size( 442, 38 );
this.label5.TabIndex = 1;
this.label5.Text = "[MaintenanceTypeDlgRemoveText]";
//
// label4
//
this.label4.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right ) ) );
this.label4.AutoEllipsis = true;
this.label4.BackColor = System.Drawing.SystemColors.Control;
this.label4.Location = new System.Drawing.Point( 28, 40 );
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size( 440, 34 );
this.label4.TabIndex = 1;
this.label4.Text = "[MaintenanceTypeDlgRepairText]";
//
// label3
//
this.label3.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right ) ) );
this.label3.AutoEllipsis = true;
this.label3.BackColor = System.Drawing.SystemColors.Control;
this.label3.Location = new System.Drawing.Point( 28, 40 );
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size( 440, 34 );
this.label3.TabIndex = 1;
this.label3.Text = "[MaintenanceTypeDlgChangeText]";
//
// remove
//
this.remove.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.remove.AutoSize = true;
this.remove.Location = new System.Drawing.Point( 0, 5 );
this.remove.MaximumSize = new System.Drawing.Size( 113, 0 );
this.remove.MinimumSize = new System.Drawing.Size( 113, 0 );
this.remove.Name = "remove";
this.remove.Size = new System.Drawing.Size( 113, 23 );
this.remove.TabIndex = 16;
this.remove.Text = "[MaintenanceTypeDlgRemoveButton]";
this.remove.UseVisualStyleBackColor = true;
this.remove.Click += new System.EventHandler( this.remove_Click );
//
// repair
//
this.repair.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.repair.AutoSize = true;
this.repair.Location = new System.Drawing.Point( 0, 5 );
this.repair.MaximumSize = new System.Drawing.Size( 113, 0 );
this.repair.MinimumSize = new System.Drawing.Size( 113, 0 );
this.repair.Name = "repair";
this.repair.Size = new System.Drawing.Size( 113, 23 );
this.repair.TabIndex = 15;
this.repair.Text = "[MaintenanceTypeDlgRepairButton]";
this.repair.UseVisualStyleBackColor = true;
this.repair.Click += new System.EventHandler( this.repair_Click );
//
// change
//
this.change.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.change.AutoSize = true;
this.change.Location = new System.Drawing.Point( 0, 5 );
this.change.MaximumSize = new System.Drawing.Size( 113, 0 );
this.change.MinimumSize = new System.Drawing.Size( 113, 0 );
this.change.Name = "change";
this.change.Size = new System.Drawing.Size( 113, 23 );
this.change.TabIndex = 0;
this.change.Text = "[MaintenanceTypeDlgChangeButton]";
this.change.UseVisualStyleBackColor = true;
this.change.Click += new System.EventHandler( this.change_Click );
//
// topPanel
//
this.topPanel.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left )
| System.Windows.Forms.AnchorStyles.Right ) ) );
this.topPanel.BackColor = System.Drawing.SystemColors.Control;
this.topPanel.Controls.Add( this.label2 );
this.topPanel.Controls.Add( this.label1 );
this.topPanel.Controls.Add( this.banner );
this.topPanel.Location = new System.Drawing.Point( 0, 0 );
this.topPanel.Name = "topPanel";
this.topPanel.Size = new System.Drawing.Size( 494, 58 );
this.topPanel.TabIndex = 13;
//
// label2
//
this.label2.AutoSize = true;
this.label2.BackColor = System.Drawing.Color.White;
this.label2.Location = new System.Drawing.Point( 19, 31 );
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size( 168, 13 );
this.label2.TabIndex = 1;
this.label2.Text = "[MaintenanceTypeDlgDescription]";
//
// label1
//
this.label1.AutoSize = true;
this.label1.BackColor = System.Drawing.Color.White;
this.label1.Font = new System.Drawing.Font( "Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ( (byte)( 0 ) ) );
this.label1.Location = new System.Drawing.Point( 11, 8 );
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size( 160, 13 );
this.label1.TabIndex = 1;
this.label1.Text = "[MaintenanceTypeDlgTitle]";
//
// banner
//
this.banner.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.banner.BackColor = System.Drawing.Color.White;
this.banner.Location = new System.Drawing.Point( 0, 0 );
this.banner.Name = "banner";
this.banner.Size = new System.Drawing.Size( 494, 58 );
this.banner.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.banner.TabIndex = 0;
this.banner.TabStop = false;
//
// bottomPanel
//
this.bottomPanel.BackColor = System.Drawing.SystemColors.Control;
this.bottomPanel.Controls.Add( this.tableLayoutPanel1 );
this.bottomPanel.Controls.Add( this.border1 );
this.bottomPanel.Dock = System.Windows.Forms.DockStyle.Bottom;
this.bottomPanel.Location = new System.Drawing.Point( 0, 312 );
this.bottomPanel.Name = "bottomPanel";
this.bottomPanel.Size = new System.Drawing.Size( 494, 49 );
this.bottomPanel.TabIndex = 12;
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right ) ) );
this.tableLayoutPanel1.ColumnCount = 5;
this.tableLayoutPanel1.ColumnStyles.Add( new System.Windows.Forms.ColumnStyle( System.Windows.Forms.SizeType.Percent, 100F ) );
this.tableLayoutPanel1.ColumnStyles.Add( new System.Windows.Forms.ColumnStyle() );
this.tableLayoutPanel1.ColumnStyles.Add( new System.Windows.Forms.ColumnStyle() );
this.tableLayoutPanel1.ColumnStyles.Add( new System.Windows.Forms.ColumnStyle( System.Windows.Forms.SizeType.Absolute, 14F ) );
this.tableLayoutPanel1.ColumnStyles.Add( new System.Windows.Forms.ColumnStyle() );
this.tableLayoutPanel1.Controls.Add( this.back, 1, 0 );
this.tableLayoutPanel1.Controls.Add( this.next, 2, 0 );
this.tableLayoutPanel1.Controls.Add( this.cancel, 4, 0 );
this.tableLayoutPanel1.Location = new System.Drawing.Point( 0, 3 );
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 1;
this.tableLayoutPanel1.RowStyles.Add( new System.Windows.Forms.RowStyle( System.Windows.Forms.SizeType.Percent, 100F ) );
this.tableLayoutPanel1.Size = new System.Drawing.Size( 491, 43 );
this.tableLayoutPanel1.TabIndex = 7;
//
// back
//
this.back.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.back.AutoSize = true;
this.back.Enabled = false;
this.back.Location = new System.Drawing.Point( 222, 10 );
this.back.MinimumSize = new System.Drawing.Size( 75, 0 );
this.back.Name = "back";
this.back.Size = new System.Drawing.Size( 77, 23 );
this.back.TabIndex = 0;
this.back.Text = "[WixUIBack]";
this.back.UseVisualStyleBackColor = true;
this.back.Click += new System.EventHandler( this.back_Click );
//
// next
//
this.next.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.next.AutoSize = true;
this.next.Enabled = false;
this.next.Location = new System.Drawing.Point( 305, 10 );
this.next.MinimumSize = new System.Drawing.Size( 75, 0 );
this.next.Name = "next";
this.next.Size = new System.Drawing.Size( 77, 23 );
this.next.TabIndex = 0;
this.next.Text = "[WixUINext]";
this.next.UseVisualStyleBackColor = true;
this.next.Click += new System.EventHandler( this.next_Click );
//
// cancel
//
this.cancel.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.cancel.AutoSize = true;
this.cancel.Location = new System.Drawing.Point( 402, 10 );
this.cancel.MinimumSize = new System.Drawing.Size( 75, 0 );
this.cancel.Name = "cancel";
this.cancel.Size = new System.Drawing.Size( 86, 23 );
this.cancel.TabIndex = 0;
this.cancel.Text = "[WixUICancel]";
this.cancel.UseVisualStyleBackColor = true;
this.cancel.Click += new System.EventHandler( this.cancel_Click );
//
// border1
//
this.border1.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left )
| System.Windows.Forms.AnchorStyles.Right ) ) );
this.border1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.border1.Location = new System.Drawing.Point( 0, 0 );
this.border1.Name = "border1";
this.border1.Size = new System.Drawing.Size( 494, 1 );
this.border1.TabIndex = 17;
//
// middlePanel
//
this.middlePanel.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.middlePanel.ColumnCount = 1;
this.middlePanel.ColumnStyles.Add( new System.Windows.Forms.ColumnStyle( System.Windows.Forms.SizeType.Percent, 100F ) );
this.middlePanel.Controls.Add( this.panel3, 0, 0 );
this.middlePanel.Controls.Add( this.panel4, 0, 1 );
this.middlePanel.Controls.Add( this.panel5, 0, 2 );
this.middlePanel.Location = new System.Drawing.Point( 15, 61 );
this.middlePanel.Name = "middlePanel";
this.middlePanel.RowCount = 3;
this.middlePanel.RowStyles.Add( new System.Windows.Forms.RowStyle( System.Windows.Forms.SizeType.Percent, 33.33333F ) );
this.middlePanel.RowStyles.Add( new System.Windows.Forms.RowStyle( System.Windows.Forms.SizeType.Percent, 33.33333F ) );
this.middlePanel.RowStyles.Add( new System.Windows.Forms.RowStyle( System.Windows.Forms.SizeType.Percent, 33.33333F ) );
this.middlePanel.Size = new System.Drawing.Size( 479, 248 );
this.middlePanel.TabIndex = 20;
//
// panel3
//
this.panel3.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.panel3.Controls.Add( this.change );
this.panel3.Controls.Add( this.label3 );
this.panel3.Location = new System.Drawing.Point( 3, 3 );
this.panel3.Name = "panel3";
this.panel3.Size = new System.Drawing.Size( 473, 76 );
this.panel3.TabIndex = 0;
//
// panel4
//
this.panel4.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.panel4.Controls.Add( this.repair );
this.panel4.Controls.Add( this.label4 );
this.panel4.Location = new System.Drawing.Point( 3, 85 );
this.panel4.Name = "panel4";
this.panel4.Size = new System.Drawing.Size( 473, 76 );
this.panel4.TabIndex = 1;
//
// panel5
//
this.panel5.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.panel5.Controls.Add( this.remove );
this.panel5.Controls.Add( this.label5 );
this.panel5.Location = new System.Drawing.Point( 3, 167 );
this.panel5.Name = "panel5";
this.panel5.Size = new System.Drawing.Size( 473, 78 );
this.panel5.TabIndex = 2;
//
// MaintenanceTypeDialog
//
this.ClientSize = new System.Drawing.Size( 494, 361 );
this.Controls.Add( this.middlePanel );
this.Controls.Add( this.topBorder );
this.Controls.Add( this.topPanel );
this.Controls.Add( this.bottomPanel );
this.Name = "MaintenanceTypeDialog";
this.Text = "[MaintenanceTypeDlg_Title]";
this.Load += new System.EventHandler( this.MaintenanceTypeDialog_Load );
this.topPanel.ResumeLayout( false );
this.topPanel.PerformLayout();
( (System.ComponentModel.ISupportInitialize)( this.banner ) ).EndInit();
this.bottomPanel.ResumeLayout( false );
this.tableLayoutPanel1.ResumeLayout( false );
this.tableLayoutPanel1.PerformLayout();
this.middlePanel.ResumeLayout( false );
this.panel3.ResumeLayout( false );
this.panel3.PerformLayout();
this.panel4.ResumeLayout( false );
this.panel4.PerformLayout();
this.panel5.ResumeLayout( false );
this.panel5.PerformLayout();
this.ResumeLayout( false );
}
#endregion
private System.Windows.Forms.PictureBox banner;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Panel topPanel;
private System.Windows.Forms.Panel bottomPanel;
private System.Windows.Forms.Button change;
private System.Windows.Forms.Button repair;
private System.Windows.Forms.Button remove;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Panel border1;
private System.Windows.Forms.Panel topBorder;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Button back;
private System.Windows.Forms.Button next;
private System.Windows.Forms.Button cancel;
private System.Windows.Forms.TableLayoutPanel middlePanel;
private System.Windows.Forms.Panel panel3;
private System.Windows.Forms.Panel panel4;
private System.Windows.Forms.Panel panel5;
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Linq;
using System.Text.RegularExpressions;
using Gallio.Common.Xml.Paths;
using Gallio.Framework.Assertions;
using MbUnit.Framework;
using System.Collections.Generic;
using System.Text;
using Gallio.Common.Collections;
using System.Reflection;
using System.IO;
using Gallio.Common.Xml;
namespace MbUnit.Tests.Framework
{
[TestsOn(typeof(Assert))]
public class AssertTest_Xml_Exists : BaseAssertTest
{
[Test]
[ExpectedArgumentNullException]
public void Assert_Exists_with_null_reader_should_throw_exception()
{
Assert.Xml.Exists((TextReader)null, XmlPath.Element("Root"), XmlOptions.Default);
}
[Test]
[ExpectedArgumentNullException]
public void Assert_Exists_with_null_xml_should_throw_exception()
{
Assert.Xml.Exists((string)null, XmlPath.Element("Root"), XmlOptions.Default);
}
[Test]
[ExpectedArgumentNullException]
public void Assert_Exists_with_null_path_should_throw_exception()
{
Assert.Xml.Exists("<xml/>", (IXmlPathLoose)null, XmlOptions.Default);
}
[Test]
[ExpectedArgumentNullException]
public void Assert_Exists_with_null_text_path_should_throw_exception()
{
Assert.Xml.Exists("<xml/>", (string)null, XmlOptions.Default);
}
[Test]
[Factory("GetTestCases")]
public void Assert_Exists(string description, string xml, string path, string expectedValue, XmlOptions options, bool shouldPass)
{
AssertionFailure[] failures = Capture(() => Assert.Xml.Exists(xml, path, options, expectedValue, description));
Assert.AreEqual(shouldPass ? 0 : 1, failures.Length);
}
private IEnumerable<object[]> GetTestCases()
{
yield return new object[]
{
"Should find root element.",
"<Root/>",
"/Root", null,
XmlOptions.Default, true
};
yield return new object[]
{
"Should find root element (case insensitive).",
"<Root/>",
"/ROOT", null,
XmlOptions.Custom.IgnoreElementsNameCase, true
};
yield return new object[]
{
"Should not find root element.",
"<Root/>",
"/DoesNotExist", null,
XmlOptions.Default, false
};
yield return new object[]
{
"Should not find root element (case sensitive).",
"<Root/>",
"/ROOT", null,
XmlOptions.Default, false
};
yield return new object[]
{
"Should find child element at depth 1.",
"<Root><Child/></Root>",
"/Root/Child", null,
XmlOptions.Default, true
};
yield return new object[]
{
"Should find attribute in root element.",
"<Root value='123' />",
"/Root:value", null,
XmlOptions.Default, true
};
yield return new object[]
{
"Should find attribute in root element (case insensitive).",
"<Root value='123' />",
"/Root:VALUE", null,
XmlOptions.Custom.IgnoreAttributesNameCase, true
};
yield return new object[]
{
"Should not find attribute in root element.",
"<Root value='123' />",
"/Root:doesNotExist", null,
XmlOptions.Default, false
};
yield return new object[]
{
"Should not find attribute in root element (case sensitive).",
"<Root value='123' />",
"/Root:VALUE", null,
XmlOptions.Default, false
};
yield return new object[]
{
"Should find attribute in child element at depth 1.",
"<Root><Child value='123'/></Root>",
"/Root/Child:value", null,
XmlOptions.Default, true
};
yield return new object[]
{
"Should not find attribute in child element at depth 1.",
"<Root><Child value='123'/></Root>",
"/Root/Child:doesNotExist", null,
XmlOptions.Default, false
};
yield return new object[]
{
"Should find child element at depth 1 in a group.",
"<Root><Child1/><Child2/><Child3/></Root>",
"/Root/Child2", null,
XmlOptions.Default, true
};
yield return new object[]
{
"Should not find child element at depth 1 in a group.",
"<Root><Child1/><Child2/><Child3/></Root>",
"/Root/DoesNotExist", null,
XmlOptions.Default, false
};
yield return new object[]
{
"Should find attribute in a child element at depth 1.",
"<Root><Child/><Child/><Child value='123'/></Root>",
"/Root/Child:value", null,
XmlOptions.Default, true
};
yield return new object[]
{
"Should not find attribute in a child element at depth 1.",
"<Root><Child/><Child/><Child value='123'/></Root>",
"/Root/Child:doesNotExist", null,
XmlOptions.Default, false
};
yield return new object[]
{
"Should find child element at depth 2 in a group.",
"<Root><Child/><Child><Node/></Child><Child/></Root>",
"/Root/Child/Node", null,
XmlOptions.Default, true
};
yield return new object[]
{
"Should find deep attribute in a complex tree.",
GetTextResource("MbUnit.Tests.Framework.SolarSystem.xml"),
"/SolarSystem/Planets/Planet/Satellites/Satellite:name", null,
XmlOptions.Default, true
};
yield return new object[]
{
"Should child at lower depth than maximum depth in the tree.",
"<Root><Parent><Child/></Parent></Root>",
"/Root/Parent", null,
XmlOptions.Default, true
};
yield return new object[]
{
"Should find root element with value.",
"<Root>Hello</Root>",
"/Root", "Hello",
XmlOptions.Default, true
};
yield return new object[]
{
"Should not find root element with wrong value.",
"<Root>Hello</Root>",
"/Root", "Good Morning",
XmlOptions.Default, false
};
yield return new object[]
{
"Should find root element with value (case insensitive).",
"<Root>Hello</Root>",
"/Root", "HELLO",
XmlOptions.Custom.IgnoreAllCase, true
};
yield return new object[]
{
"Should find attribute value in root element.",
"<Root value='Hello' />",
"/Root:value", "Hello",
XmlOptions.Default, true
};
yield return new object[]
{
"Should not find attribute with wrong value in root element.",
"<Root value='Hello' />",
"/Root:value", "Goodbye",
XmlOptions.Default, false
};
yield return new object[]
{
"Should find deep attribute name/value in a complex tree.",
GetTextResource("MbUnit.Tests.Framework.SolarSystem.xml"),
"/SolarSystem/Planets/Planet/Satellites/Satellite:name", "Tethys",
XmlOptions.Default, true
};
yield return new object[]
{
"Should not find deep attribute name with wrong value in a complex tree.",
GetTextResource("MbUnit.Tests.Framework.SolarSystem.xml"),
"/SolarSystem/Planets/Planet/Satellites/Satellite:name", "Vador's Dark Star",
XmlOptions.Default, false
};
yield return new object[]
{
"Should not find attribute value in a child element at depth 1.",
"<Root><Child/></Root>",
"/Root/Child:attribute", null,
XmlOptions.Default, false
};
}
}
}
| |
//
// NodeAttributeAttribute.cs
//
// Author:
// Lluis Sanchez Gual
//
// Copyright (C) 2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Mono.Addins
{
/// <summary>
/// Indicates that a field or property is bound to a node attribute
/// </summary>
[AttributeUsage (AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple=true)]
public class NodeAttributeAttribute: Attribute
{
string name;
bool required;
bool localizable;
Type type;
string typeName;
string description;
/// <summary>
/// Initializes a new instance
/// </summary>
public NodeAttributeAttribute ()
{
}
/// <summary>
/// Initializes a new instance
/// </summary>
/// <param name="name">
/// XML name of the attribute.
/// </param>
public NodeAttributeAttribute (string name)
:this (name, false, null)
{
}
/// <summary>
/// Initializes a new instance
/// </summary>
/// <param name="name">
/// XML name of the attribute.
/// </param>
/// <param name="description">
/// Description of the attribute.
/// </param>
public NodeAttributeAttribute (string name, string description)
:this (name, false, description)
{
}
/// <summary>
/// Initializes a new instance
/// </summary>
/// <param name="name">
/// XML name of the attribute.
/// </param>
/// <param name="required">
/// Indicates whether the attribute is required or not.
/// </param>
public NodeAttributeAttribute (string name, bool required)
: this (name, required, null)
{
}
/// <summary>
/// Initializes a new instance
/// </summary>
/// <param name="name">
/// XML name of the attribute.
/// </param>
/// <param name="required">
/// Indicates whether the attribute is required or not.
/// </param>
/// <param name="description">
/// Description of the attribute.
/// </param>
public NodeAttributeAttribute (string name, bool required, string description)
{
this.name = name;
this.required = required;
this.description = description;
}
/// <summary>
/// Initializes a new instance
/// </summary>
/// <param name="name">
/// XML name of the attribute.
/// </param>
/// <param name="type">
/// Type of the extension node attribute.
/// </param>
/// <remarks>
/// The type of the attribute is only required when applying this attribute at class level.
/// It is not required when it is applied to a field, since the attribute type will be the type of the field.
/// </remarks>
public NodeAttributeAttribute (string name, Type type)
: this (name, type, false, null)
{
}
/// <summary>
/// Initializes a new instance
/// </summary>
/// <param name="name">
/// XML name of the attribute.
/// </param>
/// <param name="type">
/// Type of the extension node attribute.
/// </param>
/// <param name="description">
/// Description of the attribute.
/// </param>
/// <remarks>
/// The type of the attribute is only required when applying this attribute at class level.
/// It is not required when it is applied to a field, since the attribute type will be the type of the field.
/// </remarks>
public NodeAttributeAttribute (string name, Type type, string description)
: this (name, type, false, description)
{
}
/// <summary>
/// Initializes a new instance
/// </summary>
/// <param name="name">
/// XML name of the attribute.
/// </param>
/// <param name="type">
/// Type of the extension node attribute.
/// </param>
/// <param name="required">
/// Indicates whether the attribute is required or not.
/// </param>
/// <remarks>
/// The type of the attribute is only required when applying this attribute at class level.
/// It is not required when it is applied to a field, since the attribute type will be the type of the field.
/// </remarks>
public NodeAttributeAttribute (string name, Type type, bool required)
: this (name, type, false, null)
{
}
/// <summary>
/// Initializes a new instance
/// </summary>
/// <param name="name">
/// XML name of the attribute.
/// </param>
/// <param name="type">
/// Type of the extension node attribute.
/// </param>
/// <param name="required">
/// Indicates whether the attribute is required or not.
/// </param>
/// <param name="description">
/// Description of the attribute.
/// </param>
/// <remarks>
/// The type of the attribute is only required when applying this attribute at class level.
/// It is not required when it is applied to a field, since the attribute type will be the type of the field.
/// </remarks>
public NodeAttributeAttribute (string name, Type type, bool required, string description)
{
this.name = name;
this.type = type;
this.required = required;
this.description = description;
}
/// <summary>
/// XML name of the attribute.
/// </summary>
/// <remarks>
/// If the name is not specified, the field name to which the [NodeAttribute]
/// is applied will be used as name. Providing a name is mandatory when applying
/// [NodeAttribute] at class level.
/// </remarks>
public string Name {
get { return name != null ? name : string.Empty; }
set { name = value; }
}
/// <summary>
/// Indicates whether the attribute is required or not.
/// </summary>
public bool Required {
get { return required; }
set { required = value; }
}
/// <summary>
/// Type of the extension node attribute.
/// </summary>
/// <remarks>
/// To be used only when applying [NodeAttribute] at class level. It is not required when it
/// is applied to a field, since the attribute type will be the type of the field.
/// </remarks>
public Type Type {
get { return type; }
set { type = value; typeName = type.FullName; }
}
internal string TypeName {
get { return typeName; }
set { typeName = value; type = null; }
}
/// <summary>
/// Description of the attribute.
/// </summary>
/// <remarks>
/// To be used in the extension point documentation.
/// </remarks>
public string Description {
get { return description != null ? description : string.Empty; }
set { description = value; }
}
/// <summary>
/// When set to True, the value of the field or property is expected to be a string id which
/// will be localized by the add-in engine
/// </summary>
public bool Localizable {
get { return localizable; }
set { localizable = value; }
}
/// <summary>
/// Gets or sets the type of the content.
/// </summary>
/// <remarks>
/// Allows specifying the type of the content of a string attribute.
/// This value is for documentation purposes only.
/// </remarks>
public ContentType ContentType { get; set; }
}
}
| |
using Csla;
using System.ComponentModel.DataAnnotations;
using System;
using System.ComponentModel;
using Csla.Rules;
namespace ProjectTracker.Library
{
[Serializable]
public class ProjectResourceEdit : BusinessBase<ProjectResourceEdit>
{
public static readonly PropertyInfo<byte[]> TimeStampProperty = RegisterProperty<byte[]>(c => c.TimeStamp);
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public byte[] TimeStamp
{
get { return GetProperty(TimeStampProperty); }
set { SetProperty(TimeStampProperty, value); }
}
public static readonly PropertyInfo<int> ResourceIdProperty =
RegisterProperty<int>(c => c.ResourceId);
[Display(Name = "Resource id")]
public int ResourceId
{
get { return GetProperty(ResourceIdProperty); }
private set { LoadProperty(ResourceIdProperty, value); }
}
public static readonly PropertyInfo<string> FirstNameProperty =
RegisterProperty<string>(c => c.FirstName);
[Display(Name = "First name")]
public string FirstName
{
get { return GetProperty(FirstNameProperty); }
private set { LoadProperty(FirstNameProperty, value); }
}
public static readonly PropertyInfo<string> LastNameProperty =
RegisterProperty<string>(c => c.LastName);
[Display(Name = "Last name")]
public string LastName
{
get { return GetProperty(LastNameProperty); }
private set { LoadProperty(LastNameProperty, value); }
}
[Display(Name = "Full name")]
public string FullName
{
get { return string.Format("{0}, {1}", LastName, FirstName); }
}
public static readonly PropertyInfo<DateTime> AssignedProperty =
RegisterProperty<DateTime>(c => c.Assigned);
[Display(Name = "Date assigned")]
public DateTime Assigned
{
get { return GetProperty(AssignedProperty); }
private set { LoadProperty(AssignedProperty, value); }
}
public static readonly PropertyInfo<int> RoleProperty =
RegisterProperty<int>(c => c.Role);
[Display(Name = "Role assigned")]
public int Role
{
get { return GetProperty(RoleProperty); }
set { SetProperty(RoleProperty, value); }
}
[Display(Name = "Role")]
public string RoleName
{
get
{
var result = "none";
if (RoleList.GetCachedList().ContainsKey(Role))
result = RoleList.GetCachedList().GetItemByKey(Role).Value;
return result;
}
}
public override string ToString()
{
return ResourceId.ToString();
}
protected override void AddBusinessRules()
{
base.AddBusinessRules();
BusinessRules.AddRule(new ValidRole(RoleProperty));
BusinessRules.AddRule(new NotifyRoleNameChanged(RoleProperty));
BusinessRules.AddRule(
new Csla.Rules.CommonRules.IsInRole(
Csla.Rules.AuthorizationActions.WriteProperty, RoleProperty, "ProjectManager"));
}
private class NotifyRoleNameChanged : BusinessRule
{
public NotifyRoleNameChanged(Csla.Core.IPropertyInfo primaryProperty)
: base(primaryProperty)
{ }
protected override void Execute(RuleContext context)
{
((ProjectResourceEdit)context.Target).OnPropertyChanged("RoleName");
}
}
#if FULL_DOTNET
private void Child_Create(int resourceId)
{
using (BypassPropertyChecks)
{
ResourceId = resourceId;
Role = RoleList.DefaultRole();
LoadProperty(AssignedProperty, DateTime.Today);
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
var dal = ctx.GetProvider<ProjectTracker.Dal.IResourceDal>();
var person = dal.Fetch(resourceId);
FirstName = person.FirstName;
LastName = person.LastName;
}
}
base.Child_Create();
}
private void Child_Fetch(int projectId, int resourceId)
{
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
var dal = ctx.GetProvider<ProjectTracker.Dal.IAssignmentDal>();
var data = dal.Fetch(projectId, resourceId);
Child_Fetch(data);
}
}
private void Child_Fetch(ProjectTracker.Dal.AssignmentDto data)
{
using (BypassPropertyChecks)
{
ResourceId = data.ResourceId;
Role = data.RoleId;
LoadProperty(AssignedProperty, data.Assigned);
TimeStamp = data.LastChanged;
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
var dal = ctx.GetProvider<ProjectTracker.Dal.IResourceDal>();
var person = dal.Fetch(data.ResourceId);
FirstName = person.FirstName;
LastName = person.LastName;
}
}
}
private void Child_Insert(ProjectEdit project)
{
Child_Insert(project.Id);
}
private void Child_Insert(int projectId)
{
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
var dal = ctx.GetProvider<ProjectTracker.Dal.IAssignmentDal>();
using (BypassPropertyChecks)
{
var item = new ProjectTracker.Dal.AssignmentDto
{
ProjectId = projectId,
ResourceId = this.ResourceId,
Assigned = ReadProperty(AssignedProperty),
RoleId = this.Role
};
dal.Insert(item);
TimeStamp = item.LastChanged;
}
}
}
private void Child_Update(ProjectEdit project)
{
Child_Update(project.Id);
}
private void Child_Update(int projectId)
{
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
var dal = ctx.GetProvider<ProjectTracker.Dal.IAssignmentDal>();
using (BypassPropertyChecks)
{
var item = dal.Fetch(projectId, ResourceId);
item.Assigned = ReadProperty(AssignedProperty);
item.RoleId = Role;
item.LastChanged = TimeStamp;
dal.Update(item);
TimeStamp = item.LastChanged;
}
}
}
private void Child_DeleteSelf(ProjectEdit project)
{
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
var dal = ctx.GetProvider<ProjectTracker.Dal.IAssignmentDal>();
using (BypassPropertyChecks)
{
dal.Delete(project.Id, ResourceId);
}
}
}
#endif
}
}
| |
/*
* 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 QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Orders;
using QuantConnect.Orders.Fees;
namespace QuantConnect.Securities
{
/// <summary>
/// SecurityHolding is a base class for purchasing and holding a market item which manages the asset portfolio
/// </summary>
public class SecurityHolding
{
/// <summary>
/// Event raised each time the holdings quantity is changed.
/// </summary>
public event EventHandler<SecurityHoldingQuantityChangedEventArgs> QuantityChanged;
//Working Variables
private decimal _averagePrice;
private decimal _quantity;
private decimal _price;
private decimal _totalSaleVolume;
private decimal _profit;
private decimal _lastTradeProfit;
private decimal _totalFees;
private readonly Security _security;
private readonly ICurrencyConverter _currencyConverter;
/// <summary>
/// Create a new holding class instance setting the initial properties to $0.
/// </summary>
/// <param name="security">The security being held</param>
/// <param name="currencyConverter">A currency converter instance</param>
public SecurityHolding(Security security, ICurrencyConverter currencyConverter)
{
_security = security;
//Total Sales Volume for the day
_totalSaleVolume = 0;
_lastTradeProfit = 0;
_currencyConverter = currencyConverter;
}
/// <summary>
/// Create a new holding class instance copying the initial properties
/// </summary>
/// <param name="holding">The security being held</param>
protected SecurityHolding(SecurityHolding holding)
{
_security = holding._security;
_averagePrice = holding._averagePrice;
_quantity = holding._quantity;
_price = holding._price;
_totalSaleVolume = holding._totalSaleVolume;
_profit = holding._profit;
_lastTradeProfit = holding._lastTradeProfit;
_totalFees = holding._totalFees;
_currencyConverter = holding._currencyConverter;
}
/// <summary>
/// The security being held
/// </summary>
protected Security Security
{
get
{
return _security;
}
}
/// <summary>
/// Gets the current target holdings for this security
/// </summary>
public IPortfolioTarget Target
{
get; set;
}
/// <summary>
/// Average price of the security holdings.
/// </summary>
public decimal AveragePrice
{
get
{
return _averagePrice;
}
protected set
{
_averagePrice = value;
}
}
/// <summary>
/// Quantity of the security held.
/// </summary>
/// <remarks>Positive indicates long holdings, negative quantity indicates a short holding</remarks>
/// <seealso cref="AbsoluteQuantity"/>
public decimal Quantity
{
get
{
return _quantity;
}
protected set
{
_quantity = value;
}
}
/// <summary>
/// Symbol identifier of the underlying security.
/// </summary>
public Symbol Symbol
{
get
{
return _security.Symbol;
}
}
/// <summary>
/// The security type of the symbol
/// </summary>
public SecurityType Type
{
get
{
return _security.Type;
}
}
/// <summary>
/// Leverage of the underlying security.
/// </summary>
public virtual decimal Leverage
{
get
{
return _security.BuyingPowerModel.GetLeverage(_security);
}
}
/// <summary>
/// Acquisition cost of the security total holdings in units of the account's currency.
/// </summary>
public virtual decimal HoldingsCost
{
get
{
if (Quantity == 0)
{
return 0;
}
return AveragePrice * Quantity * _security.QuoteCurrency.ConversionRate * _security.SymbolProperties.ContractMultiplier;
}
}
/// <summary>
/// Unlevered Acquisition cost of the security total holdings in units of the account's currency.
/// </summary>
public virtual decimal UnleveredHoldingsCost
{
get { return HoldingsCost/Leverage; }
}
/// <summary>
/// Current market price of the security.
/// </summary>
public virtual decimal Price
{
get
{
return _price;
}
protected set
{
_price = value;
}
}
/// <summary>
/// Absolute holdings cost for current holdings in units of the account's currency.
/// </summary>
/// <seealso cref="HoldingsCost"/>
public virtual decimal AbsoluteHoldingsCost
{
get
{
return Math.Abs(HoldingsCost);
}
}
/// <summary>
/// Unlevered absolute acquisition cost of the security total holdings in units of the account's currency.
/// </summary>
public virtual decimal UnleveredAbsoluteHoldingsCost
{
get
{
return Math.Abs(UnleveredHoldingsCost);
}
}
/// <summary>
/// Market value of our holdings in units of the account's currency.
/// </summary>
public virtual decimal HoldingsValue
{
get
{
if (Quantity == 0)
{
return 0;
}
return GetQuantityValue(Quantity);
}
}
/// <summary>
/// Absolute of the market value of our holdings in units of the account's currency.
/// </summary>
/// <seealso cref="HoldingsValue"/>
public virtual decimal AbsoluteHoldingsValue
{
get { return Math.Abs(HoldingsValue); }
}
/// <summary>
/// Boolean flat indicating if we hold any of the security
/// </summary>
public virtual bool HoldStock
{
get
{
return (AbsoluteQuantity > 0);
}
}
/// <summary>
/// Boolean flat indicating if we hold any of the security
/// </summary>
/// <remarks>Alias of HoldStock</remarks>
/// <seealso cref="HoldStock"/>
public virtual bool Invested
{
get
{
return HoldStock;
}
}
/// <summary>
/// The total transaction volume for this security since the algorithm started in units of the account's currency.
/// </summary>
public virtual decimal TotalSaleVolume
{
get { return _totalSaleVolume; }
}
/// <summary>
/// Total fees for this company since the algorithm started in units of the account's currency.
/// </summary>
public virtual decimal TotalFees
{
get { return _totalFees; }
}
/// <summary>
/// Boolean flag indicating we have a net positive holding of the security.
/// </summary>
/// <seealso cref="IsShort"/>
public virtual bool IsLong
{
get
{
return Quantity > 0;
}
}
/// <summary>
/// BBoolean flag indicating we have a net negative holding of the security.
/// </summary>
/// <seealso cref="IsLong"/>
public virtual bool IsShort
{
get
{
return Quantity < 0;
}
}
/// <summary>
/// Absolute quantity of holdings of this security
/// </summary>
/// <seealso cref="Quantity"/>
public virtual decimal AbsoluteQuantity
{
get
{
return Math.Abs(Quantity);
}
}
/// <summary>
/// Record of the closing profit from the last trade conducted in units of the account's currency.
/// </summary>
public virtual decimal LastTradeProfit
{
get
{
return _lastTradeProfit;
}
}
/// <summary>
/// Calculate the total profit for this security in units of the account's currency.
/// </summary>
/// <seealso cref="NetProfit"/>
public virtual decimal Profit
{
get { return _profit; }
}
/// <summary>
/// Return the net for this company measured by the profit less fees in units of the account's currency.
/// </summary>
/// <seealso cref="Profit"/>
/// <seealso cref="TotalFees"/>
public virtual decimal NetProfit
{
get
{
return Profit - TotalFees;
}
}
/// <summary>
/// Gets the unrealized profit as a percenage of holdings cost
/// </summary>
public virtual decimal UnrealizedProfitPercent
{
get
{
if (AbsoluteHoldingsCost == 0) return 0m;
return UnrealizedProfit/AbsoluteHoldingsCost;
}
}
/// <summary>
/// Unrealized profit of this security when absolute quantity held is more than zero in units of the account's currency.
/// </summary>
public virtual decimal UnrealizedProfit
{
get { return TotalCloseProfit(); }
}
/// <summary>
/// Adds a fee to the running total of total fees in units of the account's currency.
/// </summary>
/// <param name="newFee"></param>
public void AddNewFee(decimal newFee)
{
_totalFees += newFee;
}
/// <summary>
/// Adds a profit record to the running total of profit in units of the account's currency.
/// </summary>
/// <param name="profitLoss">The cash change in portfolio from closing a position</param>
public void AddNewProfit(decimal profitLoss)
{
_profit += profitLoss;
}
/// <summary>
/// Adds a new sale value to the running total trading volume in units of the account's currency.
/// </summary>
/// <param name="saleValue"></param>
public void AddNewSale(decimal saleValue)
{
_totalSaleVolume += saleValue;
}
/// <summary>
/// Set the last trade profit for this security from a Portfolio.ProcessFill call in units of the account's currency.
/// </summary>
/// <param name="lastTradeProfit">Value of the last trade profit</param>
public void SetLastTradeProfit(decimal lastTradeProfit)
{
_lastTradeProfit = lastTradeProfit;
}
/// <summary>
/// Set the quantity of holdings and their average price after processing a portfolio fill.
/// </summary>
public virtual void SetHoldings(decimal averagePrice, int quantity)
{
SetHoldings(averagePrice, (decimal) quantity);
}
/// <summary>
/// Set the quantity of holdings and their average price after processing a portfolio fill.
/// </summary>
public virtual void SetHoldings(decimal averagePrice, decimal quantity)
{
var previousQuantity = _quantity;
var previousAveragePrice = _averagePrice;
_quantity = quantity;
_averagePrice = averagePrice;
OnQuantityChanged(previousAveragePrice, previousQuantity);
}
/// <summary>
/// Update local copy of closing price value.
/// </summary>
/// <param name="closingPrice">Price of the underlying asset to be used for calculating market price / portfolio value</param>
public virtual void UpdateMarketPrice(decimal closingPrice)
{
_price = closingPrice;
}
/// <summary>
/// Gets the total value of the specified <paramref name="quantity"/> of shares of this security
/// in the account currency
/// </summary>
/// <param name="quantity">The quantity of shares</param>
/// <returns>The value of the quantity of shares in the account currency</returns>
public virtual decimal GetQuantityValue(decimal quantity)
{
return GetQuantityValue(quantity, _price);
}
/// <summary>
/// Gets the total value of the specified <paramref name="quantity"/> of shares of this security
/// in the account currency
/// </summary>
/// <param name="quantity">The quantity of shares</param>
/// <param name="price">The current price</param>
/// <returns>The value of the quantity of shares in the account currency</returns>
public virtual decimal GetQuantityValue(decimal quantity, decimal price)
{
return price * quantity * _security.QuoteCurrency.ConversionRate * _security.SymbolProperties.ContractMultiplier;
}
/// <summary>
/// Profit if we closed the holdings right now including the approximate fees in units of the account's currency.
/// </summary>
/// <remarks>Does not use the transaction model for market fills but should.</remarks>
public virtual decimal TotalCloseProfit()
{
if (Quantity == 0)
{
return 0;
}
// this is in the account currency
var marketOrder = new MarketOrder(_security.Symbol, -Quantity, _security.LocalTime.ConvertToUtc(_security.Exchange.TimeZone));
var orderFee = _security.FeeModel.GetOrderFee(
new OrderFeeParameters(_security, marketOrder)).Value;
var feesInAccountCurrency = _currencyConverter.
ConvertToAccountCurrency(orderFee).Amount;
var price = marketOrder.Direction == OrderDirection.Sell ? _security.BidPrice : _security.AskPrice;
if (price == 0)
{
// Bid/Ask prices can both be equal to 0. This usually happens when we request our holdings from
// the brokerage, but only the last trade price was provided.
price = _security.Price;
}
return (price - AveragePrice) * Quantity * _security.QuoteCurrency.ConversionRate
* _security.SymbolProperties.ContractMultiplier - feesInAccountCurrency;
}
/// <summary>
/// Event invocator for the <see cref="QuantityChanged"/> event
/// </summary>
protected virtual void OnQuantityChanged(decimal previousAveragePrice, decimal previousQuantity)
{
QuantityChanged?.Invoke(this, new SecurityHoldingQuantityChangedEventArgs(
_security, previousAveragePrice, previousQuantity
));
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.ADF.CATIDs;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.esriSystem;
namespace ReshapePolylineEditTask_CS
{
[Guid("89467aa7-76c1-4531-a160-e160e8d782f7")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("ReshapePolylineEditTask_CS.ReshapePolylineEditTask")]
public class ReshapePolylineEditTask : ESRI.ArcGIS.Controls.IEngineEditTask
{
#region Private Members
IEngineEditor m_engineEditor;
IEngineEditSketch m_editSketch;
IEngineEditLayers m_editLayer;
#endregion
#region COM Registration Function(s)
[ComRegisterFunction()]
[ComVisible(false)]
static void RegisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryRegistration(registerType);
}
[ComUnregisterFunction()]
[ComVisible(false)]
static void UnregisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryUnregistration(registerType);
}
#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);
EngineEditTasks.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);
EngineEditTasks.Unregister(regKey);
}
#endregion
#endregion
#region IEngineEditTask Implementations
public void Activate(ESRI.ArcGIS.Controls.IEngineEditor editor, ESRI.ArcGIS.Controls.IEngineEditTask oldTask)
{
if (editor == null)
return;
m_engineEditor = editor;
m_editSketch = m_engineEditor as IEngineEditSketch;
m_editSketch.GeometryType = esriGeometryType.esriGeometryPolyline;
m_editLayer = m_editSketch as IEngineEditLayers;
//Listen to engine editor events
((IEngineEditEvents_Event)m_editSketch).OnTargetLayerChanged += new IEngineEditEvents_OnTargetLayerChangedEventHandler(OnTargetLayerChanged);
((IEngineEditEvents_Event)m_editSketch).OnSelectionChanged += new IEngineEditEvents_OnSelectionChangedEventHandler(OnSelectionChanged);
((IEngineEditEvents_Event)m_editSketch).OnCurrentTaskChanged += new IEngineEditEvents_OnCurrentTaskChangedEventHandler(OnCurrentTaskChanged);
}
public void Deactivate()
{
m_editSketch.RefreshSketch();
//Stop listening to engine editor events.
((IEngineEditEvents_Event)m_editSketch).OnTargetLayerChanged -= OnTargetLayerChanged;
((IEngineEditEvents_Event)m_editSketch).OnSelectionChanged -= OnSelectionChanged;
((IEngineEditEvents_Event)m_editSketch).OnCurrentTaskChanged -= OnCurrentTaskChanged;
//Release object references.
m_engineEditor = null;
m_editSketch = null;
m_editLayer = null;
}
public string GroupName
{
get
{
//This property allows groups to be created/used in the EngineEditTaskToolControl treeview.
//If an empty string is supplied the task will be appear in an "Other Tasks" group.
//In this example the Reshape Polyline_CSharp task will appear in the existing Modify Tasks group.
return "Modify Tasks";
}
}
public string Name
{
get
{
return "Reshape Polyline_CSharp"; //unique edit task name
}
}
public void OnDeleteSketch()
{
}
public void OnFinishSketch()
{
//get reference to featurelayer being edited
IFeatureLayer featureLayer = m_editLayer.TargetLayer as IFeatureLayer;
//get reference to the sketch geometry
IGeometry reshapeGeom = m_editSketch.Geometry;
if (reshapeGeom.IsEmpty == false)
{
//get the currently selected feature
IFeatureSelection featureSelection = featureLayer as IFeatureSelection;
ISelectionSet selectionSet = featureSelection.SelectionSet;
ICursor cursor;
selectionSet.Search(null, false, out cursor);
IFeatureCursor featureCursor = cursor as IFeatureCursor;
//the PerformSketchToolEnabledChecks property has already checked that only 1 feature is selected
IFeature feature = featureCursor.NextFeature();
//Take a copy of geometry for the selected feature
IGeometry editShape = feature.ShapeCopy;
//create a path from the editsketch geometry
IPointCollection reshapePath = new PathClass();
reshapePath.AddPointCollection(reshapeGeom as IPointCollection);
//reshape the selected feature
IPolyline polyline = editShape as IPolyline;
polyline.Reshape(reshapePath as IPath);
#region Perform an edit operation to store the new geometry for selected feature
try
{
m_engineEditor.StartOperation();
feature.Shape = editShape;
feature.Store();
m_engineEditor.StopOperation("Reshape Feature");
}
catch (Exception ex)
{
m_engineEditor.AbortOperation();
System.Diagnostics.Trace.WriteLine(ex.Message, "Reshape Geometry Failed");
}
#endregion
}
//refresh the display
IActiveView activeView = m_engineEditor.Map as IActiveView;
activeView.PartialRefresh(esriViewDrawPhase.esriViewGeography, (object)featureLayer, activeView.Extent);
}
public string UniqueName
{
get
{
return "ReshapePolylineEditTask_Reshape Polyline_CSharp" ;
}
}
#endregion
#region Event Listeners
public void OnTargetLayerChanged()
{
PerformSketchToolEnabledChecks();
}
public void OnSelectionChanged()
{
PerformSketchToolEnabledChecks();
}
void OnCurrentTaskChanged()
{
if (m_engineEditor.CurrentTask.Name == "Reshape Polyline_CSharp")
{
PerformSketchToolEnabledChecks();
}
}
#endregion
#region private methods
private void PerformSketchToolEnabledChecks()
{
if (m_editLayer == null)
return;
//Only enable the sketch tool if there is a polyline target layer.
if (m_editLayer.TargetLayer.FeatureClass.ShapeType != esriGeometryType.esriGeometryPolyline)
{
m_editSketch.GeometryType = esriGeometryType.esriGeometryNull;
return;
}
//check that only one feature in the target layer is currently selected
IFeatureSelection featureSelection = m_editLayer.TargetLayer as IFeatureSelection;
ISelectionSet selectionSet = featureSelection.SelectionSet;
if (selectionSet.Count != 1)
{
m_editSketch.GeometryType = esriGeometryType.esriGeometryNull;
return;
}
m_editSketch.GeometryType = esriGeometryType.esriGeometryPolyline;
}
#endregion
}
}
| |
// 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.Linq;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Extensions.DependencyModel;
using NuGet.Frameworks;
using NuGet.Packaging;
using NuGet.Packaging.Core;
using NuGet.ProjectModel;
namespace Microsoft.DotNet.Cli.Utils
{
internal class DepsJsonBuilder
{
private readonly VersionFolderPathResolver _versionFolderPathResolver;
public DepsJsonBuilder()
{
// This resolver is only used for building file names, so that base path is not required.
_versionFolderPathResolver = new VersionFolderPathResolver(rootPath: null);
}
public DependencyContext Build(
SingleProjectInfo mainProjectInfo,
CompilationOptions compilationOptions,
LockFile lockFile,
NuGetFramework framework,
string runtime)
{
bool includeCompilationLibraries = compilationOptions != null;
LockFileTarget lockFileTarget = lockFile.GetTarget(framework, runtime);
IEnumerable<LockFileTargetLibrary> runtimeExports = lockFileTarget.GetRuntimeLibraries();
IEnumerable<LockFileTargetLibrary> compilationExports =
includeCompilationLibraries ?
lockFileTarget.GetCompileLibraries() :
Enumerable.Empty<LockFileTargetLibrary>();
var dependencyLookup = compilationExports
.Concat(runtimeExports)
.Distinct()
.Select(library => new Dependency(library.Name, library.Version.ToString()))
.ToDictionary(dependency => dependency.Name, StringComparer.OrdinalIgnoreCase);
var libraryLookup = lockFile.Libraries.ToDictionary(l => l.Name, StringComparer.OrdinalIgnoreCase);
var runtimeSignature = GenerateRuntimeSignature(runtimeExports);
IEnumerable<RuntimeLibrary> runtimeLibraries =
GetLibraries(runtimeExports, libraryLookup, dependencyLookup, runtime: true).Cast<RuntimeLibrary>();
IEnumerable<CompilationLibrary> compilationLibraries;
if (includeCompilationLibraries)
{
CompilationLibrary projectCompilationLibrary = GetProjectCompilationLibrary(
mainProjectInfo,
lockFile,
lockFileTarget,
dependencyLookup);
compilationLibraries = new[] { projectCompilationLibrary }
.Concat(
GetLibraries(compilationExports, libraryLookup, dependencyLookup, runtime: false)
.Cast<CompilationLibrary>());
}
else
{
compilationLibraries = Enumerable.Empty<CompilationLibrary>();
}
return new DependencyContext(
new TargetInfo(framework.DotNetFrameworkName, runtime, runtimeSignature, lockFileTarget.IsPortable()),
compilationOptions ?? CompilationOptions.Default,
compilationLibraries,
runtimeLibraries,
new RuntimeFallbacks[] { });
}
private static string GenerateRuntimeSignature(IEnumerable<LockFileTargetLibrary> runtimeExports)
{
var sha1 = SHA1.Create();
var builder = new StringBuilder();
var packages = runtimeExports
.Where(libraryExport => libraryExport.Type == "package");
var separator = "|";
foreach (var libraryExport in packages)
{
builder.Append(libraryExport.Name);
builder.Append(separator);
builder.Append(libraryExport.Version.ToString());
builder.Append(separator);
}
var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(builder.ToString()));
builder.Clear();
foreach (var hashByte in hash)
{
builder.AppendFormat("{0:x2}", hashByte);
}
return builder.ToString();
}
private List<Dependency> GetProjectDependencies(
LockFile lockFile,
LockFileTarget lockFileTarget,
Dictionary<string, Dependency> dependencyLookup)
{
List<Dependency> dependencies = new List<Dependency>();
IEnumerable<ProjectFileDependencyGroup> projectFileDependencies = lockFile
.ProjectFileDependencyGroups
.Where(dg => dg.FrameworkName == string.Empty ||
dg.FrameworkName == lockFileTarget.TargetFramework.DotNetFrameworkName);
foreach (string projectFileDependency in projectFileDependencies.SelectMany(dg => dg.Dependencies))
{
int separatorIndex = projectFileDependency.IndexOf(' ');
string dependencyName = separatorIndex > 0 ?
projectFileDependency.Substring(0, separatorIndex) :
projectFileDependency;
Dependency dependency;
if (dependencyLookup.TryGetValue(dependencyName, out dependency))
{
dependencies.Add(dependency);
}
}
return dependencies;
}
private RuntimeLibrary GetProjectRuntimeLibrary(
SingleProjectInfo projectInfo,
LockFile lockFile,
LockFileTarget lockFileTarget,
Dictionary<string, Dependency> dependencyLookup)
{
RuntimeAssetGroup[] runtimeAssemblyGroups = new[] { new RuntimeAssetGroup(string.Empty, projectInfo.GetOutputName()) };
List<Dependency> dependencies = GetProjectDependencies(lockFile, lockFileTarget, dependencyLookup);
ResourceAssembly[] resourceAssemblies = projectInfo
.ResourceAssemblies
.Select(r => new ResourceAssembly(r.RelativePath, r.Culture))
.ToArray();
return new RuntimeLibrary(
type: "project",
name: projectInfo.Name,
version: projectInfo.Version,
hash: string.Empty,
runtimeAssemblyGroups: runtimeAssemblyGroups,
nativeLibraryGroups: new RuntimeAssetGroup[] { },
resourceAssemblies: resourceAssemblies,
dependencies: dependencies.ToArray(),
serviceable: false);
}
private CompilationLibrary GetProjectCompilationLibrary(
SingleProjectInfo projectInfo,
LockFile lockFile,
LockFileTarget lockFileTarget,
Dictionary<string, Dependency> dependencyLookup)
{
List<Dependency> dependencies = GetProjectDependencies(lockFile, lockFileTarget, dependencyLookup);
return new CompilationLibrary(
type: "project",
name: projectInfo.Name,
version: projectInfo.Version,
hash: string.Empty,
assemblies: new[] { projectInfo.GetOutputName() },
dependencies: dependencies.ToArray(),
serviceable: false);
}
private IEnumerable<Library> GetLibraries(
IEnumerable<LockFileTargetLibrary> exports,
IDictionary<string, LockFileLibrary> libraryLookup,
IDictionary<string, Dependency> dependencyLookup,
bool runtime)
{
return exports.Select(export => GetLibrary(export, libraryLookup, dependencyLookup, runtime));
}
private Library GetLibrary(
LockFileTargetLibrary export,
IDictionary<string, LockFileLibrary> libraryLookup,
IDictionary<string, Dependency> dependencyLookup,
bool runtime)
{
var type = export.Type;
// TEMPORARY: All packages are serviceable in RC2
// See https://github.com/dotnet/cli/issues/2569
var serviceable = export.Type == "package";
var libraryDependencies = new HashSet<Dependency>();
foreach (PackageDependency libraryDependency in export.Dependencies)
{
Dependency dependency;
if (dependencyLookup.TryGetValue(libraryDependency.Id, out dependency))
{
libraryDependencies.Add(dependency);
}
}
string hash = string.Empty;
string path = null;
string hashPath = null;
LockFileLibrary library;
if (libraryLookup.TryGetValue(export.Name, out library))
{
if (!string.IsNullOrEmpty(library.Sha512))
{
hash = "sha512-" + library.Sha512;
hashPath = _versionFolderPathResolver.GetHashFileName(export.Name, export.Version);
}
path = library.Path;
}
if (runtime)
{
return new RuntimeLibrary(
type.ToLowerInvariant(),
export.Name,
export.Version.ToString(),
hash,
CreateRuntimeAssemblyGroups(export),
CreateNativeLibraryGroups(export),
export.ResourceAssemblies.FilterPlaceHolderFiles().Select(CreateResourceAssembly),
libraryDependencies,
serviceable,
path,
hashPath);
}
else
{
IEnumerable<string> assemblies = export
.CompileTimeAssemblies
.FilterPlaceHolderFiles()
.Select(libraryAsset => libraryAsset.Path);
return new CompilationLibrary(
type.ToString().ToLowerInvariant(),
export.Name,
export.Version.ToString(),
hash,
assemblies,
libraryDependencies,
serviceable,
path,
hashPath);
}
}
private IReadOnlyList<RuntimeAssetGroup> CreateRuntimeAssemblyGroups(LockFileTargetLibrary export)
{
List<RuntimeAssetGroup> assemblyGroups = new List<RuntimeAssetGroup>();
assemblyGroups.Add(
new RuntimeAssetGroup(
string.Empty,
export.RuntimeAssemblies.FilterPlaceHolderFiles().Select(a => a.Path)));
foreach (var runtimeTargetsGroup in export.GetRuntimeTargetsGroups("runtime"))
{
assemblyGroups.Add(
new RuntimeAssetGroup(
runtimeTargetsGroup.Key,
runtimeTargetsGroup.Select(t => t.Path)));
}
return assemblyGroups;
}
private IReadOnlyList<RuntimeAssetGroup> CreateNativeLibraryGroups(LockFileTargetLibrary export)
{
List<RuntimeAssetGroup> nativeGroups = new List<RuntimeAssetGroup>();
nativeGroups.Add(
new RuntimeAssetGroup(
string.Empty,
export.NativeLibraries.FilterPlaceHolderFiles().Select(a => a.Path)));
foreach (var runtimeTargetsGroup in export.GetRuntimeTargetsGroups("native"))
{
nativeGroups.Add(
new RuntimeAssetGroup(
runtimeTargetsGroup.Key,
runtimeTargetsGroup.Select(t => t.Path)));
}
return nativeGroups;
}
private ResourceAssembly CreateResourceAssembly(LockFileItem resourceAssembly)
{
string locale;
if (!resourceAssembly.Properties.TryGetValue("locale", out locale))
{
locale = null;
}
return new ResourceAssembly(resourceAssembly.Path, locale);
}
}
}
| |
// 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.Security;
using System.Threading;
using System.Diagnostics.Contracts;
namespace System.Text
{
[Serializable]
public abstract class EncoderFallback
{
// disable csharp compiler warning #0414: field assigned unused value
#pragma warning disable 0414
internal bool bIsMicrosoftBestFitFallback = false;
#pragma warning restore 0414
private static volatile EncoderFallback replacementFallback; // Default fallback, uses no best fit & "?"
private static volatile EncoderFallback exceptionFallback;
// Private object for locking instead of locking on a public type for SQL reliability work.
private static Object s_InternalSyncObject;
private static Object InternalSyncObject
{
get
{
if (s_InternalSyncObject == null)
{
Object o = new Object();
Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null);
}
return s_InternalSyncObject;
}
}
// Get each of our generic fallbacks.
public static EncoderFallback ReplacementFallback
{
get
{
if (replacementFallback == null)
lock(InternalSyncObject)
if (replacementFallback == null)
replacementFallback = new EncoderReplacementFallback();
return replacementFallback;
}
}
public static EncoderFallback ExceptionFallback
{
get
{
if (exceptionFallback == null)
lock(InternalSyncObject)
if (exceptionFallback == null)
exceptionFallback = new EncoderExceptionFallback();
return exceptionFallback;
}
}
// Fallback
//
// Return the appropriate unicode string alternative to the character that need to fall back.
// Most implimentations will be:
// return new MyCustomEncoderFallbackBuffer(this);
public abstract EncoderFallbackBuffer CreateFallbackBuffer();
// Maximum number of characters that this instance of this fallback could return
public abstract int MaxCharCount { get; }
}
public abstract class EncoderFallbackBuffer
{
// Most implementations will probably need an implemenation-specific constructor
// Public methods that cannot be overriden that let us do our fallback thing
// These wrap the internal methods so that we can check for people doing stuff that is incorrect
public abstract bool Fallback(char charUnknown, int index);
public abstract bool Fallback(char charUnknownHigh, char charUnknownLow, int index);
// Get next character
public abstract char GetNextChar();
// Back up a character
public abstract bool MovePrevious();
// How many chars left in this fallback?
public abstract int Remaining { get; }
// Not sure if this should be public or not.
// Clear the buffer
public virtual void Reset()
{
while (GetNextChar() != (char)0);
}
// Internal items to help us figure out what we're doing as far as error messages, etc.
// These help us with our performance and messages internally
[SecurityCritical]
internal unsafe char* charStart;
[SecurityCritical]
internal unsafe char* charEnd;
internal EncoderNLS encoder;
internal bool setEncoder;
internal bool bUsedEncoder;
internal bool bFallingBack = false;
internal int iRecursionCount = 0;
private const int iMaxRecursion = 250;
// Internal Reset
// For example, what if someone fails a conversion and wants to reset one of our fallback buffers?
[System.Security.SecurityCritical] // auto-generated
internal unsafe void InternalReset()
{
charStart = null;
bFallingBack = false;
iRecursionCount = 0;
Reset();
}
// Set the above values
// This can't be part of the constructor because EncoderFallbacks would have to know how to impliment these.
[System.Security.SecurityCritical] // auto-generated
internal unsafe void InternalInitialize(char* charStart, char* charEnd, EncoderNLS encoder, bool setEncoder)
{
this.charStart = charStart;
this.charEnd = charEnd;
this.encoder = encoder;
this.setEncoder = setEncoder;
this.bUsedEncoder = false;
this.bFallingBack = false;
this.iRecursionCount = 0;
}
internal char InternalGetNextChar()
{
char ch = GetNextChar();
bFallingBack = (ch != 0);
if (ch == 0) iRecursionCount = 0;
return ch;
}
// Fallback the current character using the remaining buffer and encoder if necessary
// This can only be called by our encodings (other have to use the public fallback methods), so
// we can use our EncoderNLS here too.
// setEncoder is true if we're calling from a GetBytes method, false if we're calling from a GetByteCount
//
// Note that this could also change the contents of this.encoder, which is the same
// object that the caller is using, so the caller could mess up the encoder for us
// if they aren't careful.
[System.Security.SecurityCritical] // auto-generated
internal unsafe virtual bool InternalFallback(char ch, ref char* chars)
{
// Shouldn't have null charStart
Contract.Assert(charStart != null,
"[EncoderFallback.InternalFallbackBuffer]Fallback buffer is not initialized");
// Get our index, remember chars was preincremented to point at next char, so have to -1
int index = (int)(chars - charStart) - 1;
// See if it was a high surrogate
if (Char.IsHighSurrogate(ch))
{
// See if there's a low surrogate to go with it
if (chars >= this.charEnd)
{
// Nothing left in input buffer
// No input, return 0 if mustflush is false
if (this.encoder != null && !this.encoder.MustFlush)
{
// Done, nothing to fallback
if (this.setEncoder)
{
bUsedEncoder = true;
this.encoder.charLeftOver = ch;
}
bFallingBack = false;
return false;
}
}
else
{
// Might have a low surrogate
char cNext = *chars;
if (Char.IsLowSurrogate(cNext))
{
// If already falling back then fail
if (bFallingBack && iRecursionCount++ > iMaxRecursion)
ThrowLastCharRecursive(Char.ConvertToUtf32(ch, cNext));
// Next is a surrogate, add it as surrogate pair, and increment chars
chars++;
bFallingBack = Fallback(ch, cNext, index);
return bFallingBack;
}
// Next isn't a low surrogate, just fallback the high surrogate
}
}
// If already falling back then fail
if (bFallingBack && iRecursionCount++ > iMaxRecursion)
ThrowLastCharRecursive((int)ch);
// Fall back our char
bFallingBack = Fallback(ch, index);
return bFallingBack;
}
// private helper methods
internal void ThrowLastCharRecursive(int charRecursive)
{
// Throw it, using our complete character
throw new ArgumentException(
Environment.GetResourceString("Argument_RecursiveFallback",
charRecursive), "chars");
}
}
}
| |
/*
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.
*/
using System;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using Orleans.Streams;
using System.Runtime.CompilerServices;
using UnitTests.GrainInterfaces;
namespace UnitTests.Grains
{
internal class SampleConsumerObserver<T> : IAsyncObserver<T>
{
private readonly SampleStreaming_ConsumerGrain hostingGrain;
internal SampleConsumerObserver(SampleStreaming_ConsumerGrain hostingGrain)
{
this.hostingGrain = hostingGrain;
}
public Task OnNextAsync(T item, StreamSequenceToken token = null)
{
hostingGrain.logger.Info("OnNextAsync(item={0}, token={1})", item, token != null ? token.ToString() : "null");
hostingGrain.numConsumedItems++;
return TaskDone.Done;
}
public Task OnCompletedAsync()
{
hostingGrain.logger.Info("OnCompletedAsync()");
return TaskDone.Done;
}
public Task OnErrorAsync(Exception ex)
{
hostingGrain.logger.Info("OnErrorAsync({0})", ex);
return TaskDone.Done;
}
}
public class SampleStreaming_ProducerGrain : Grain, ISampleStreaming_ProducerGrain
{
private IAsyncStream<int> producer;
private int numProducedItems;
private IDisposable producerTimer;
internal Logger logger;
internal readonly static string RequestContextKey = "RequestContextField";
internal readonly static string RequestContextValue = "JustAString";
public override Task OnActivateAsync()
{
logger = base.GetLogger("SampleStreaming_ProducerGrain " + base.IdentityString);
logger.Info("OnActivateAsync");
numProducedItems = 0;
return TaskDone.Done;
}
public Task BecomeProducer(Guid streamId, string streamNamespace, string providerToUse)
{
logger.Info("BecomeProducer");
IStreamProvider streamProvider = base.GetStreamProvider(providerToUse);
producer = streamProvider.GetStream<int>(streamId, streamNamespace);
return TaskDone.Done;
}
public Task StartPeriodicProducing()
{
logger.Info("StartPeriodicProducing");
producerTimer = base.RegisterTimer(TimerCallback, null, TimeSpan.Zero, TimeSpan.FromMilliseconds(10));
return TaskDone.Done;
}
public Task StopPeriodicProducing()
{
logger.Info("StopPeriodicProducing");
producerTimer.Dispose();
producerTimer = null;
return TaskDone.Done;
}
public Task<int> GetNumberProduced()
{
logger.Info("GetNumberProduced {0}", numProducedItems);
return Task.FromResult(numProducedItems);
}
public Task ClearNumberProduced()
{
numProducedItems = 0;
return TaskDone.Done;
}
public Task Produce()
{
return Fire();
}
private Task TimerCallback(object state)
{
return producerTimer != null? Fire(): TaskDone.Done;
}
private Task Fire([CallerMemberName] string caller = null)
{
numProducedItems++;
logger.Info("{0} (item={1})", caller, numProducedItems);
RequestContext.Set(RequestContextKey, RequestContextValue);
return producer.OnNextAsync(numProducedItems);
}
public override Task OnDeactivateAsync()
{
logger.Info("OnDeactivateAsync");
return TaskDone.Done;
}
}
public class SampleStreaming_ConsumerGrain : Grain, ISampleStreaming_ConsumerGrain
{
private IAsyncObservable<int> consumer;
internal int numConsumedItems;
internal Logger logger;
private IAsyncObserver<int> consumerObserver;
private StreamSubscriptionHandle<int> consumerHandle;
public override Task OnActivateAsync()
{
logger = base.GetLogger("SampleStreaming_ConsumerGrain " + base.IdentityString);
logger.Info("OnActivateAsync");
numConsumedItems = 0;
consumerHandle = null;
return TaskDone.Done;
}
public async Task BecomeConsumer(Guid streamId, string streamNamespace, string providerToUse)
{
logger.Info("BecomeConsumer");
consumerObserver = new SampleConsumerObserver<int>(this);
IStreamProvider streamProvider = base.GetStreamProvider(providerToUse);
consumer = streamProvider.GetStream<int>(streamId, streamNamespace);
consumerHandle = await consumer.SubscribeAsync(consumerObserver);
}
public async Task StopConsuming()
{
logger.Info("StopConsuming");
if (consumerHandle != null)
{
await consumerHandle.UnsubscribeAsync();
consumerHandle = null;
}
}
public Task<int> GetNumberConsumed()
{
return Task.FromResult(numConsumedItems);
}
public override Task OnDeactivateAsync()
{
logger.Info("OnDeactivateAsync");
return TaskDone.Done;
}
}
public class SampleStreaming_InlineConsumerGrain : Grain, ISampleStreaming_InlineConsumerGrain
{
private IAsyncObservable<int> consumer;
internal int numConsumedItems;
internal Logger logger;
private StreamSubscriptionHandle<int> consumerHandle;
public override Task OnActivateAsync()
{
logger = base.GetLogger( "SampleStreaming_InlineConsumerGrain " + base.IdentityString );
logger.Info( "OnActivateAsync" );
numConsumedItems = 0;
consumerHandle = null;
return TaskDone.Done;
}
public async Task BecomeConsumer(Guid streamId, string streamNamespace, string providerToUse)
{
logger.Info( "BecomeConsumer" );
IStreamProvider streamProvider = base.GetStreamProvider( providerToUse );
consumer = streamProvider.GetStream<int>(streamId, streamNamespace);
consumerHandle = await consumer.SubscribeAsync( OnNextAsync, OnErrorAsync, OnCompletedAsync );
}
public async Task StopConsuming()
{
logger.Info( "StopConsuming" );
if ( consumerHandle != null )
{
await consumerHandle.UnsubscribeAsync();
//consumerHandle.Dispose();
consumerHandle = null;
}
}
public Task<int> GetNumberConsumed()
{
return Task.FromResult( numConsumedItems );
}
public Task OnNextAsync( int item, StreamSequenceToken token = null )
{
logger.Info( "OnNextAsync({0}{1})", item, token != null ? token.ToString() : "null" );
numConsumedItems++;
return TaskDone.Done;
}
public Task OnCompletedAsync()
{
logger.Info( "OnCompletedAsync()" );
return TaskDone.Done;
}
public Task OnErrorAsync( Exception ex )
{
logger.Info( "OnErrorAsync({0})", ex );
return TaskDone.Done;
}
public override Task OnDeactivateAsync()
{
logger.Info("OnDeactivateAsync");
return TaskDone.Done;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
{
public class TestHostDocument
{
private readonly ExportProvider _exportProvider;
private HostLanguageServices _languageServiceProvider;
private readonly string _initialText;
private IWpfTextView _textView;
private DocumentId _id;
private TestHostProject _project;
public ITextBuffer TextBuffer;
public ITextSnapshot InitialTextSnapshot;
private readonly string _name;
private readonly SourceCodeKind _sourceCodeKind;
private readonly string _filePath;
private readonly IReadOnlyList<string> _folders;
private readonly TextLoader _loader;
public DocumentId Id
{
get
{
return _id;
}
}
public TestHostProject Project
{
get
{
return _project;
}
}
public string Name
{
get
{
return _name;
}
}
public SourceCodeKind SourceCodeKind
{
get
{
return _sourceCodeKind;
}
}
public string FilePath
{
get
{
return _filePath;
}
}
public bool IsGenerated
{
get
{
return false;
}
}
public TextLoader Loader
{
get
{
return _loader;
}
}
public int? CursorPosition { get; }
public IList<TextSpan> SelectedSpans { get; }
public IDictionary<string, IList<TextSpan>> AnnotatedSpans { get; }
/// <summary>
/// If a file exists in ProjectA and is added to ProjectB as a link, then this returns
/// false for the document in ProjectA and true for the document in ProjectB.
/// </summary>
public bool IsLinkFile { get; internal set; }
internal TestHostDocument(
ExportProvider exportProvider,
HostLanguageServices languageServiceProvider,
ITextBuffer textBuffer,
string filePath,
int? cursorPosition,
IDictionary<string, IList<TextSpan>> spans,
SourceCodeKind sourceCodeKind = SourceCodeKind.Regular,
IReadOnlyList<string> folders = null,
bool isLinkFile = false)
{
Contract.ThrowIfNull(textBuffer);
Contract.ThrowIfNull(filePath);
_exportProvider = exportProvider;
_languageServiceProvider = languageServiceProvider;
this.TextBuffer = textBuffer;
this.InitialTextSnapshot = textBuffer.CurrentSnapshot;
_filePath = filePath;
_folders = folders;
_name = filePath;
this.CursorPosition = cursorPosition;
_sourceCodeKind = sourceCodeKind;
this.IsLinkFile = isLinkFile;
this.SelectedSpans = new List<TextSpan>();
if (spans.ContainsKey(string.Empty))
{
this.SelectedSpans = spans[string.Empty];
}
this.AnnotatedSpans = new Dictionary<string, IList<TextSpan>>();
foreach (var namedSpanList in spans.Where(s => s.Key != string.Empty))
{
this.AnnotatedSpans.Add(namedSpanList);
}
_loader = new TestDocumentLoader(this);
}
public TestHostDocument(
string text = "", string displayName = "",
SourceCodeKind sourceCodeKind = SourceCodeKind.Regular,
DocumentId id = null, string filePath = null,
IReadOnlyList<string> folders = null)
{
_exportProvider = TestExportProvider.ExportProviderWithCSharpAndVisualBasic;
_id = id;
_initialText = text;
_name = displayName;
_sourceCodeKind = sourceCodeKind;
_loader = new TestDocumentLoader(this);
_filePath = filePath;
_folders = folders;
}
internal void SetProject(TestHostProject project)
{
_project = project;
if (this.Id == null)
{
_id = DocumentId.CreateNewId(project.Id, this.Name);
}
else
{
Contract.ThrowIfFalse(project.Id == this.Id.ProjectId);
}
if (_languageServiceProvider == null)
{
_languageServiceProvider = project.LanguageServiceProvider;
}
if (this.TextBuffer == null)
{
var contentTypeService = _languageServiceProvider.GetService<IContentTypeLanguageService>();
var contentType = contentTypeService.GetDefaultContentType();
this.TextBuffer = _exportProvider.GetExportedValue<ITextBufferFactoryService>().CreateTextBuffer(_initialText, contentType);
this.InitialTextSnapshot = this.TextBuffer.CurrentSnapshot;
}
}
private class TestDocumentLoader : TextLoader
{
private readonly TestHostDocument _hostDocument;
internal TestDocumentLoader(TestHostDocument hostDocument)
{
_hostDocument = hostDocument;
}
public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
{
return Task.FromResult(TextAndVersion.Create(_hostDocument.LoadText(cancellationToken), VersionStamp.Create(), "test"));
}
}
public IContentType ContentType
{
get
{
return this.TextBuffer.ContentType;
}
}
public IWpfTextView GetTextView()
{
if (_textView == null)
{
TestWorkspace.ResetThreadAffinity();
WpfTestCase.RequireWpfFact($"Creates an IWpfTextView through {nameof(TestHostDocument)}.{nameof(GetTextView)}");
_textView = _exportProvider.GetExportedValue<ITextEditorFactoryService>().CreateTextView(this.TextBuffer);
if (this.CursorPosition.HasValue)
{
_textView.Caret.MoveTo(new SnapshotPoint(_textView.TextSnapshot, CursorPosition.Value));
}
else if (this.SelectedSpans.IsSingle())
{
var span = this.SelectedSpans.Single();
_textView.Selection.Select(new SnapshotSpan(_textView.TextSnapshot, new Span(span.Start, span.Length)), false);
}
}
return _textView;
}
public ITextBuffer GetTextBuffer()
{
return this.TextBuffer;
}
public SourceText LoadText(CancellationToken cancellationToken = default(CancellationToken))
{
var loadedBuffer = _exportProvider.GetExportedValue<ITextBufferFactoryService>().CreateTextBuffer(this.InitialTextSnapshot.GetText(), this.InitialTextSnapshot.ContentType);
return loadedBuffer.CurrentSnapshot.AsText();
}
public SourceTextContainer GetOpenTextContainer()
{
return this.GetTextBuffer().AsTextContainer();
}
public IReadOnlyList<string> Folders
{
get
{
return _folders ?? ImmutableArray.Create<string>();
}
}
internal void Update(SourceText newText)
{
var buffer = GetTextBuffer();
using (var edit = buffer.CreateEdit(EditOptions.DefaultMinimalChange, reiteratedVersionNumber: null, editTag: null))
{
var oldText = buffer.CurrentSnapshot.AsText();
var changes = newText.GetTextChanges(oldText);
foreach (var change in changes)
{
edit.Replace(change.Span.Start, change.Span.Length, change.NewText);
}
edit.Apply();
}
}
private void Update(string newText)
{
using (var edit = this.GetTextBuffer().CreateEdit(EditOptions.DefaultMinimalChange, reiteratedVersionNumber: null, editTag: null))
{
edit.Replace(new Span(0, this.GetTextBuffer().CurrentSnapshot.Length), newText);
edit.Apply();
}
}
internal void CloseTextView()
{
if (_textView != null && !_textView.IsClosed)
{
_textView.Close();
_textView = null;
}
}
public DocumentInfo ToDocumentInfo()
{
return DocumentInfo.Create(this.Id, this.Name, this.Folders, this.SourceCodeKind, loader: this.Loader, filePath: this.FilePath, isGenerated: this.IsGenerated);
}
}
}
| |
// 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.InteropServices;
using System.Security;
#if ES_BUILD_STANDALONE
using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment;
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
/// <summary>
/// TraceLogging: This is the implementation of the DataCollector
/// functionality. To enable safe access to the DataCollector from
/// untrusted code, there is one thread-local instance of this structure
/// per thread. The instance must be Enabled before any data is written to
/// it. The instance must be Finished before the data is passed to
/// EventWrite. The instance must be Disabled before the arrays referenced
/// by the pointers are freed or unpinned.
/// </summary>
[SecurityCritical]
internal unsafe struct DataCollector
{
[ThreadStatic]
internal static DataCollector ThreadInstance;
private byte* scratchEnd;
private EventSource.EventData* datasEnd;
private GCHandle* pinsEnd;
private EventSource.EventData* datasStart;
private byte* scratch;
private EventSource.EventData* datas;
private GCHandle* pins;
private byte[] buffer;
private int bufferPos;
private int bufferNesting; // We may merge many fields int a single blob. If we are doing this we increment this.
private bool writingScalars;
internal void Enable(
byte* scratch,
int scratchSize,
EventSource.EventData* datas,
int dataCount,
GCHandle* pins,
int pinCount)
{
this.datasStart = datas;
this.scratchEnd = scratch + scratchSize;
this.datasEnd = datas + dataCount;
this.pinsEnd = pins + pinCount;
this.scratch = scratch;
this.datas = datas;
this.pins = pins;
this.writingScalars = false;
}
internal void Disable()
{
this = new DataCollector();
}
/// <summary>
/// Completes the list of scalars. Finish must be called before the data
/// descriptor array is passed to EventWrite.
/// </summary>
/// <returns>
/// A pointer to the next unused data descriptor, or datasEnd if they were
/// all used. (Descriptors may be unused if a string or array was null.)
/// </returns>
internal EventSource.EventData* Finish()
{
this.ScalarsEnd();
return this.datas;
}
internal void AddScalar(void* value, int size)
{
var pb = (byte*)value;
if (this.bufferNesting == 0)
{
var scratchOld = this.scratch;
var scratchNew = scratchOld + size;
if (this.scratchEnd < scratchNew)
{
throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_AddScalarOutOfRange"));
}
this.ScalarsBegin();
this.scratch = scratchNew;
for (int i = 0; i != size; i++)
{
scratchOld[i] = pb[i];
}
}
else
{
var oldPos = this.bufferPos;
this.bufferPos = checked(this.bufferPos + size);
this.EnsureBuffer();
for (int i = 0; i != size; i++, oldPos++)
{
this.buffer[oldPos] = pb[i];
}
}
}
internal void AddBinary(string value, int size)
{
if (size > ushort.MaxValue)
{
size = ushort.MaxValue - 1;
}
if (this.bufferNesting != 0)
{
this.EnsureBuffer(size + 2);
}
this.AddScalar(&size, 2);
if (size != 0)
{
if (this.bufferNesting == 0)
{
this.ScalarsEnd();
this.PinArray(value, size);
}
else
{
var oldPos = this.bufferPos;
this.bufferPos = checked(this.bufferPos + size);
this.EnsureBuffer();
fixed (void* p = value)
{
Marshal.Copy((IntPtr)p, this.buffer, oldPos, size);
}
}
}
}
internal void AddBinary(Array value, int size)
{
this.AddArray(value, size, 1);
}
internal void AddArray(Array value, int length, int itemSize)
{
if (length > ushort.MaxValue)
{
length = ushort.MaxValue;
}
var size = length * itemSize;
if (this.bufferNesting != 0)
{
this.EnsureBuffer(size + 2);
}
this.AddScalar(&length, 2);
if (length != 0)
{
if (this.bufferNesting == 0)
{
this.ScalarsEnd();
this.PinArray(value, size);
}
else
{
var oldPos = this.bufferPos;
this.bufferPos = checked(this.bufferPos + size);
this.EnsureBuffer();
Buffer.BlockCopy(value, 0, this.buffer, oldPos, size);
}
}
}
/// <summary>
/// Marks the start of a non-blittable array or enumerable.
/// </summary>
/// <returns>Bookmark to be passed to EndBufferedArray.</returns>
internal int BeginBufferedArray()
{
this.BeginBuffered();
this.bufferPos += 2; // Reserve space for the array length (filled in by EndEnumerable)
return this.bufferPos;
}
/// <summary>
/// Marks the end of a non-blittable array or enumerable.
/// </summary>
/// <param name="bookmark">The value returned by BeginBufferedArray.</param>
/// <param name="count">The number of items in the array.</param>
internal void EndBufferedArray(int bookmark, int count)
{
this.EnsureBuffer();
this.buffer[bookmark - 2] = unchecked((byte)count);
this.buffer[bookmark - 1] = unchecked((byte)(count >> 8));
this.EndBuffered();
}
/// <summary>
/// Marks the start of dynamically-buffered data.
/// </summary>
internal void BeginBuffered()
{
this.ScalarsEnd();
this.bufferNesting += 1;
}
/// <summary>
/// Marks the end of dynamically-buffered data.
/// </summary>
internal void EndBuffered()
{
this.bufferNesting -= 1;
if (this.bufferNesting == 0)
{
/*
TODO (perf): consider coalescing adjacent buffered regions into a
single buffer, similar to what we're already doing for adjacent
scalars. In addition, if a type contains a buffered region adjacent
to a blittable array, and the blittable array is small, it would be
more efficient to buffer the array instead of pinning it.
*/
this.EnsureBuffer();
this.PinArray(this.buffer, this.bufferPos);
this.buffer = null;
this.bufferPos = 0;
}
}
private void EnsureBuffer()
{
var required = this.bufferPos;
if (this.buffer == null || this.buffer.Length < required)
{
this.GrowBuffer(required);
}
}
private void EnsureBuffer(int additionalSize)
{
var required = this.bufferPos + additionalSize;
if (this.buffer == null || this.buffer.Length < required)
{
this.GrowBuffer(required);
}
}
private void GrowBuffer(int required)
{
var newSize = this.buffer == null ? 64 : this.buffer.Length;
do
{
newSize *= 2;
}
while (newSize < required);
Array.Resize(ref this.buffer, newSize);
}
private void PinArray(object value, int size)
{
var pinsTemp = this.pins;
if (this.pinsEnd <= pinsTemp)
{
throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_PinArrayOutOfRange"));
}
var datasTemp = this.datas;
if (this.datasEnd <= datasTemp)
{
throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_DataDescriptorsOutOfRange"));
}
this.pins = pinsTemp + 1;
this.datas = datasTemp + 1;
*pinsTemp = GCHandle.Alloc(value, GCHandleType.Pinned);
datasTemp->m_Ptr = (long)(ulong)(UIntPtr)(void*)pinsTemp->AddrOfPinnedObject();
datasTemp->m_Size = size;
}
private void ScalarsBegin()
{
if (!this.writingScalars)
{
var datasTemp = this.datas;
if (this.datasEnd <= datasTemp)
{
throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_DataDescriptorsOutOfRange"));
}
datasTemp->m_Ptr = (long)(ulong)(UIntPtr)this.scratch;
this.writingScalars = true;
}
}
private void ScalarsEnd()
{
if (this.writingScalars)
{
var datasTemp = this.datas;
datasTemp->m_Size = checked((int)(this.scratch - (byte*)datasTemp->m_Ptr));
this.datas = datasTemp + 1;
this.writingScalars = 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.AzureStack.Management.Fabric.Admin
{
using Microsoft.AzureStack;
using Microsoft.AzureStack.Management;
using Microsoft.AzureStack.Management.Fabric;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// NetworkFabricOperations operations.
/// </summary>
internal partial class NetworkFabricOperations : IServiceOperations<FabricAdminClient>, INetworkFabricOperations
{
/// <summary>
/// Initializes a new instance of the NetworkFabricOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal NetworkFabricOperations(FabricAdminClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the FabricAdminClient
/// </summary>
public FabricAdminClient Client { get; private set; }
/// <summary>
/// Get the status of a network fabric operation.
/// </summary>
/// <param name='location'>
/// Location of the resource.
/// </param>
/// <param name='provider'>
/// Name of the provider.
/// </param>
/// <param name='networkOperationResult'>
/// Id of a network fabric operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<OperationStatus>> GetWithHttpMessagesAsync(string location, string provider, string networkOperationResult, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (location == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "location");
}
if (provider == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "provider");
}
if (networkOperationResult == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkOperationResult");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("location", location);
tracingParameters.Add("provider", provider);
tracingParameters.Add("networkOperationResult", networkOperationResult);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/System.{location}/providers/{provider}/fabricLocations/{location}/networkOperationResults/{networkOperationResult}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{location}", System.Uri.EscapeDataString(location));
_url = _url.Replace("{provider}", System.Uri.EscapeDataString(provider));
_url = _url.Replace("{networkOperationResult}", System.Uri.EscapeDataString(networkOperationResult));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<OperationStatus>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 202)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<OperationStatus>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Tests
{
public class FileStream_WriteAsync : FileSystemTest
{
[Fact]
public void NullBufferThrows()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
Assert.Throws<ArgumentNullException>("buffer", () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(null, 0, 1)));
}
}
[Fact]
public void NegativeOffsetThrows()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
Assert.Throws<ArgumentOutOfRangeException>("offset", () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], -1, 1)));
// buffer is checked first
Assert.Throws<ArgumentNullException>("buffer", () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(null, -1, 1)));
}
}
[Fact]
public void NegativeCountThrows()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
Assert.Throws<ArgumentOutOfRangeException>("count", () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], 0, -1)));
// offset is checked before count
Assert.Throws<ArgumentOutOfRangeException>("offset", () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], -1, -1)));
// buffer is checked first
Assert.Throws<ArgumentNullException>("buffer", () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(null, -1, -1)));
}
}
[Fact]
public void BufferOutOfBoundsThrows()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
// offset out of bounds
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], 1, 1)));
// offset out of bounds for 0 count WriteAsync
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], 2, 0)));
// offset out of bounds even for 0 length buffer
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[0], 1, 0)));
// combination offset and count out of bounds
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[2], 1, 2)));
// edges
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[0], int.MaxValue, 0)));
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[0], int.MaxValue, int.MaxValue)));
}
}
[Fact]
public void WriteAsyncDisposedThrows()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
fs.Dispose();
Assert.Throws<ObjectDisposedException>(() =>
FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], 0, 1)));
// even for noop WriteAsync
Assert.Throws<ObjectDisposedException>(() =>
FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], 0, 0)));
// out of bounds checking happens first
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[2], 1, 2)));
// count is checked prior
Assert.Throws<ArgumentOutOfRangeException>("count", () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], 0, -1)));
// offset is checked prior
Assert.Throws<ArgumentOutOfRangeException>("offset", () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], -1, -1)));
// buffer is checked first
Assert.Throws<ArgumentNullException>("buffer", () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(null, -1, -1)));
}
}
[Fact]
public void ReadOnlyThrows()
{
string fileName = GetTestFilePath();
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{ }
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
Assert.Throws<NotSupportedException>(() =>
FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], 0, 1)));
fs.Dispose();
// Disposed checking happens first
Assert.Throws<ObjectDisposedException>(() =>
FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], 0, 1)));
// out of bounds checking happens first
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[2], 1, 2)));
// count is checked prior
Assert.Throws<ArgumentOutOfRangeException>("count", () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], 0, -1)));
// offset is checked prior
Assert.Throws<ArgumentOutOfRangeException>("offset", () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], -1, -1)));
// buffer is checked first
Assert.Throws<ArgumentNullException>("buffer", () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(null, -1, -1)));
}
}
[Fact]
public void CancelledTokenFastPath()
{
CancellationTokenSource cts = new CancellationTokenSource();
cts.Cancel();
CancellationToken cancelledToken = cts.Token;
string fileName = GetTestFilePath();
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
FSAssert.IsCancelled(fs.WriteAsync(new byte[1], 0, 1, cancelledToken), cancelledToken);
}
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
// before read only check
FSAssert.IsCancelled(fs.WriteAsync(new byte[1], 0, 1, cancelledToken), cancelledToken);
fs.Dispose();
// before disposed check
FSAssert.IsCancelled(fs.WriteAsync(new byte[1], 0, 1, cancelledToken), cancelledToken);
// out of bounds checking happens first
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[2], 1, 2, cancelledToken)));
// count is checked prior
Assert.Throws<ArgumentOutOfRangeException>("count", () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], 0, -1, cancelledToken)));
// offset is checked prior
Assert.Throws<ArgumentOutOfRangeException>("offset", () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], -1, -1, cancelledToken)));
// buffer is checked first
Assert.Throws<ArgumentNullException>("buffer", () =>
FSAssert.CompletesSynchronously(fs.WriteAsync(null, -1, -1, cancelledToken)));
}
}
[Fact]
public async Task NoopWriteAsyncsSucceed()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
// note that these do not succeed synchronously even though they do nothing.
await fs.WriteAsync(new byte[0], 0, 0);
await fs.WriteAsync(new byte[1], 0, 0);
// even though offset is out of bounds of buffer, this is still allowed
// for the last element
await fs.WriteAsync(new byte[1], 1, 0);
await fs.WriteAsync(new byte[2], 1, 0);
Assert.Equal(0, fs.Length);
Assert.Equal(0, fs.Position);
}
}
[Fact]
public void WriteAsyncBufferedCompletesSynchronously()
{
using (FileStream fs = new FileStream(
GetTestFilePath(), FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete,
TestBuffer.Length * 2, useAsync: true))
{
FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[TestBuffer.Length], 0, TestBuffer.Length));
}
}
[Fact]
public async Task SimpleWriteAsync()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
await fs.WriteAsync(TestBuffer, 0, TestBuffer.Length);
Assert.Equal(TestBuffer.Length, fs.Length);
Assert.Equal(TestBuffer.Length, fs.Position);
fs.Position = 0;
byte[] buffer = new byte[TestBuffer.Length];
Assert.Equal(TestBuffer.Length, await fs.ReadAsync(buffer, 0, buffer.Length));
Assert.Equal(TestBuffer, buffer);
}
}
[Fact]
public async Task WriteAsyncCancelledFile()
{
const int writeSize = 1024 * 1024;
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
byte[] buffer = new byte[writeSize];
CancellationTokenSource cts = new CancellationTokenSource();
Task writeTask = fs.WriteAsync(buffer, 0, buffer.Length, cts.Token);
cts.Cancel();
try
{
await writeTask;
}
catch (OperationCanceledException oce)
{
// Ideally we'd be doing an Assert.Throws<OperationCanceledException>
// but since cancellation is a race condition we accept either outcome
Assert.Equal(cts.Token, oce.CancellationToken);
}
}
}
[Fact]
public async void WriteAsyncInternalBufferOverflow()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write, FileShare.None, 3, useAsync: true))
{
// Fill buffer; should trigger flush of full buffer, no additional I/O
await fs.WriteAsync(TestBuffer, 0, 3);
Assert.True(fs.Length == 3);
// Add to next buffer
await fs.WriteAsync(TestBuffer, 0, 1);
Assert.True(fs.Length == 4);
// Complete that buffer; should trigger flush of full buffer, no additional I/O
await fs.WriteAsync(TestBuffer, 0, 2);
Assert.True(fs.Length == 6);
// Add to next buffer
await fs.WriteAsync(TestBuffer, 0, 2);
Assert.True(fs.Length == 8);
// Overflow buffer with amount that could fit in a buffer; should trigger a flush, with additional I/O
await fs.WriteAsync(TestBuffer, 0, 2);
Assert.True(fs.Length == 10);
// Overflow buffer with amount that couldn't fit in a buffer; shouldn't be anything to flush, just an additional I/O
await fs.WriteAsync(TestBuffer, 0, 4);
Assert.True(fs.Length == 14);
}
}
public static IEnumerable<object[]> MemberData_FileStreamAsyncWriting()
{
foreach (bool useAsync in new[] { true, false })
{
if (useAsync && !RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// We don't have a special async I/O implementation in FileStream on Unix.
continue;
}
foreach (bool preSize in new[] { true, false })
{
foreach (bool cancelable in new[] { true, false })
{
yield return new object[] { useAsync, preSize, false, cancelable, 0x1000, 0x100, 100 };
yield return new object[] { useAsync, preSize, false, cancelable, 0x1, 0x1, 1000 };
yield return new object[] { useAsync, preSize, true, cancelable, 0x2, 0x100, 100 };
yield return new object[] { useAsync, preSize, false, cancelable, 0x4000, 0x10, 100 };
yield return new object[] { useAsync, preSize, true, cancelable, 0x1000, 99999, 10 };
}
}
}
}
[Fact]
public Task ManyConcurrentWriteAsyncs()
{
// For inner loop, just test one case
return ManyConcurrentWriteAsyncs(
useAsync: RuntimeInformation.IsOSPlatform(OSPlatform.Windows),
presize: false,
exposeHandle: false,
cancelable: true,
bufferSize: 4096,
writeSize: 1024,
numWrites: 10);
}
[Theory]
[MemberData(nameof(MemberData_FileStreamAsyncWriting))]
[OuterLoop] // many combinations: we test just one in inner loop and the rest outer
public async Task ManyConcurrentWriteAsyncs(
bool useAsync, bool presize, bool exposeHandle, bool cancelable, int bufferSize, int writeSize, int numWrites)
{
long totalLength = writeSize * numWrites;
var expectedData = new byte[totalLength];
new Random(42).NextBytes(expectedData);
CancellationToken cancellationToken = cancelable ? new CancellationTokenSource().Token : CancellationToken.None;
string path = GetTestFilePath();
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, useAsync))
{
if (presize)
{
fs.SetLength(totalLength);
}
if (exposeHandle)
{
var ignored = fs.SafeFileHandle;
}
Task[] writes = new Task[numWrites];
for (int i = 0; i < numWrites; i++)
{
writes[i] = fs.WriteAsync(expectedData, i * writeSize, writeSize, cancellationToken);
Assert.Null(writes[i].Exception);
if (useAsync)
{
Assert.Equal((i + 1) * writeSize, fs.Position);
}
}
await Task.WhenAll(writes);
}
byte[] actualData = File.ReadAllBytes(path);
Assert.Equal(expectedData.Length, actualData.Length);
if (useAsync)
{
Assert.Equal<byte>(expectedData, actualData);
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task BufferCorrectlyMaintainedWhenReadAndWrite(bool useAsync)
{
string path = GetTestFilePath();
File.WriteAllBytes(path, TestBuffer);
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None, 2, useAsync))
{
Assert.Equal(TestBuffer[0], await ReadByteAsync(fs));
Assert.Equal(TestBuffer[1], await ReadByteAsync(fs));
Assert.Equal(TestBuffer[2], await ReadByteAsync(fs));
await fs.WriteAsync(TestBuffer, 0, TestBuffer.Length);
fs.Position = 0;
Assert.Equal(TestBuffer[0], await ReadByteAsync(fs));
Assert.Equal(TestBuffer[1], await ReadByteAsync(fs));
Assert.Equal(TestBuffer[2], await ReadByteAsync(fs));
for (int i = 0; i < TestBuffer.Length; i++)
{
Assert.Equal(TestBuffer[i], await ReadByteAsync(fs));
}
}
}
private static async Task<byte> ReadByteAsync(FileStream fs)
{
byte[] oneByte = new byte[1];
Assert.Equal(1, await fs.ReadAsync(oneByte, 0, 1));
return oneByte[0];
}
[Fact, OuterLoop]
public async Task WriteAsyncMiniStress()
{
TimeSpan testRunTime = TimeSpan.FromSeconds(10);
const int MaximumWriteSize = 16 * 1024;
const int NormalWriteSize = 4 * 1024;
Random rand = new Random();
DateTime testStartTime = DateTime.UtcNow;
// Generate data to write (NOTE: Randomizing this is important as some file systems may optimize writing 0s)
byte[] dataToWrite = new byte[MaximumWriteSize];
rand.NextBytes(dataToWrite);
string writeFileName = GetTestFilePath();
do
{
// Create a new token that expires between 100-1000ms
CancellationTokenSource tokenSource = new CancellationTokenSource();
tokenSource.CancelAfter(rand.Next(100, 1000));
using (var stream = new FileStream(writeFileName, FileMode.Create, FileAccess.Write))
{
do
{
try
{
// 20%: random write size
int bytesToWrite = (rand.NextDouble() < 0.2 ? rand.Next(16, MaximumWriteSize) : NormalWriteSize);
if (rand.NextDouble() < 0.1)
{
// 10%: Sync write
stream.Write(dataToWrite, 0, bytesToWrite);
}
else
{
// 90%: Async write
await stream.WriteAsync(dataToWrite, 0, bytesToWrite, tokenSource.Token);
}
}
catch (TaskCanceledException)
{
Assert.True(tokenSource.Token.IsCancellationRequested, "Received cancellation exception before token expired");
}
} while (!tokenSource.Token.IsCancellationRequested);
}
} while (DateTime.UtcNow - testStartTime <= testRunTime);
}
}
}
| |
using AVFoundation;
using Foundation;
using Music.PCL;
using Music.PCL.Models;
using Music.PCL.Services;
using Music.SC;
using Music.SC.Models;
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using UIKit;
namespace Music.tvOS
{
public partial class PlaybackViewController : UIViewController
{
AVPlayer player;
NSTimer timer;
Song currentSong;
public PlaybackViewController (IntPtr handle) : base (handle)
{
timer = NSTimer.CreateRepeatingScheduledTimer(1, OnTimer);
}
private void OnTimer(NSTimer obj)
{
if (player != null && currentSong != null)
{
if (player.Rate == 0 && player.CurrentTime.Seconds > currentSong.Duration - 2)
{
NextSong();
}
InvokeOnMainThread(() =>
{
var progress = (float)player.CurrentTime.Seconds / (float)currentSong.Duration;
SongProgressView.Progress = progress;
CloudService.Instance.SendStatusUpdate(GetPartyStatus());
});
}
}
public override UIView PreferredFocusedView
{
get
{
return SongsView;
}
}
public async override void ViewDidLoad()
{
base.ViewDidLoad();
PlayButton.SetBackgroundImage(UIImage.FromFile("images/play.png"), UIControlState.Normal);
PlayButton.SetBackgroundImage(UIImage.FromFile("images/play_black.png"), UIControlState.Focused);
PreviousButton.SetBackgroundImage(UIImage.FromFile("images/previous.png"), UIControlState.Normal);
PreviousButton.SetBackgroundImage(UIImage.FromFile("images/previous_black.png"), UIControlState.Focused);
NextButton.SetBackgroundImage(UIImage.FromFile("images/next.png"), UIControlState.Normal);
NextButton.SetBackgroundImage(UIImage.FromFile("images/next_black.png"), UIControlState.Focused);
PlayButton.AdjustsImageWhenHighlighted = true;
PreviousButton.AdjustsImageWhenHighlighted = true;
NextButton.AdjustsImageWhenHighlighted = true;
PlayButton.AdjustsImageWhenDisabled = true;
PreviousButton.AdjustsImageWhenDisabled = true;
NextButton.AdjustsImageWhenDisabled = true;
PlayButton.Enabled = false;
PreviousButton.Enabled = false;
NextButton.Enabled = false;
PlayButton.PrimaryActionTriggered += PlayButton_PrimaryActionTriggered;
PreviousButton.PrimaryActionTriggered += PreviousButton_PrimaryActionTriggered;
NextButton.PrimaryActionTriggered += NextButton_PrimaryActionTriggered;
UIVisualEffect blurEffect = UIBlurEffect.FromStyle(UIBlurEffectStyle.Light);
UIVisualEffectView visualEffectView = new UIVisualEffectView(blurEffect);
visualEffectView.Frame = new CoreGraphics.CGRect(0, -100, 1920, 1200);
BackgroundImage.AddSubview(visualEffectView);
CloudService.Instance.Init(new User()
{
TwitterId = "fakeId",
Name = "Fake user"
});
CloudService.Instance.Connected += Instance_Connected;
DataService.Instance.Dispatcher = new DispatcherWrapper(this);
}
private void UpdateButtonViews()
{
if (player != null)
{
if (player.Rate == 0)
{
PlayButton.SetBackgroundImage(UIImage.FromFile("images/play.png"), UIControlState.Normal);
PlayButton.SetBackgroundImage(UIImage.FromFile("images/play_black.png"), UIControlState.Focused);
}
else
{
PlayButton.SetBackgroundImage(UIImage.FromFile("images/pause.png"), UIControlState.Normal);
PlayButton.SetBackgroundImage(UIImage.FromFile("images/pause_black.png"), UIControlState.Focused);
}
PlayButton.Enabled = true;
}
else
{
PlayButton.SetBackgroundImage(UIImage.FromFile("images/play.png"), UIControlState.Normal);
PlayButton.SetBackgroundImage(UIImage.FromFile("images/play_black.png"), UIControlState.Focused);
PlayButton.Enabled = false;
}
if (DataService.Instance.Playlist != null && DataService.Instance.Playlist.Count > 0 && currentSong != null)
{
var index = DataService.Instance.Playlist.IndexOf(currentSong);
if (index > -1)
{
NextButton.Enabled = index < DataService.Instance.Playlist.Count - 1;
PreviousButton.Enabled = index > 0;
return;
}
}
NextButton.Enabled = false;
PreviousButton.Enabled = false;
}
private void NextButton_PrimaryActionTriggered(object sender, EventArgs e)
{
NextSong();
}
private void NextSong()
{
if (player != null)
{
var index = DataService.Instance.Playlist.IndexOf(currentSong);
PlaySong(DataService.Instance.Playlist[index + 1]);
}
}
private void PreviousButton_PrimaryActionTriggered(object sender, EventArgs e)
{
PreviousSong();
}
private void PreviousSong()
{
if (player != null)
{
var index = DataService.Instance.Playlist.IndexOf(currentSong);
PlaySong(DataService.Instance.Playlist[index - 1]);
}
}
private void PlayButton_PrimaryActionTriggered(object sender, EventArgs e)
{
if (player != null)
{
if (player.Rate == 0)
player.Play();
else
player.Pause();
}
UpdateButtonViews();
}
private void Instance_Connected(object sender, EventArgs e)
{
InvokeOnMainThread(async () =>
{
await DataService.Instance.InitDataServiceAsHost();
DataService.Instance.Playlist.CollectionChanged += Playlist_CollectionChanged;
var source = new SongViewDataSource(DataService.Instance.Playlist);
SongsView.SongFocused += SongsView_SongFocused;
SongsView.DataSource = source;
SongsView.ReloadData();
View.SetNeedsFocusUpdate();
View.UpdateFocusIfNeeded();
PartyCodeLabel.Text = "The code is " + DataService.Instance.PartyCode;
});
}
private void Playlist_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
SongsView.ReloadData();
}
private PartyStatus GetPartyStatus()
{
var status = new PartyStatus();
if (player != null && currentSong != null)
{
status.Duration = currentSong.Duration;
status.TrackIndex = DataService.Instance.Playlist.IndexOf(currentSong);
status.State = player.Rate != 0 ? PlaybackState.Playing : PlaybackState.Paused;
status.Progress = (int)player.CurrentTime.Seconds;
}
else
{
status.State = PlaybackState.Other;
}
return status;
}
private void SongsView_SongFocused(object sender, Song e)
{
if (currentSong != e)
{
PlaySong(e);
}
}
private void PlaySong(Song song)
{
currentSong = song;
SongNameLabel.Text = song.Title;
ArtistName.Text = song.Artist;
BackgroundImage.Image = FromUrl(song.AlbumArtLarge);
BackgroundImage.Alpha = 0.6f;
BackgroundImage.ContentMode = UIViewContentMode.ScaleAspectFill;
Play(song.StreamUrl);
SongsView.CenterSong(currentSong);
UpdateButtonViews();
}
private UIImage FromUrl(string uri)
{
using (var url = new NSUrl(uri))
using (var data = NSData.FromUrl(url))
return UIImage.LoadFromData(data);
}
private void Play(string url)
{
if (player != null)
{
player.Dispose();
player = null;
}
player = AVPlayer.FromUrl(new NSUrl(url));
player.Play();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Automation
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// UsagesOperations operations.
/// </summary>
internal partial class UsagesOperations : IServiceOperations<AutomationClient>, IUsagesOperations
{
/// <summary>
/// Initializes a new instance of the UsagesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal UsagesOperations(AutomationClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutomationClient
/// </summary>
public AutomationClient Client { get; private set; }
/// <summary>
/// Retrieve the usage for the account id.
/// <see href="http://aka.ms/azureautomationsdk/usageoperations" />
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// The automation account name.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<Usage>>> ListByAutomationAccountWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (automationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-10-31";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccountName", automationAccountName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByAutomationAccount", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/usages").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<Usage>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<Usage>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
namespace MeshEngine {
public static class Mode {
public static ModeType mode;
public delegate void ModeChanged();
public static event ModeChanged OnModeChanged;
private static void Initialize() {
mode = ModeType.Vertex;
}
public static void SetMode(ModeType value) {
ModeType oldMode = mode;
mode = value;
Mesh mesh = Meshes.GetSelectedMesh();
if (!mesh) return;
//Debug.Log("oldMode=" + oldMode + ",mode=" + mode);
if (!Modes.noDelete.Contains(mode)) {
mesh.selection.ClearSelectedVertices();
mesh.vertices.DeleteVertexInstances();
mesh.triangles.DeleteTriangleInstances();
mesh.alignmentTools.SetActiveCollidersOnAlignmentTools(false);
mesh.SetRenderOptions(true, true, true);
mesh.triangles.autoCreateTriangleObjects = false;
mesh.triangles.SetTriangleInstancesSelectable(true);
}
if (mode != ModeType.SelectVerticesByTriangles) {
mesh.vertices.SetVertexInstancesSelectable(true);
}
switch (mode) {
case ModeType.AlignmentDelete:
mesh.alignmentTools.SetActiveCollidersOnAlignmentTools(true);
if (OnModeChanged != null) OnModeChanged();
return;
case ModeType.Settings:
mode = oldMode;
if (OnModeChanged != null) OnModeChanged();
return;
case ModeType.Tools:
mode = oldMode;
if (OnModeChanged != null) OnModeChanged();
return;
case ModeType.Open:
mode = oldMode;
if (OnModeChanged != null) OnModeChanged();
return;
case ModeType.SaveAs:
//meshController.keyboardPanelController.ToggleVisible();
mode = oldMode;
if (OnModeChanged != null) OnModeChanged();
return;
case ModeType.DeselectAll:
mesh.selection.Clear();
mesh.copy.Clear();
mode = oldMode;
if (OnModeChanged != null) OnModeChanged();
return;
case ModeType.Vertex:
case ModeType.Face:
case ModeType.Delete:
mesh.vertices.CreateVertexInstances();
break;
case ModeType.PrimitiveSphere:
case ModeType.PrimitiveCircle:
case ModeType.PrimitiveCylinder:
case ModeType.PrimitivePlane:
case ModeType.PrimitiveBox:
mesh.vertices.CreateVertexInstances();
mesh.triangles.autoCreateTriangleObjects = true;
mesh.SetRenderOptions(false, false, false);
mesh.triangles.SetTriangleInstancesSelectable(false);
mesh.triangles.CreateTriangleInstances();
break;
case ModeType.SelectVertices:
mesh.vertices.CreateVertexInstances(false);
mesh.triangles.SetTriangleInstancesSelectable(false);
mesh.triangles.CreateTriangleInstances();
mesh.SetRenderOptions(false, false, false);
break;
case ModeType.SelectVerticesByTriangles:
mesh.vertices.SetVertexInstancesSelectable(false);
mesh.vertices.CreateVertexInstances(false);
mesh.triangles.SetTriangleInstancesSelectable(true);
mesh.triangles.CreateTriangleInstances();
mesh.SetRenderOptions(false, false, false);
break;
case ModeType.BoxSelect:
mesh.vertices.CreateVertexInstances(false);
mesh.triangles.autoCreateTriangleObjects = true;
mesh.triangles.SetTriangleInstancesSelectable(false);
mesh.triangles.CreateTriangleInstances();
mesh.SetRenderOptions(false, false, false);
break;
case ModeType.Normal:
case ModeType.Fill:
case ModeType.TriangleDelete:
case ModeType.SelectTriangles:
case ModeType.PickColor:
mesh.SetRenderOptions(false, false, false);
mesh.triangles.CreateTriangleInstances();
break;
}
if (!Modes.noSelectionClear.Contains(mode)) {
mesh.selection.Clear();
mesh.copy.Clear();
}
if (Modes.endingInTriangleSelection.Contains(oldMode) && !Modes.noTriangleSelectionClear.Contains(mode)) {
mesh.selection.Clear();
mesh.copy.Clear();
}
if (Modes.endingInSelection.Contains(oldMode) && mode == ModeType.DeleteSelection) {
mesh.selection.DeleteSelected();
mesh.triangles.DeleteTriangleInstances(); // This shouldn't be necessary, but there is a bug somewhere
mesh.triangles.SetTriangleInstancesSelectable(false);
mesh.triangles.CreateTriangleInstances(); // ditto
mesh.SetRenderOptions(false, false, false);
mode = ModeType.SelectVertices;
}
if ((Modes.endingInSelection.Contains(oldMode) || Modes.endingInTriangleSelection.Contains(oldMode)) && mode == ModeType.FillSelection) {
mesh.selection.FillSelected();
mesh.SetRenderOptions(false, false, false);
mode = (oldMode == ModeType.SelectTriangles) ? ModeType.SelectTriangles : ModeType.SelectVertices;
}
if (Modes.endingInSelection.Contains(oldMode) && mode == ModeType.Extrude) {
mesh.extrusion.ExtrudeSelected(true);
mesh.SetRenderOptions(false, false, false);
mesh.triangles.SetTriangleInstancesSelectable(false);
mode = ModeType.SelectVertices;
}
if (oldMode == ModeType.SelectVertices && mode == ModeType.MergeVertices) {
mesh.vertices.MergeSelected();
mesh.SetRenderOptions(false, false, false);
mode = ModeType.SelectVertices;
}
if ((Modes.endingInSelection.Contains(oldMode) || Modes.endingInTriangleSelection.Contains(oldMode)) && mode == ModeType.SelectionFlipNormal) {
mesh.triangles.FlipNormalsOfSelection();
mesh.SetRenderOptions(false, false, false);
mode = (oldMode == ModeType.SelectTriangles) ? ModeType.SelectTriangles : ModeType.SelectVertices;
}
if (Modes.endingInSelection.Contains(oldMode) && mode == ModeType.Copy) {
mesh.copy.CopySelection();
mesh.SetRenderOptions(false, false, false);
mode = ModeType.SelectVertices;
}
if (Modes.endingInSelection.Contains(oldMode) && mode == ModeType.Paste) {
mesh.selection.Clear();
mesh.triangles.autoCreateTriangleObjects = true;
mesh.copy.Paste();
mesh.SetRenderOptions(false, false, false);
mode = ModeType.SelectVertices;
}
if (oldMode != ModeType.Object && mode == ModeType.Object) {
mesh.triangles.trianglesChanged = true;
mesh.EnableBoxCollider();
}
if (oldMode == ModeType.Object && mode != ModeType.Object) {
mesh.DisableBoxCollider();
}
if (OnModeChanged != null) OnModeChanged();
}
public static void UpdateMode() {
Mesh mesh = Meshes.GetSelectedMesh();
if (!mesh) return;
mesh.alignmentTools.SetActiveCollidersOnAlignmentTools(false);
if (mode == ModeType.AlignmentDelete) {
mesh.alignmentTools.SetActiveCollidersOnAlignmentTools(true);
}
switch (mode) {
case ModeType.AlignmentX:
case ModeType.AlignmentY:
case ModeType.AlignmentZ:
case ModeType.Alignment3d:
case ModeType.AlignmentDelete:
/*
if (!Settings.AlignmentToolsEnabled()) {
mode = ModeType."vertex";
}
*/
break;
}
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Xml.Serialization;
using OTFontFile;
using OTFontFileVal;
namespace FontVal
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button ClearAllTestsBtn;
private System.Windows.Forms.Button SetAllTestsBtn;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuItem3;
private System.Windows.Forms.MenuItem menuItem10;
private System.Windows.Forms.MenuItem menuItem15;
private System.Windows.Forms.MenuItem menuItem18;
private System.Windows.Forms.ToolBar toolBar1;
private System.Windows.Forms.MenuItem menuItem20;
private System.Windows.Forms.MenuItem menuItem32;
private System.Windows.Forms.MenuItem menuItem33;
private System.Windows.Forms.ImageList imageList1;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.ListBox listBoxFont;
private System.Windows.Forms.Button btnAddFont;
private System.Windows.Forms.Button btnRemoveFont;
private System.Windows.Forms.CheckedListBox checkedListBoxTests;
private System.Windows.Forms.ToolBarButton tbBtnNewProj;
private System.Windows.Forms.ToolBarButton tbBtnOpenProj;
private System.Windows.Forms.ToolBarButton tbBtnSaveProj;
private System.Windows.Forms.ToolBarButton sep1;
private System.Windows.Forms.ToolBarButton tbBtnOpenReport;
private System.Windows.Forms.ToolBarButton tbBtnPrintReport;
private System.Windows.Forms.ToolBarButton sep2;
private System.Windows.Forms.ToolBarButton tbBtnValidate;
private System.Windows.Forms.MenuItem menuItemFileExit;
private System.Windows.Forms.MenuItem menuItemNewProj;
private System.Windows.Forms.MenuItem menuItemOpenProj;
private System.Windows.Forms.MenuItem menuItemOpenReport;
private System.Windows.Forms.MenuItem menuItemCloseReport;
private System.Windows.Forms.MenuItem menuItemSaveProj;
private System.Windows.Forms.MenuItem menuItemSaveProjAs;
private System.Windows.Forms.MenuItem menuItemSaveReportAs;
private System.Windows.Forms.MenuItem menuItemPrint;
private System.Windows.Forms.MenuItem menuItemRecentProj;
private System.Windows.Forms.MenuItem menuItemRecentReports;
private System.Windows.Forms.MenuItem menuItemEditCopy;
private System.Windows.Forms.MenuItem menuItemEditSelectAll;
private System.Windows.Forms.MenuItem menuItemHelpHelp;
private System.Windows.Forms.MenuItem menuItemHelpAbout;
private System.Windows.Forms.MenuItem menuItem2;
private System.Windows.Forms.MenuItem menuItemVal;
private System.Windows.Forms.MenuItem menuItemValRun;
private System.ComponentModel.IContainer components;
private System.Windows.Forms.Splitter splitter1;
private System.Windows.Forms.MenuItem menuItemMRUProject1;
private System.Windows.Forms.MenuItem menuItemMRUProject2;
private System.Windows.Forms.MenuItem menuItemMRUProject3;
private System.Windows.Forms.MenuItem menuItemMRUProject4;
project m_project;
Validator m_Validator;
Progress m_formProgress;
RastTestTransform m_RastTestTransform;
PersistedData m_PersistedData;
private System.Windows.Forms.MenuItem menuItemMRUReport1;
private System.Windows.Forms.MenuItem menuItemMRUReport2;
private System.Windows.Forms.MenuItem menuItemMRUReport3;
private System.Windows.Forms.MenuItem menuItemMRUReport4;
private System.Windows.Forms.MenuItem menuItemWinCascade;
private System.Windows.Forms.MenuItem menuItemWinTileHorz;
private System.Windows.Forms.MenuItem menuItemWinTileVert;
private System.Windows.Forms.MenuItem menuItemWinCloseAll;
private System.Windows.Forms.MenuItem menuItem6;
private System.Windows.Forms.MenuItem menuItemValAddFont;
private System.Windows.Forms.TabPage tabPage3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.CheckBox checkBoxRast;
private System.Windows.Forms.Button btnTransform;
private System.Windows.Forms.TextBox textBoxPointSizes;
private System.Windows.Forms.Label labelPointsizes;
private System.Windows.Forms.TextBox textBoxXRes;
private System.Windows.Forms.TextBox textBoxYRes;
private System.Windows.Forms.MenuItem menuItem5;
private System.Windows.Forms.MenuItem menuReportOptions;
private System.Windows.Forms.CheckBox checkBoxBW;
private System.Windows.Forms.CheckBox checkBoxGray;
private System.Windows.Forms.CheckBox checkBoxClearType;
private System.Windows.Forms.CheckBox checkBoxCTCompWidth;
private System.Windows.Forms.CheckBox checkBoxCTVert;
private System.Windows.Forms.CheckBox checkBoxCTBGR;
private System.Windows.Forms.CheckBox checkBoxCTFractWidth;
private System.Windows.Forms.GroupBox groupBoxCTFlags;
private System.Windows.Forms.GroupBox groupBoxResolution;
private System.Windows.Forms.MenuItem menuItemValRemoveFont;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
m_Validator = new Validator();
string [] sTableTypes = TableManager.GetKnownOTTableTypes();
for (int i=0; i<sTableTypes.Length; i++)
{
checkedListBoxTests.Items.Add(sTableTypes[i], System.Windows.Forms.CheckState.Checked);
}
groupBoxCTFlags.Enabled = checkBoxClearType.Checked;
m_project = new project();
m_RastTestTransform = new RastTestTransform();
m_PersistedData = new PersistedData();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1));
this.ClearAllTestsBtn = new System.Windows.Forms.Button();
this.SetAllTestsBtn = new System.Windows.Forms.Button();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.btnRemoveFont = new System.Windows.Forms.Button();
this.btnAddFont = new System.Windows.Forms.Button();
this.listBoxFont = new System.Windows.Forms.ListBox();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.checkedListBoxTests = new System.Windows.Forms.CheckedListBox();
this.tabPage3 = new System.Windows.Forms.TabPage();
this.groupBoxResolution = new System.Windows.Forms.GroupBox();
this.label2 = new System.Windows.Forms.Label();
this.textBoxYRes = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.textBoxXRes = new System.Windows.Forms.TextBox();
this.groupBoxCTFlags = new System.Windows.Forms.GroupBox();
this.checkBoxCTFractWidth = new System.Windows.Forms.CheckBox();
this.checkBoxCTBGR = new System.Windows.Forms.CheckBox();
this.checkBoxCTVert = new System.Windows.Forms.CheckBox();
this.checkBoxCTCompWidth = new System.Windows.Forms.CheckBox();
this.checkBoxClearType = new System.Windows.Forms.CheckBox();
this.checkBoxGray = new System.Windows.Forms.CheckBox();
this.checkBoxBW = new System.Windows.Forms.CheckBox();
this.labelPointsizes = new System.Windows.Forms.Label();
this.textBoxPointSizes = new System.Windows.Forms.TextBox();
this.checkBoxRast = new System.Windows.Forms.CheckBox();
this.btnTransform = new System.Windows.Forms.Button();
this.mainMenu1 = new System.Windows.Forms.MainMenu();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuItemNewProj = new System.Windows.Forms.MenuItem();
this.menuItem3 = new System.Windows.Forms.MenuItem();
this.menuItemOpenProj = new System.Windows.Forms.MenuItem();
this.menuItemOpenReport = new System.Windows.Forms.MenuItem();
this.menuItemCloseReport = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.menuItemSaveProj = new System.Windows.Forms.MenuItem();
this.menuItemSaveProjAs = new System.Windows.Forms.MenuItem();
this.menuItemSaveReportAs = new System.Windows.Forms.MenuItem();
this.menuItem10 = new System.Windows.Forms.MenuItem();
this.menuItemPrint = new System.Windows.Forms.MenuItem();
this.menuItem15 = new System.Windows.Forms.MenuItem();
this.menuItemRecentProj = new System.Windows.Forms.MenuItem();
this.menuItemMRUProject1 = new System.Windows.Forms.MenuItem();
this.menuItemMRUProject2 = new System.Windows.Forms.MenuItem();
this.menuItemMRUProject3 = new System.Windows.Forms.MenuItem();
this.menuItemMRUProject4 = new System.Windows.Forms.MenuItem();
this.menuItemRecentReports = new System.Windows.Forms.MenuItem();
this.menuItemMRUReport1 = new System.Windows.Forms.MenuItem();
this.menuItemMRUReport2 = new System.Windows.Forms.MenuItem();
this.menuItemMRUReport3 = new System.Windows.Forms.MenuItem();
this.menuItemMRUReport4 = new System.Windows.Forms.MenuItem();
this.menuItem18 = new System.Windows.Forms.MenuItem();
this.menuItemFileExit = new System.Windows.Forms.MenuItem();
this.menuItem20 = new System.Windows.Forms.MenuItem();
this.menuItemEditCopy = new System.Windows.Forms.MenuItem();
this.menuItemEditSelectAll = new System.Windows.Forms.MenuItem();
this.menuItemVal = new System.Windows.Forms.MenuItem();
this.menuItemValAddFont = new System.Windows.Forms.MenuItem();
this.menuItemValRemoveFont = new System.Windows.Forms.MenuItem();
this.menuItem6 = new System.Windows.Forms.MenuItem();
this.menuReportOptions = new System.Windows.Forms.MenuItem();
this.menuItem5 = new System.Windows.Forms.MenuItem();
this.menuItemValRun = new System.Windows.Forms.MenuItem();
this.menuItem32 = new System.Windows.Forms.MenuItem();
this.menuItemWinCascade = new System.Windows.Forms.MenuItem();
this.menuItemWinTileHorz = new System.Windows.Forms.MenuItem();
this.menuItemWinTileVert = new System.Windows.Forms.MenuItem();
this.menuItemWinCloseAll = new System.Windows.Forms.MenuItem();
this.menuItem33 = new System.Windows.Forms.MenuItem();
this.menuItemHelpHelp = new System.Windows.Forms.MenuItem();
this.menuItemHelpAbout = new System.Windows.Forms.MenuItem();
this.toolBar1 = new System.Windows.Forms.ToolBar();
this.tbBtnNewProj = new System.Windows.Forms.ToolBarButton();
this.tbBtnOpenProj = new System.Windows.Forms.ToolBarButton();
this.tbBtnSaveProj = new System.Windows.Forms.ToolBarButton();
this.sep1 = new System.Windows.Forms.ToolBarButton();
this.tbBtnOpenReport = new System.Windows.Forms.ToolBarButton();
this.tbBtnPrintReport = new System.Windows.Forms.ToolBarButton();
this.sep2 = new System.Windows.Forms.ToolBarButton();
this.tbBtnValidate = new System.Windows.Forms.ToolBarButton();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.panel1 = new System.Windows.Forms.Panel();
this.splitter1 = new System.Windows.Forms.Splitter();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
this.tabPage2.SuspendLayout();
this.tabPage3.SuspendLayout();
this.groupBoxResolution.SuspendLayout();
this.groupBoxCTFlags.SuspendLayout();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// ClearAllTestsBtn
//
this.ClearAllTestsBtn.Location = new System.Drawing.Point(112, 9);
this.ClearAllTestsBtn.Name = "ClearAllTestsBtn";
this.ClearAllTestsBtn.Size = new System.Drawing.Size(80, 24);
this.ClearAllTestsBtn.TabIndex = 4;
this.ClearAllTestsBtn.Text = "Clear All";
this.ClearAllTestsBtn.Click += new System.EventHandler(this.ClearAllTestsBtn_Click);
//
// SetAllTestsBtn
//
this.SetAllTestsBtn.Location = new System.Drawing.Point(8, 9);
this.SetAllTestsBtn.Name = "SetAllTestsBtn";
this.SetAllTestsBtn.Size = new System.Drawing.Size(80, 24);
this.SetAllTestsBtn.TabIndex = 3;
this.SetAllTestsBtn.Text = "Set All";
this.SetAllTestsBtn.Click += new System.EventHandler(this.SetAllTestsBtn_Click);
//
// tabControl1
//
this.tabControl1.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.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Controls.Add(this.tabPage3);
this.tabControl1.Location = new System.Drawing.Point(0, 9);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(208, 492);
this.tabControl1.TabIndex = 0;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.btnRemoveFont);
this.tabPage1.Controls.Add(this.btnAddFont);
this.tabPage1.Controls.Add(this.listBoxFont);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Size = new System.Drawing.Size(200, 362);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Font Files";
//
// btnRemoveFont
//
this.btnRemoveFont.Location = new System.Drawing.Point(112, 8);
this.btnRemoveFont.Name = "btnRemoveFont";
this.btnRemoveFont.Size = new System.Drawing.Size(80, 24);
this.btnRemoveFont.TabIndex = 5;
this.btnRemoveFont.Text = "Remove";
this.btnRemoveFont.Click += new System.EventHandler(this.btnRemoveFont_Click);
//
// btnAddFont
//
this.btnAddFont.Location = new System.Drawing.Point(8, 8);
this.btnAddFont.Name = "btnAddFont";
this.btnAddFont.Size = new System.Drawing.Size(80, 24);
this.btnAddFont.TabIndex = 4;
this.btnAddFont.Text = "Add...";
this.btnAddFont.Click += new System.EventHandler(this.btnAddFont_Click);
//
// listBoxFont
//
this.listBoxFont.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.listBoxFont.HorizontalScrollbar = true;
this.listBoxFont.Location = new System.Drawing.Point(9, 45);
this.listBoxFont.Name = "listBoxFont";
this.listBoxFont.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
this.listBoxFont.Size = new System.Drawing.Size(183, 290);
this.listBoxFont.TabIndex = 3;
this.listBoxFont.KeyDown += new System.Windows.Forms.KeyEventHandler(this.listBoxFont_KeyDown);
this.listBoxFont.SelectedIndexChanged += new System.EventHandler(this.listBoxFont_SelectedIndexChanged);
//
// tabPage2
//
this.tabPage2.Controls.Add(this.checkedListBoxTests);
this.tabPage2.Controls.Add(this.SetAllTestsBtn);
this.tabPage2.Controls.Add(this.ClearAllTestsBtn);
this.tabPage2.Location = new System.Drawing.Point(4, 22);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Size = new System.Drawing.Size(200, 348);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "Table Tests";
//
// checkedListBoxTests
//
this.checkedListBoxTests.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.checkedListBoxTests.CheckOnClick = true;
this.checkedListBoxTests.Location = new System.Drawing.Point(9, 45);
this.checkedListBoxTests.Name = "checkedListBoxTests";
this.checkedListBoxTests.Size = new System.Drawing.Size(183, 287);
this.checkedListBoxTests.TabIndex = 5;
//
// tabPage3
//
this.tabPage3.Controls.Add(this.groupBoxResolution);
this.tabPage3.Controls.Add(this.groupBoxCTFlags);
this.tabPage3.Controls.Add(this.checkBoxClearType);
this.tabPage3.Controls.Add(this.checkBoxGray);
this.tabPage3.Controls.Add(this.checkBoxBW);
this.tabPage3.Controls.Add(this.labelPointsizes);
this.tabPage3.Controls.Add(this.textBoxPointSizes);
this.tabPage3.Controls.Add(this.checkBoxRast);
this.tabPage3.Controls.Add(this.btnTransform);
this.tabPage3.Location = new System.Drawing.Point(4, 22);
this.tabPage3.Name = "tabPage3";
this.tabPage3.Size = new System.Drawing.Size(200, 466);
this.tabPage3.TabIndex = 2;
this.tabPage3.Text = "Rasterization";
//
// groupBoxResolution
//
this.groupBoxResolution.Controls.Add(this.label2);
this.groupBoxResolution.Controls.Add(this.textBoxYRes);
this.groupBoxResolution.Controls.Add(this.label3);
this.groupBoxResolution.Controls.Add(this.textBoxXRes);
this.groupBoxResolution.Location = new System.Drawing.Point(8, 240);
this.groupBoxResolution.Name = "groupBoxResolution";
this.groupBoxResolution.Size = new System.Drawing.Size(184, 48);
this.groupBoxResolution.TabIndex = 20;
this.groupBoxResolution.TabStop = false;
this.groupBoxResolution.Text = "Resolution";
//
// label2
//
this.label2.Location = new System.Drawing.Point(8, 16);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(24, 23);
this.label2.TabIndex = 1;
this.label2.Text = "X";
//
// textBoxYRes
//
this.textBoxYRes.Location = new System.Drawing.Point(128, 16);
this.textBoxYRes.Name = "textBoxYRes";
this.textBoxYRes.Size = new System.Drawing.Size(48, 20);
this.textBoxYRes.TabIndex = 8;
this.textBoxYRes.Text = "96";
//
// label3
//
this.label3.Location = new System.Drawing.Point(96, 16);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(24, 23);
this.label3.TabIndex = 2;
this.label3.Text = "Y";
//
// textBoxXRes
//
this.textBoxXRes.Location = new System.Drawing.Point(40, 16);
this.textBoxXRes.Name = "textBoxXRes";
this.textBoxXRes.Size = new System.Drawing.Size(48, 20);
this.textBoxXRes.TabIndex = 7;
this.textBoxXRes.Text = "96";
//
// groupBoxCTFlags
//
this.groupBoxCTFlags.Controls.Add(this.checkBoxCTFractWidth);
this.groupBoxCTFlags.Controls.Add(this.checkBoxCTBGR);
this.groupBoxCTFlags.Controls.Add(this.checkBoxCTVert);
this.groupBoxCTFlags.Controls.Add(this.checkBoxCTCompWidth);
this.groupBoxCTFlags.Location = new System.Drawing.Point(40, 120);
this.groupBoxCTFlags.Name = "groupBoxCTFlags";
this.groupBoxCTFlags.Size = new System.Drawing.Size(152, 112);
this.groupBoxCTFlags.TabIndex = 19;
this.groupBoxCTFlags.TabStop = false;
this.groupBoxCTFlags.Text = "ClearType flags";
//
// checkBoxCTFractWidth
//
this.checkBoxCTFractWidth.Enabled = false;
this.checkBoxCTFractWidth.Location = new System.Drawing.Point(16, 88);
this.checkBoxCTFractWidth.Name = "checkBoxCTFractWidth";
this.checkBoxCTFractWidth.Size = new System.Drawing.Size(120, 16);
this.checkBoxCTFractWidth.TabIndex = 3;
this.checkBoxCTFractWidth.Text = "Fractional Width";
//
// checkBoxCTBGR
//
this.checkBoxCTBGR.Checked = true;
this.checkBoxCTBGR.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBoxCTBGR.Location = new System.Drawing.Point(16, 64);
this.checkBoxCTBGR.Name = "checkBoxCTBGR";
this.checkBoxCTBGR.Size = new System.Drawing.Size(120, 16);
this.checkBoxCTBGR.TabIndex = 2;
this.checkBoxCTBGR.Text = "BGR";
//
// checkBoxCTVert
//
this.checkBoxCTVert.Checked = true;
this.checkBoxCTVert.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBoxCTVert.Location = new System.Drawing.Point(16, 40);
this.checkBoxCTVert.Name = "checkBoxCTVert";
this.checkBoxCTVert.Size = new System.Drawing.Size(120, 16);
this.checkBoxCTVert.TabIndex = 1;
this.checkBoxCTVert.Text = "Vertical";
//
// checkBoxCTCompWidth
//
this.checkBoxCTCompWidth.Checked = true;
this.checkBoxCTCompWidth.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBoxCTCompWidth.Location = new System.Drawing.Point(16, 16);
this.checkBoxCTCompWidth.Name = "checkBoxCTCompWidth";
this.checkBoxCTCompWidth.Size = new System.Drawing.Size(120, 16);
this.checkBoxCTCompWidth.TabIndex = 0;
this.checkBoxCTCompWidth.Text = "Compatible Width";
//
// checkBoxClearType
//
this.checkBoxClearType.Checked = true;
this.checkBoxClearType.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBoxClearType.Location = new System.Drawing.Point(24, 96);
this.checkBoxClearType.Name = "checkBoxClearType";
this.checkBoxClearType.Size = new System.Drawing.Size(104, 16);
this.checkBoxClearType.TabIndex = 18;
this.checkBoxClearType.Text = "ClearType";
this.checkBoxClearType.CheckedChanged += new System.EventHandler(this.checkBoxClearType_CheckedChanged);
//
// checkBoxGray
//
this.checkBoxGray.Checked = true;
this.checkBoxGray.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBoxGray.Location = new System.Drawing.Point(24, 72);
this.checkBoxGray.Name = "checkBoxGray";
this.checkBoxGray.Size = new System.Drawing.Size(104, 16);
this.checkBoxGray.TabIndex = 17;
this.checkBoxGray.Text = "Grayscale";
//
// checkBoxBW
//
this.checkBoxBW.Checked = true;
this.checkBoxBW.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBoxBW.Location = new System.Drawing.Point(24, 48);
this.checkBoxBW.Name = "checkBoxBW";
this.checkBoxBW.Size = new System.Drawing.Size(104, 16);
this.checkBoxBW.TabIndex = 16;
this.checkBoxBW.Text = "BW";
//
// labelPointsizes
//
this.labelPointsizes.Location = new System.Drawing.Point(16, 296);
this.labelPointsizes.Name = "labelPointsizes";
this.labelPointsizes.Size = new System.Drawing.Size(72, 16);
this.labelPointsizes.TabIndex = 15;
this.labelPointsizes.Text = "Point size(s)";
//
// textBoxPointSizes
//
this.textBoxPointSizes.Location = new System.Drawing.Point(16, 320);
this.textBoxPointSizes.Name = "textBoxPointSizes";
this.textBoxPointSizes.Size = new System.Drawing.Size(168, 20);
this.textBoxPointSizes.TabIndex = 14;
this.textBoxPointSizes.Text = "4-72, 80, 88, 96, 102, 110, 118, 126";
//
// checkBoxRast
//
this.checkBoxRast.Checked = true;
this.checkBoxRast.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBoxRast.Location = new System.Drawing.Point(8, 8);
this.checkBoxRast.Name = "checkBoxRast";
this.checkBoxRast.Size = new System.Drawing.Size(176, 40);
this.checkBoxRast.TabIndex = 6;
this.checkBoxRast.Text = "Test rasterization of TrueType outlines";
this.checkBoxRast.CheckedChanged += new System.EventHandler(this.checkBoxRast_CheckedChanged);
//
// btnTransform
//
this.btnTransform.Location = new System.Drawing.Point(64, 352);
this.btnTransform.Name = "btnTransform";
this.btnTransform.Size = new System.Drawing.Size(80, 23);
this.btnTransform.TabIndex = 1;
this.btnTransform.Text = "Transform...";
this.btnTransform.Click += new System.EventHandler(this.btnTransform_Click);
//
// mainMenu1
//
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem1,
this.menuItem20,
this.menuItemVal,
this.menuItem32,
this.menuItem33});
//
// menuItem1
//
this.menuItem1.Index = 0;
this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemNewProj,
this.menuItem3,
this.menuItemCloseReport,
this.menuItem2,
this.menuItemSaveProj,
this.menuItemSaveProjAs,
this.menuItemSaveReportAs,
this.menuItem10,
this.menuItemPrint,
this.menuItem15,
this.menuItemRecentProj,
this.menuItemRecentReports,
this.menuItem18,
this.menuItemFileExit});
this.menuItem1.Text = "&File";
//
// menuItemNewProj
//
this.menuItemNewProj.Index = 0;
this.menuItemNewProj.Shortcut = System.Windows.Forms.Shortcut.CtrlN;
this.menuItemNewProj.Text = "&New Project";
this.menuItemNewProj.Click += new System.EventHandler(this.menuItemNewProj_Click);
//
// menuItem3
//
this.menuItem3.Index = 1;
this.menuItem3.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemOpenProj,
this.menuItemOpenReport});
this.menuItem3.Shortcut = System.Windows.Forms.Shortcut.CtrlO;
this.menuItem3.Text = "Open";
//
// menuItemOpenProj
//
this.menuItemOpenProj.Index = 0;
this.menuItemOpenProj.Text = "&Project...";
this.menuItemOpenProj.Click += new System.EventHandler(this.menuItemOpenProj_Click);
//
// menuItemOpenReport
//
this.menuItemOpenReport.Index = 1;
this.menuItemOpenReport.Text = "&Report...";
this.menuItemOpenReport.Click += new System.EventHandler(this.menuItemOpenReport_Click);
//
// menuItemCloseReport
//
this.menuItemCloseReport.Index = 2;
this.menuItemCloseReport.Text = "&Close Report";
this.menuItemCloseReport.Click += new System.EventHandler(this.menuItemCloseReport_Click);
//
// menuItem2
//
this.menuItem2.Index = 3;
this.menuItem2.Text = "-";
//
// menuItemSaveProj
//
this.menuItemSaveProj.Index = 4;
this.menuItemSaveProj.Shortcut = System.Windows.Forms.Shortcut.CtrlS;
this.menuItemSaveProj.Text = "&Save Project";
this.menuItemSaveProj.Click += new System.EventHandler(this.menuItemSaveProj_Click);
//
// menuItemSaveProjAs
//
this.menuItemSaveProjAs.Index = 5;
this.menuItemSaveProjAs.Text = "Save Project &As ...";
this.menuItemSaveProjAs.Click += new System.EventHandler(this.menuItemSaveProjAs_Click);
//
// menuItemSaveReportAs
//
this.menuItemSaveReportAs.Index = 6;
this.menuItemSaveReportAs.Text = "Save Report &As ...";
this.menuItemSaveReportAs.Click += new System.EventHandler(this.menuItemSaveReportAs_Click);
//
// menuItem10
//
this.menuItem10.Index = 7;
this.menuItem10.Text = "-";
//
// menuItemPrint
//
this.menuItemPrint.Index = 8;
this.menuItemPrint.Shortcut = System.Windows.Forms.Shortcut.CtrlP;
this.menuItemPrint.Text = "&Print...";
this.menuItemPrint.Click += new System.EventHandler(this.menuItemPrint_Click);
//
// menuItem15
//
this.menuItem15.Index = 9;
this.menuItem15.Text = "-";
//
// menuItemRecentProj
//
this.menuItemRecentProj.Index = 10;
this.menuItemRecentProj.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemMRUProject1,
this.menuItemMRUProject2,
this.menuItemMRUProject3,
this.menuItemMRUProject4});
this.menuItemRecentProj.Text = "Recent Pro&jects";
//
// menuItemMRUProject1
//
this.menuItemMRUProject1.Index = 0;
this.menuItemMRUProject1.Text = "";
this.menuItemMRUProject1.Click += new System.EventHandler(this.menuItemMRUProject1_Click);
//
// menuItemMRUProject2
//
this.menuItemMRUProject2.Index = 1;
this.menuItemMRUProject2.Text = "";
this.menuItemMRUProject2.Click += new System.EventHandler(this.menuItemMRUProject2_Click);
//
// menuItemMRUProject3
//
this.menuItemMRUProject3.Index = 2;
this.menuItemMRUProject3.Text = "";
this.menuItemMRUProject3.Click += new System.EventHandler(this.menuItemMRUProject3_Click);
//
// menuItemMRUProject4
//
this.menuItemMRUProject4.Index = 3;
this.menuItemMRUProject4.Text = "";
this.menuItemMRUProject4.Click += new System.EventHandler(this.menuItemMRUProject4_Click);
//
// menuItemRecentReports
//
this.menuItemRecentReports.Index = 11;
this.menuItemRecentReports.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemMRUReport1,
this.menuItemMRUReport2,
this.menuItemMRUReport3,
this.menuItemMRUReport4});
this.menuItemRecentReports.Text = "Recen&t Reports";
//
// menuItemMRUReport1
//
this.menuItemMRUReport1.Index = 0;
this.menuItemMRUReport1.Text = "r1";
this.menuItemMRUReport1.Click += new System.EventHandler(this.menuItemMRUReport1_Click);
//
// menuItemMRUReport2
//
this.menuItemMRUReport2.Index = 1;
this.menuItemMRUReport2.Text = "r2";
this.menuItemMRUReport2.Click += new System.EventHandler(this.menuItemMRUReport2_Click);
//
// menuItemMRUReport3
//
this.menuItemMRUReport3.Index = 2;
this.menuItemMRUReport3.Text = "r3";
this.menuItemMRUReport3.Click += new System.EventHandler(this.menuItemMRUReport3_Click);
//
// menuItemMRUReport4
//
this.menuItemMRUReport4.Index = 3;
this.menuItemMRUReport4.Text = "r4";
this.menuItemMRUReport4.Click += new System.EventHandler(this.menuItemMRUReport4_Click);
//
// menuItem18
//
this.menuItem18.Index = 12;
this.menuItem18.Text = "-";
//
// menuItemFileExit
//
this.menuItemFileExit.Index = 13;
this.menuItemFileExit.Text = "E&xit";
this.menuItemFileExit.Click += new System.EventHandler(this.menuItemFileExit_Click);
//
// menuItem20
//
this.menuItem20.Index = 1;
this.menuItem20.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemEditCopy,
this.menuItemEditSelectAll});
this.menuItem20.Text = "&Edit";
//
// menuItemEditCopy
//
this.menuItemEditCopy.Index = 0;
this.menuItemEditCopy.Shortcut = System.Windows.Forms.Shortcut.CtrlC;
this.menuItemEditCopy.Text = "&Copy";
this.menuItemEditCopy.Click += new System.EventHandler(this.menuItemEditCopy_Click);
//
// menuItemEditSelectAll
//
this.menuItemEditSelectAll.Index = 1;
this.menuItemEditSelectAll.Shortcut = System.Windows.Forms.Shortcut.CtrlA;
this.menuItemEditSelectAll.Text = "SelectA&ll";
this.menuItemEditSelectAll.Click += new System.EventHandler(this.menuItemEditSelectAll_Click);
//
// menuItemVal
//
this.menuItemVal.Index = 2;
this.menuItemVal.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemValAddFont,
this.menuItemValRemoveFont,
this.menuItem6,
this.menuReportOptions,
this.menuItem5,
this.menuItemValRun});
this.menuItemVal.Text = "&Validation";
//
// menuItemValAddFont
//
this.menuItemValAddFont.Index = 0;
this.menuItemValAddFont.Text = "&Add Font...";
this.menuItemValAddFont.Click += new System.EventHandler(this.menuItemValAddFont_Click);
//
// menuItemValRemoveFont
//
this.menuItemValRemoveFont.Index = 1;
this.menuItemValRemoveFont.Text = "&Remove Font";
this.menuItemValRemoveFont.Click += new System.EventHandler(this.menuItemValRemoveFont_Click);
//
// menuItem6
//
this.menuItem6.Index = 2;
this.menuItem6.Text = "-";
//
// menuReportOptions
//
this.menuReportOptions.Index = 3;
this.menuReportOptions.Text = "Report &Options...";
this.menuReportOptions.Click += new System.EventHandler(this.menuReportOptions_Click);
//
// menuItem5
//
this.menuItem5.Index = 4;
this.menuItem5.Text = "-";
//
// menuItemValRun
//
this.menuItemValRun.Index = 5;
this.menuItemValRun.Text = "&Start";
this.menuItemValRun.Click += new System.EventHandler(this.menuItemValRun_Click);
//
// menuItem32
//
this.menuItem32.Index = 3;
this.menuItem32.MdiList = true;
this.menuItem32.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemWinCascade,
this.menuItemWinTileHorz,
this.menuItemWinTileVert,
this.menuItemWinCloseAll});
this.menuItem32.Text = "&Window";
//
// menuItemWinCascade
//
this.menuItemWinCascade.Index = 0;
this.menuItemWinCascade.Text = "&Cascade";
this.menuItemWinCascade.Click += new System.EventHandler(this.menuItemWinCascade_Click);
//
// menuItemWinTileHorz
//
this.menuItemWinTileHorz.Index = 1;
this.menuItemWinTileHorz.Text = "Tile &Horizontally";
this.menuItemWinTileHorz.Click += new System.EventHandler(this.menuItemWinTileHorz_Click);
//
// menuItemWinTileVert
//
this.menuItemWinTileVert.Index = 2;
this.menuItemWinTileVert.Text = "Tile &Vertically";
this.menuItemWinTileVert.Click += new System.EventHandler(this.menuItemWinTileVert_Click);
//
// menuItemWinCloseAll
//
this.menuItemWinCloseAll.Index = 3;
this.menuItemWinCloseAll.Text = "Close &All";
this.menuItemWinCloseAll.Click += new System.EventHandler(this.menuItemWinCloseAll_Click);
//
// menuItem33
//
this.menuItem33.Index = 4;
this.menuItem33.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemHelpHelp,
this.menuItemHelpAbout});
this.menuItem33.Text = "&Help";
//
// menuItemHelpHelp
//
this.menuItemHelpHelp.Index = 0;
this.menuItemHelpHelp.Shortcut = System.Windows.Forms.Shortcut.F1;
this.menuItemHelpHelp.Text = "Font Validator &Help...";
this.menuItemHelpHelp.Click += new System.EventHandler(this.menuItemHelpHelp_Click);
//
// menuItemHelpAbout
//
this.menuItemHelpAbout.Index = 1;
this.menuItemHelpAbout.Text = "&About Font Validator...";
this.menuItemHelpAbout.Click += new System.EventHandler(this.menuItemHelpAbout_Click);
//
// toolBar1
//
this.toolBar1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
this.tbBtnNewProj,
this.tbBtnOpenProj,
this.tbBtnSaveProj,
this.sep1,
this.tbBtnOpenReport,
this.tbBtnPrintReport,
this.sep2,
this.tbBtnValidate});
this.toolBar1.DropDownArrows = true;
this.toolBar1.ImageList = this.imageList1;
this.toolBar1.Location = new System.Drawing.Point(0, 0);
this.toolBar1.Name = "toolBar1";
this.toolBar1.ShowToolTips = true;
this.toolBar1.Size = new System.Drawing.Size(632, 28);
this.toolBar1.TabIndex = 11;
this.toolBar1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick);
//
// tbBtnNewProj
//
this.tbBtnNewProj.ImageIndex = 0;
this.tbBtnNewProj.ToolTipText = "New Project";
//
// tbBtnOpenProj
//
this.tbBtnOpenProj.ImageIndex = 1;
this.tbBtnOpenProj.ToolTipText = "Open Project";
//
// tbBtnSaveProj
//
this.tbBtnSaveProj.ImageIndex = 2;
this.tbBtnSaveProj.ToolTipText = "Save Project";
//
// sep1
//
this.sep1.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// tbBtnOpenReport
//
this.tbBtnOpenReport.ImageIndex = 3;
this.tbBtnOpenReport.ToolTipText = "Open Report";
//
// tbBtnPrintReport
//
this.tbBtnPrintReport.ImageIndex = 4;
this.tbBtnPrintReport.ToolTipText = "Print Report";
//
// sep2
//
this.sep2.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// tbBtnValidate
//
this.tbBtnValidate.ImageIndex = 5;
this.tbBtnValidate.ToolTipText = "Start Validation";
//
// imageList1
//
this.imageList1.ImageSize = new System.Drawing.Size(16, 16);
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
//
// panel1
//
this.panel1.Controls.Add(this.tabControl1);
this.panel1.Dock = System.Windows.Forms.DockStyle.Left;
this.panel1.Location = new System.Drawing.Point(0, 28);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(208, 501);
this.panel1.TabIndex = 13;
//
// splitter1
//
this.splitter1.Location = new System.Drawing.Point(208, 28);
this.splitter1.Name = "splitter1";
this.splitter1.Size = new System.Drawing.Size(8, 501);
this.splitter1.TabIndex = 15;
this.splitter1.TabStop = false;
//
// Form1
//
this.AllowDrop = true;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(632, 529);
this.Controls.Add(this.splitter1);
this.Controls.Add(this.panel1);
this.Controls.Add(this.toolBar1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.IsMdiContainer = true;
this.Menu = this.mainMenu1;
this.Name = "Form1";
this.Text = "Font Validator";
this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);
this.Load += new System.EventHandler(this.Form1_Load);
this.DragDrop += new System.Windows.Forms.DragEventHandler(this.Form1_DragDrop);
this.DragEnter += new System.Windows.Forms.DragEventHandler(this.Form1_DragEnter);
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tabPage2.ResumeLayout(false);
this.tabPage3.ResumeLayout(false);
this.groupBoxResolution.ResumeLayout(false);
this.groupBoxCTFlags.ResumeLayout(false);
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void btnAddFont_Click(object sender, System.EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "OpenType Font files (*.ttf;*.ttc;*.otf)|*.ttf;*.ttc;*.otf|All files (*.*)|*.*" ;
openFileDialog1.FilterIndex = 1 ;
openFileDialog1.RestoreDirectory = true ;
openFileDialog1.Multiselect = true;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
for (int i=0; i<openFileDialog1.FileNames.Length; i++)
{
listBoxFont.Items.Add(openFileDialog1.FileNames[i]);
}
}
}
private void btnRemoveFont_Click(object sender, System.EventArgs e)
{
while (listBoxFont.SelectedIndices.Count > 0)
{
listBoxFont.Items.RemoveAt(listBoxFont.SelectedIndices[listBoxFont.SelectedIndices.Count-1]);
}
}
private void SetAllTestsBtn_Click(object sender, System.EventArgs e)
{
for (int i=0; i<checkedListBoxTests.Items.Count; i++)
{
checkedListBoxTests.SetItemChecked(i, true);
}
}
private void ClearAllTestsBtn_Click(object sender, System.EventArgs e)
{
for (int i=0; i<checkedListBoxTests.Items.Count; i++)
{
checkedListBoxTests.SetItemChecked(i, false);
}
}
void OnNewProject()
{
m_project = new project();
ProjectToForm(m_project);
}
void OnOpenProject()
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Font Validator Project files (*.fvp)|*.fvp|All files (*.*)|*.*";
dlg.FilterIndex = 1 ;
dlg.RestoreDirectory = true ;
if(dlg.ShowDialog() == DialogResult.OK)
{
OpenProject(dlg.FileName);
}
}
void OpenProject(String sFile)
{
m_project.LoadFromXmlFile(sFile);
ProjectToForm(m_project);
AddMRUProject(sFile);
}
void OnSaveProject()
{
if (m_project.GetFilename() == null)
{
OnSaveProjectAs();
}
else
{
// write the project file
FormToProject(m_project);
m_project.SaveToXmlFile();
}
}
void OnSaveProjectAs()
{
// get the filename from the user
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "Font Validator Project files (*.fvp)|*.fvp";
dlg.FilterIndex = 1;
dlg.RestoreDirectory = true ;
if(dlg.ShowDialog() == DialogResult.OK)
{
// write the project file
FormToProject(m_project);
m_project.SetFilename(dlg.FileName);
m_project.SaveToXmlFile();
AddMRUProject(dlg.FileName);
}
}
void OnOpenReport()
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Font Validator Report files (*.xml)|*.xml|All files (*.*)|*.*";
dlg.FilterIndex = 1 ;
dlg.RestoreDirectory = true ;
dlg.Multiselect = true;
if(dlg.ShowDialog() == DialogResult.OK)
{
for (int i=0; i<dlg.FileNames.Length; i++)
{
FileInfo fi = new FileInfo(dlg.FileNames[i]);
OpenReport(fi.FullName, fi.Name, false);
}
}
}
public delegate void OpenReportDelegate(string sFile, string sCaption, bool bDeleteOnClose);
public void OpenReport(String sFile, string sCaption, bool bDeleteOnClose)
{
ResultsForm rf = new ResultsForm();
rf.MdiParent = this;
rf.Text = sFile;
rf.Show();
rf.ShowFile(sFile, sCaption, bDeleteOnClose);
LayoutMdi(MdiLayout.Cascade); // this is necessary because the mshtml control was messing up the default window placement
Invalidate(true); // this is necessary to clean up some paint bugs in the current .Net framework
if (m_PersistedData.m_ReportFileDestination != ReportFileDestination.TempFiles)
{
AddMRUReport(sFile);
}
/*
WebBrowse wb = new WebBrowse( sFile );
wb.MdiParent = this;
wb.Show();
*/
}
void OnPrintReport()
{
ResultsForm rf = (ResultsForm)ActiveMdiChild;
if (rf != null)
{
rf.PrintFile();
}
else
{
MessageBox.Show(this, "nothing to print!");
}
}
void BeginValidation()
{
if (listBoxFont.Items.Count == 0)
{
MessageBox.Show(this, "No fonts to validate!\r\nYou must first add one or more fonts to the font file list.");
}
else
{
// disable the ui during validation
EnableUI(false);
try
{
// tell the validator which tests to perform
for (int i=0; i<checkedListBoxTests.Items.Count; i++)
{
string sTable = checkedListBoxTests.Items[i].ToString();
bool bPerform = checkedListBoxTests.GetItemChecked(i);
m_Validator.SetTablePerformTest(sTable, bPerform);
}
if (checkBoxRast.Checked)
{
m_Validator.SetRastPerformTest(checkBoxBW.Checked, checkBoxGray.Checked, checkBoxClearType.Checked,
checkBoxCTCompWidth.Checked, checkBoxCTVert.Checked, checkBoxCTBGR.Checked, checkBoxCTFractWidth.Checked);
}
else
{
m_Validator.SetRastPerformTest(false, false, false, false, false, false, false);
}
int x = Int32.Parse(textBoxXRes.Text);
int y = Int32.Parse(textBoxYRes.Text);
int [] pointsizes = ParseRastPointSizes();
m_Validator.SetRastTestParams(x, y, pointsizes, m_RastTestTransform);
// put up the progress dialog which will manage the validation
string [] sFiles = new string[listBoxFont.Items.Count];
for (int i=0; i<listBoxFont.Items.Count; i++)
{
sFiles[i] = listBoxFont.Items[i].ToString();
}
m_formProgress = new Progress(this, m_Validator, sFiles,
m_PersistedData.m_ReportFileDestination,
m_PersistedData.m_bOpenReportFile,
m_PersistedData.m_sReportFixedDir);
m_formProgress.TopLevel = false;
m_formProgress.Parent = this;
m_formProgress.BringToFront();
// centering isn't working with the current .Net framework, so force it to be centered
//m_formProgress.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
m_formProgress.SetBounds(Width/2 - m_formProgress.Width/2, Height/2 - m_formProgress.Height/2,
m_formProgress.Width, m_formProgress.Height, BoundsSpecified.Location);
m_formProgress.Show();
}
catch (Exception e)
{
MessageBox.Show(this, e.Message, "Error");
EnableUI(true);
}
}
}
public int[] ParseRastPointSizes()
{
ArrayList arrPointSizes = new ArrayList();
string s = textBoxPointSizes.Text;
Int32 n1;
Int32 n2;
while (s.Length != 0)
{
if (Char.IsDigit(s, 0))
{
// extract the number
n1=0;
while (s.Length != 0)
{
n1 = n1*10 + (s[0]-'0');
s = s.Substring(1, s.Length-1);
if (s.Length == 0)
{
break;
}
else if (!Char.IsDigit(s,0))
{
break;
}
}
// check if this is a range of numbers
n2 = -1;
while (s.Length != 0)
{
if (s[0] == '-')
{
// seek to the number
while (s.Length != 0)
{
s = s.Substring(1, s.Length-1);
if (s.Length == 0)
{
break;
}
else if (Char.IsDigit(s,0))
{
break;
}
}
// extract the number
n2=0;
while (s.Length != 0)
{
n2 = n2*10 + (s[0]-'0');
s = s.Substring(1, s.Length-1);
if (s.Length == 0)
{
break;
}
else if (!Char.IsDigit(s,0))
{
break;
}
}
break;
}
else if (!Char.IsDigit(s, 0))
{
s = s.Substring(1, s.Length-1);
}
else
{
break;
}
}
if (n2 == -1)
{
// add the point size
arrPointSizes.Add(n1);
}
else
{
// add each point in the range
for (Int32 i=n1; i<=n2; i++)
{
arrPointSizes.Add(i);
}
}
}
else
{
s = s.Substring(1, s.Length-1);
}
}
int [] sizearray = new int[arrPointSizes.Count];
for (int i=0; i<arrPointSizes.Count; i++)
{
sizearray[i] = (Int32)arrPointSizes[i];
}
return sizearray;
}
public delegate void UpdateBoolDelegate( bool val );
public delegate void UpdateIthBoolDelegate( int i, bool val );
private void UpdateIthMenuItem( int i, bool val )
{
mainMenu1.MenuItems[i].Enabled = val;
}
private void UpdateIthButton( int i, bool val )
{
toolBar1.Buttons[i].Enabled = val;
}
private void UpdateTabControl( bool val )
{
tabControl1.Enabled = val;
}
public void EnableUI(bool bEnabled)
{
UpdateIthBoolDelegate d1 = new UpdateIthBoolDelegate( UpdateIthMenuItem );
for (int i=0; i<mainMenu1.MenuItems.Count; i++)
{
//JJF mainMenu1.MenuItems[i].Enabled = bEnabled;
//JJF mainMenu1.MenuItems[i].Invoke( d1, new object[]{ i, bEnabled } );
tabControl1.Invoke( d1, new object[]{ i, bEnabled } );
}
UpdateIthBoolDelegate d2 = new UpdateIthBoolDelegate( UpdateIthButton );
for (int i=0; i<toolBar1.Buttons.Count; i++)
{
//JJF toolBar1.Buttons[i].Enabled = bEnabled;
//JJF toolBar1.Buttons[i].Invoke( d2, new object[]{ i, bEnabled } );
tabControl1.Invoke( d2, new object[]{ i, bEnabled } );
}
//JJF tabControl1.Enabled = bEnabled;
UpdateBoolDelegate d3 = new UpdateBoolDelegate( UpdateTabControl );
tabControl1.Invoke( d3, new object[]{ bEnabled } );
}
/**************************************************************************
*
* button handling
*
**************************************************************************/
private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
{
if (e.Button == tbBtnNewProj)
{
OnNewProject();
}
else if (e.Button == tbBtnOpenProj)
{
OnOpenProject();
}
else if (e.Button == tbBtnSaveProj)
{
OnSaveProject();
}
else if (e.Button == tbBtnOpenReport)
{
OnOpenReport();
}
else if (e.Button == tbBtnPrintReport)
{
OnPrintReport();
}
else if (e.Button == tbBtnValidate)
{
BeginValidation();
}
}
/**************************************************************************
*
* menu handlers
*
**************************************************************************/
/*********************
* file menu
*/
private void menuItemNewProj_Click(object sender, System.EventArgs e)
{
OnNewProject();
}
private void menuItemOpenProj_Click(object sender, System.EventArgs e)
{
OnOpenProject();
}
private void menuItemOpenReport_Click(object sender, System.EventArgs e)
{
OnOpenReport();
}
private void menuItemCloseReport_Click(object sender, System.EventArgs e)
{
if (ActiveMdiChild != null)
{
ActiveMdiChild.Close();
}
else
{
MessageBox.Show(this, "No report to close!");
}
}
private void menuItemSaveProj_Click(object sender, System.EventArgs e)
{
OnSaveProject();
}
private void menuItemSaveProjAs_Click(object sender, System.EventArgs e)
{
OnSaveProjectAs();
}
private void menuItemSaveReportAs_Click(object sender, System.EventArgs e)
{
ResultsForm rf = (ResultsForm)ActiveMdiChild;
if (rf != null)
{
// get the filename from the user
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "report files (*.xml)|*.xml";
dlg.FilterIndex = 1;
dlg.RestoreDirectory = true ;
dlg.FileName = rf.GetFilename();
if(dlg.ShowDialog() == DialogResult.OK)
{
rf.SaveReportAs(dlg.FileName);
Progress.CopyXslFile(dlg.FileName);
AddMRUReport(dlg.FileName);
}
}
else
{
MessageBox.Show(this, "no report to save!");
}
}
private void menuItemPrint_Click(object sender, System.EventArgs e)
{
OnPrintReport();
}
private void menuItemFileExit_Click(object sender, System.EventArgs e)
{
Close();
}
/*********************
* edit menu
*/
private void menuItemEditCopy_Click(object sender, System.EventArgs e)
{
ResultsForm rf = (ResultsForm)ActiveMdiChild;
if (rf != null)
{
rf.CopyToClipboard();
}
else
{
MessageBox.Show(this, "nothing to copy!");
}
}
private void menuItemEditSelectAll_Click(object sender, System.EventArgs e)
{
if (this.ActiveControl == listBoxFont)
{
for (int i=0; i<listBoxFont.Items.Count; i++)
{
listBoxFont.SetSelected(i, true);
}
}
else
{
ResultsForm rf = (ResultsForm)ActiveMdiChild;
if (rf != null)
{
rf.SelectAll();
}
else
{
MessageBox.Show(this, "nothing to select!");
}
}
}
/*********************
* validation menu
*/
private void menuItemValRun_Click(object sender, System.EventArgs e)
{
BeginValidation();
}
/*********************
* window menu
*/
/*********************
* help menu
*/
private void menuItemHelpHelp_Click(object sender, System.EventArgs e)
{
Help.ShowHelp(this, "fontvalidatorhelp.chm");
}
private void menuItemHelpAbout_Click(object sender, System.EventArgs e)
{
FormAbout aboutForm = new FormAbout();
aboutForm.ShowDialog(this);
}
/*********************
* project support
*/
private String GetComputerName()
{
String sComputerName;
try
{
sComputerName = SystemInformation.ComputerName;
}
catch
{
sComputerName = "unavailable";
}
return sComputerName;
}
private void FormToProject(project prj)
{
// set the network name for this computer
prj.SetComputerName(GetComputerName());
// set files to use
string [] sFiles = new string[listBoxFont.Items.Count];
for (int i=0; i<listBoxFont.Items.Count; i++)
{
sFiles[i] = listBoxFont.Items[i].ToString();
}
prj.SetFilesToTest(sFiles);
// set which tests to perform
for (int i=0; i<checkedListBoxTests.Items.Count; i++)
{
string sTable = checkedListBoxTests.Items[i].ToString();
bool bPerform = checkedListBoxTests.GetItemChecked(i);
prj.SetTableTest(sTable, bPerform);
}
}
private void ProjectToForm(project prj)
{
// compare the project's computername with the network name for this computer
if (prj.GetComputerName() != GetComputerName())
{
String sMsg = "Warning! This project was created on a different computer named" +
"'" + prj.GetComputerName() + "'. Some files may not be accessible.";
MessageBox.Show(this, sMsg);
}
// load the files
listBoxFont.Items.Clear();
string [] sFiles = prj.GetFilesToTest();
if (sFiles != null)
{
for (int i=0; i<sFiles.Length; i++)
{
listBoxFont.Items.Add(sFiles[i]);
}
}
// load the tests
for (int i=0; i<checkedListBoxTests.Items.Count; i++)
{
string sTable = checkedListBoxTests.Items[i].ToString();
bool bPerform = prj.GetTableTest(sTable);
checkedListBoxTests.SetItemChecked(i, bPerform);
}
}
private void Form1_Load(object sender, System.EventArgs e)
{
// load PersistedData
FileStream fs = null;
try
{
// Create an XmlSerializer for the PersistedData type.
XmlSerializer ser = new XmlSerializer(typeof(PersistedData));
FileInfo fi = new FileInfo(Application.LocalUserAppDataPath + Path.DirectorySeparatorChar + @"FontVal.Data");
// If the config file exists, open it.
if(fi.Exists)
{
fs = fi.OpenRead();
m_PersistedData = (PersistedData)ser.Deserialize(fs);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
// If the FileStream is open, close it.
if (fs != null) fs.Close();
}
UpdateMRUMenus();
// hack the size of the listbox if it is bigger than the tabcontrol
// which happens courtesy of the current .Net framework when running the program
// on a display that is greater than 96 dpi
if (listBoxFont.Right > tabControl1.Width || listBoxFont.Bottom > tabControl1.Height)
{
listBoxFont.SetBounds(listBoxFont.Location.X, listBoxFont.Location.Y,
tabControl1.Width-listBoxFont.Left*3, tabControl1.Height-listBoxFont.Top-listBoxFont.Left*3, BoundsSpecified.Size);
}
// show help if this is the first time the program is being run
if (m_PersistedData.m_bFirstTime)
{
Help.ShowHelp(this, "fontvalidatorhelp.chm", HelpNavigator.Topic, "usingvalidator.htm");
m_PersistedData.m_bFirstTime = false;
}
}
private void Form1_Closing(object sender, CancelEventArgs e)
{
// save application settings
StreamWriter sw = null;
try
{
// Create an XmlSerializer for the PersistedData type.
XmlSerializer ser = new XmlSerializer(typeof(PersistedData));
sw = new StreamWriter(Application.LocalUserAppDataPath + Path.DirectorySeparatorChar + @"FontVal.Data", false);
// Serialize the instance of the PersistedData class
ser.Serialize(sw, m_PersistedData);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
// If the StreamWriter is open, close it.
if (sw != null) sw.Close();
}
}
private void AddMRUProject(String sProject)
{
int iDeletePos = m_PersistedData.m_sMRUProjects.Length-1;
for (int i=0; i<m_PersistedData.m_sMRUProjects.Length; i++)
{
if (m_PersistedData.m_sMRUProjects[i] == sProject)
{
iDeletePos = i;
break;
}
}
for (int i=iDeletePos; i>0; i--)
{
m_PersistedData.m_sMRUProjects[i] = m_PersistedData.m_sMRUProjects[i-1];
}
m_PersistedData.m_sMRUProjects[0] = sProject;
UpdateMRUMenus();
}
private void AddMRUReport(String sReport)
{
int iDeletePos = m_PersistedData.m_sMRUReports.Length-1;
for (int i=0; i<m_PersistedData.m_sMRUReports.Length; i++)
{
if (m_PersistedData.m_sMRUReports[i] == sReport)
{
iDeletePos = i;
break;
}
}
for (int i=iDeletePos; i>0; i--)
{
m_PersistedData.m_sMRUReports[i] = m_PersistedData.m_sMRUReports[i-1];
}
m_PersistedData.m_sMRUReports[0] = sReport;
UpdateMRUMenus();
}
private void UpdateMRUMenus()
{
menuItemMRUProject1.Text = m_PersistedData.m_sMRUProjects[0];
menuItemMRUProject2.Text = m_PersistedData.m_sMRUProjects[1];
menuItemMRUProject3.Text = m_PersistedData.m_sMRUProjects[2];
menuItemMRUProject4.Text = m_PersistedData.m_sMRUProjects[3];
bool bProjects = false;
for (int i=0; i<4; i++)
{
if (m_PersistedData.m_sMRUProjects[i] != null)
{
if (m_PersistedData.m_sMRUProjects[i].Length > 0)
{
bProjects = true;
}
}
}
menuItemRecentProj.Enabled = bProjects;
menuItemMRUReport1.Text = m_PersistedData.m_sMRUReports[0];
menuItemMRUReport2.Text = m_PersistedData.m_sMRUReports[1];
menuItemMRUReport3.Text = m_PersistedData.m_sMRUReports[2];
menuItemMRUReport4.Text = m_PersistedData.m_sMRUReports[3];
bool bReports = false;
for (int i=0; i<4; i++)
{
if (m_PersistedData.m_sMRUReports[i] != null)
{
if (m_PersistedData.m_sMRUReports[i].Length > 0)
{
bReports = true;
}
}
}
menuItemRecentReports.Enabled = bReports;
}
private void menuItemMRUProject1_Click(object sender, System.EventArgs e)
{
if (m_PersistedData.m_sMRUProjects[0] != "")
{
OpenProject(m_PersistedData.m_sMRUProjects[0]);
}
}
private void menuItemMRUProject2_Click(object sender, System.EventArgs e)
{
if (m_PersistedData.m_sMRUProjects[1] != "")
{
OpenProject(m_PersistedData.m_sMRUProjects[1]);
}
}
private void menuItemMRUProject3_Click(object sender, System.EventArgs e)
{
if (m_PersistedData.m_sMRUProjects[2] != "")
{
OpenProject(m_PersistedData.m_sMRUProjects[2]);
}
}
private void menuItemMRUProject4_Click(object sender, System.EventArgs e)
{
if (m_PersistedData.m_sMRUProjects[3] != "")
{
OpenProject(m_PersistedData.m_sMRUProjects[3]);
}
}
private void menuItemMRUReport1_Click(object sender, System.EventArgs e)
{
if (m_PersistedData.m_sMRUReports[0] != "")
{
FileInfo fi = new FileInfo(m_PersistedData.m_sMRUReports[0]);
OpenReport(fi.FullName, fi.Name, false);
}
}
private void menuItemMRUReport2_Click(object sender, System.EventArgs e)
{
if (m_PersistedData.m_sMRUReports[1] != "")
{
FileInfo fi = new FileInfo(m_PersistedData.m_sMRUReports[1]);
OpenReport(fi.FullName, fi.Name, false);
}
}
private void menuItemMRUReport3_Click(object sender, System.EventArgs e)
{
if (m_PersistedData.m_sMRUReports[2] != "")
{
FileInfo fi = new FileInfo(m_PersistedData.m_sMRUReports[2]);
OpenReport(fi.FullName, fi.Name, false);
}
}
private void menuItemMRUReport4_Click(object sender, System.EventArgs e)
{
if (m_PersistedData.m_sMRUReports[3] != "")
{
FileInfo fi = new FileInfo(m_PersistedData.m_sMRUReports[3]);
OpenReport(fi.FullName, fi.Name, false);
}
}
private void menuItemWinCascade_Click(object sender, System.EventArgs e)
{
LayoutMdi(MdiLayout.Cascade);
}
private void menuItemWinTileHorz_Click(object sender, System.EventArgs e)
{
LayoutMdi(MdiLayout.TileHorizontal);
}
private void menuItemWinTileVert_Click(object sender, System.EventArgs e)
{
LayoutMdi(MdiLayout.TileVertical);
}
private void menuItemWinCloseAll_Click(object sender, System.EventArgs e)
{
while (MdiChildren.Length != 0)
{
MdiChildren[MdiChildren.Length-1].Close();
}
}
private void menuItemValAddFont_Click(object sender, System.EventArgs e)
{
if (tabControl1.SelectedIndex != 0)
{
tabControl1.SelectedIndex = 0;
}
btnAddFont_Click(sender, e);
}
private void menuItemValRemoveFont_Click(object sender, System.EventArgs e)
{
if (tabControl1.SelectedIndex == 0)
{
btnRemoveFont_Click(sender, e);
}
else
{
MessageBox.Show(this,
"select the 'Fonts Files' tab before attempting to remove a font from the list",
"Warning: font not removed",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void listBoxFont_SelectedIndexChanged(object sender, System.EventArgs e)
{
}
private void checkBoxRast_CheckedChanged(object sender, System.EventArgs e)
{
bool bChecked = checkBoxRast.Checked;
checkBoxBW.Enabled = bChecked;
checkBoxGray.Enabled = bChecked;
checkBoxClearType.Enabled = bChecked;
if (bChecked)
{
groupBoxCTFlags.Enabled = checkBoxClearType.Checked;
}
else
{
groupBoxCTFlags.Enabled = bChecked;
}
groupBoxResolution.Enabled = bChecked;
labelPointsizes.Enabled = bChecked;
textBoxPointSizes.Enabled = bChecked;
btnTransform.Enabled = bChecked;
}
private void checkBoxClearType_CheckedChanged(object sender, System.EventArgs e)
{
groupBoxCTFlags.Enabled = checkBoxClearType.Checked;
}
private void btnTransform_Click(object sender, System.EventArgs e)
{
FormTransform form = new FormTransform(m_RastTestTransform);
form.ShowDialog(this);
}
private void menuReportOptions_Click(object sender, System.EventArgs e)
{
FormReportOptions fro = new FormReportOptions();
fro.OpenReportFile = m_PersistedData.m_bOpenReportFile;
fro.ReportFileDestination = m_PersistedData.m_ReportFileDestination;
fro.FixedDir = m_PersistedData.m_sReportFixedDir;
DialogResult dr = fro.ShowDialog(this);
if (dr == DialogResult.OK)
{
m_PersistedData.m_bOpenReportFile = fro.OpenReportFile;
m_PersistedData.m_ReportFileDestination = fro.ReportFileDestination;
m_PersistedData.m_sReportFixedDir = fro.FixedDir;
}
}
private void listBoxFont_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
btnRemoveFont_Click(null, null);
}
}
private void Form1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
private void Form1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
string [] arrFiles = (string[])e.Data.GetData(DataFormats.FileDrop);
for (int i=0; i<arrFiles.Length; i++)
{
listBoxFont.Items.Add(arrFiles[i]);
}
// show the font pane if necessary
if (tabControl1.SelectedIndex != 0)
{
tabControl1.SelectedIndex = 0;
}
}
}
public class PersistedData
{
public PersistedData()
{
m_sMRUProjects = new String[4];
m_sMRUReports = new String[4];
m_ReportFileDestination = ReportFileDestination.TempFiles;
m_bOpenReportFile = true;
m_sReportFixedDir = "";
m_bFirstTime = true;
}
public String [] m_sMRUProjects;
public String [] m_sMRUReports;
public ReportFileDestination m_ReportFileDestination;
public bool m_bOpenReportFile;
public string m_sReportFixedDir;
public bool m_bFirstTime;
}
}
| |
/*
* REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application
*
* The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using HETSAPI.Models;
namespace HETSAPI.ViewModels
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class RentalRequestSearchResultViewModel : IEquatable<RentalRequestSearchResultViewModel>
{
/// <summary>
/// Default constructor, required by entity framework
/// </summary>
public RentalRequestSearchResultViewModel()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RentalRequestSearchResultViewModel" /> class.
/// </summary>
/// <param name="Id">Id (required).</param>
/// <param name="LocalArea">LocalArea.</param>
/// <param name="EquipmentCount">EquipmentCount.</param>
/// <param name="EquipmentTypeName">EquipmentTypeName.</param>
/// <param name="ProjectName">ProjectName.</param>
/// <param name="PrimaryContact">PrimaryContact.</param>
/// <param name="Status">Project status.</param>
/// <param name="ProjectId">ProjectId.</param>
/// <param name="ExpectedStartDate">ExpectedStartDate.</param>
/// <param name="ExpectedEndDate">ExpectedEndDate.</param>
public RentalRequestSearchResultViewModel(int Id, LocalArea LocalArea = null, int? EquipmentCount = null, string EquipmentTypeName = null, string ProjectName = null, Contact PrimaryContact = null, string Status = null, int? ProjectId = null, DateTime? ExpectedStartDate = null, DateTime? ExpectedEndDate = null)
{
this.Id = Id;
this.LocalArea = LocalArea;
this.EquipmentCount = EquipmentCount;
this.EquipmentTypeName = EquipmentTypeName;
this.ProjectName = ProjectName;
this.PrimaryContact = PrimaryContact;
this.Status = Status;
this.ProjectId = ProjectId;
this.ExpectedStartDate = ExpectedStartDate;
this.ExpectedEndDate = ExpectedEndDate;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id")]
public int Id { get; set; }
/// <summary>
/// Gets or Sets LocalArea
/// </summary>
[DataMember(Name="localArea")]
public LocalArea LocalArea { get; set; }
/// <summary>
/// Gets or Sets EquipmentCount
/// </summary>
[DataMember(Name="equipmentCount")]
public int? EquipmentCount { get; set; }
/// <summary>
/// Gets or Sets EquipmentTypeName
/// </summary>
[DataMember(Name="equipmentTypeName")]
public string EquipmentTypeName { get; set; }
/// <summary>
/// Gets or Sets ProjectName
/// </summary>
[DataMember(Name="projectName")]
public string ProjectName { get; set; }
/// <summary>
/// Gets or Sets PrimaryContact
/// </summary>
[DataMember(Name="primaryContact")]
public Contact PrimaryContact { get; set; }
/// <summary>
/// Project status
/// </summary>
/// <value>Project status</value>
[DataMember(Name="status")]
[MetaDataExtension (Description = "Project status")]
public string Status { get; set; }
/// <summary>
/// Gets or Sets ProjectId
/// </summary>
[DataMember(Name="projectId")]
public int? ProjectId { get; set; }
/// <summary>
/// Gets or Sets ExpectedStartDate
/// </summary>
[DataMember(Name="expectedStartDate")]
public DateTime? ExpectedStartDate { get; set; }
/// <summary>
/// Gets or Sets ExpectedEndDate
/// </summary>
[DataMember(Name="expectedEndDate")]
public DateTime? ExpectedEndDate { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class RentalRequestSearchResultViewModel {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" LocalArea: ").Append(LocalArea).Append("\n");
sb.Append(" EquipmentCount: ").Append(EquipmentCount).Append("\n");
sb.Append(" EquipmentTypeName: ").Append(EquipmentTypeName).Append("\n");
sb.Append(" ProjectName: ").Append(ProjectName).Append("\n");
sb.Append(" PrimaryContact: ").Append(PrimaryContact).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" ProjectId: ").Append(ProjectId).Append("\n");
sb.Append(" ExpectedStartDate: ").Append(ExpectedStartDate).Append("\n");
sb.Append(" ExpectedEndDate: ").Append(ExpectedEndDate).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
if (obj.GetType() != GetType()) { return false; }
return Equals((RentalRequestSearchResultViewModel)obj);
}
/// <summary>
/// Returns true if RentalRequestSearchResultViewModel instances are equal
/// </summary>
/// <param name="other">Instance of RentalRequestSearchResultViewModel to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(RentalRequestSearchResultViewModel other)
{
if (ReferenceEquals(null, other)) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
this.Id == other.Id ||
this.Id.Equals(other.Id)
) &&
(
this.LocalArea == other.LocalArea ||
this.LocalArea != null &&
this.LocalArea.Equals(other.LocalArea)
) &&
(
this.EquipmentCount == other.EquipmentCount ||
this.EquipmentCount != null &&
this.EquipmentCount.Equals(other.EquipmentCount)
) &&
(
this.EquipmentTypeName == other.EquipmentTypeName ||
this.EquipmentTypeName != null &&
this.EquipmentTypeName.Equals(other.EquipmentTypeName)
) &&
(
this.ProjectName == other.ProjectName ||
this.ProjectName != null &&
this.ProjectName.Equals(other.ProjectName)
) &&
(
this.PrimaryContact == other.PrimaryContact ||
this.PrimaryContact != null &&
this.PrimaryContact.Equals(other.PrimaryContact)
) &&
(
this.Status == other.Status ||
this.Status != null &&
this.Status.Equals(other.Status)
) &&
(
this.ProjectId == other.ProjectId ||
this.ProjectId != null &&
this.ProjectId.Equals(other.ProjectId)
) &&
(
this.ExpectedStartDate == other.ExpectedStartDate ||
this.ExpectedStartDate != null &&
this.ExpectedStartDate.Equals(other.ExpectedStartDate)
) &&
(
this.ExpectedEndDate == other.ExpectedEndDate ||
this.ExpectedEndDate != null &&
this.ExpectedEndDate.Equals(other.ExpectedEndDate)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks
hash = hash * 59 + this.Id.GetHashCode();
if (this.LocalArea != null)
{
hash = hash * 59 + this.LocalArea.GetHashCode();
} if (this.EquipmentCount != null)
{
hash = hash * 59 + this.EquipmentCount.GetHashCode();
}
if (this.EquipmentTypeName != null)
{
hash = hash * 59 + this.EquipmentTypeName.GetHashCode();
}
if (this.ProjectName != null)
{
hash = hash * 59 + this.ProjectName.GetHashCode();
}
if (this.PrimaryContact != null)
{
hash = hash * 59 + this.PrimaryContact.GetHashCode();
} if (this.Status != null)
{
hash = hash * 59 + this.Status.GetHashCode();
}
if (this.ProjectId != null)
{
hash = hash * 59 + this.ProjectId.GetHashCode();
}
if (this.ExpectedStartDate != null)
{
hash = hash * 59 + this.ExpectedStartDate.GetHashCode();
}
if (this.ExpectedEndDate != null)
{
hash = hash * 59 + this.ExpectedEndDate.GetHashCode();
}
return hash;
}
}
#region Operators
/// <summary>
/// Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(RentalRequestSearchResultViewModel left, RentalRequestSearchResultViewModel right)
{
return Equals(left, right);
}
/// <summary>
/// Not Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(RentalRequestSearchResultViewModel left, RentalRequestSearchResultViewModel right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
//
// TreeView.cs
//
// Author:
// Lluis Sanchez <[email protected]>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Drawing;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using Xwt.Backends;
namespace Xwt
{
[BackendType (typeof(ITreeViewBackend))]
public class TreeView: Widget, IColumnContainer, IScrollableWidget
{
ListViewColumnCollection columns;
ITreeDataSource dataSource;
SelectionMode mode;
protected new class WidgetBackendHost: Widget.WidgetBackendHost<TreeView,ITreeViewBackend>, ITreeViewEventSink
{
protected override void OnBackendCreated ()
{
base.OnBackendCreated ();
Backend.Initialize (this);
Parent.columns.Attach (Backend);
}
public void OnSelectionChanged ()
{
((TreeView)Parent).OnSelectionChanged (EventArgs.Empty);
}
public void OnRowActivated (TreePosition position)
{
((TreeView)Parent).OnRowActivated (new TreeViewRowEventArgs (position));
}
public void OnRowExpanded (TreePosition position)
{
((TreeView)Parent).OnRowExpanded (new TreeViewRowEventArgs (position));
}
public void OnRowExpanding (TreePosition position)
{
((TreeView)Parent).OnRowExpanding (new TreeViewRowEventArgs (position));
}
public override Size GetDefaultNaturalSize ()
{
return Xwt.Backends.DefaultNaturalSizes.TreeView;
}
}
static TreeView ()
{
MapEvent (TableViewEvent.SelectionChanged, typeof(TreeView), "OnSelectionChanged");
MapEvent (TreeViewEvent.RowActivated, typeof(TreeView), "OnRowActivated");
MapEvent (TreeViewEvent.RowExpanded, typeof(TreeView), "OnRowExpanded");
MapEvent (TreeViewEvent.RowExpanding, typeof(TreeView), "OnRowExpanding");
}
/// <summary>
/// Initializes a new instance of the <see cref="Xwt.TreeView"/> class.
/// </summary>
public TreeView ()
{
columns = new ListViewColumnCollection (this);
VerticalScrollPolicy = HorizontalScrollPolicy = ScrollPolicy.Automatic;
}
/// <summary>
/// Initializes a new instance of the <see cref="Xwt.TreeView"/> class.
/// </summary>
/// <param name='source'>
/// Data source
/// </param>
public TreeView (ITreeDataSource source): this ()
{
VerifyConstructorCall (this);
DataSource = source;
}
protected override BackendHost CreateBackendHost ()
{
return new WidgetBackendHost ();
}
ITreeViewBackend Backend {
get { return (ITreeViewBackend) BackendHost.Backend; }
}
public ScrollPolicy VerticalScrollPolicy {
get { return Backend.VerticalScrollPolicy; }
set { Backend.VerticalScrollPolicy = value; }
}
public ScrollPolicy HorizontalScrollPolicy {
get { return Backend.HorizontalScrollPolicy; }
set { Backend.HorizontalScrollPolicy = value; }
}
ScrollControl verticalScrollAdjustment;
public ScrollControl VerticalScrollControl {
get {
if (verticalScrollAdjustment == null)
verticalScrollAdjustment = new ScrollControl (Backend.CreateVerticalScrollControl ());
return verticalScrollAdjustment;
}
}
ScrollControl horizontalScrollAdjustment;
public ScrollControl HorizontalScrollControl {
get {
if (horizontalScrollAdjustment == null)
horizontalScrollAdjustment = new ScrollControl (Backend.CreateHorizontalScrollControl ());
return horizontalScrollAdjustment;
}
}
/// <summary>
/// Gets the tree columns.
/// </summary>
/// <value>
/// The columns.
/// </value>
public ListViewColumnCollection Columns {
get {
return columns;
}
}
/// <summary>
/// Gets or sets the data source.
/// </summary>
/// <value>
/// The data source.
/// </value>
public ITreeDataSource DataSource {
get {
return dataSource;
}
set {
if (dataSource != value) {
Backend.SetSource (value, value is IFrontend ? (IBackend)BackendHost.ToolkitEngine.GetSafeBackend (value) : null);
dataSource = value;
}
}
}
/// <summary>
/// Gets or sets a value indicating whether headers are visible or not.
/// </summary>
/// <value>
/// <c>true</c> if headers are visible; otherwise, <c>false</c>.
/// </value>
public bool HeadersVisible {
get {
return Backend.HeadersVisible;
}
set {
Backend.HeadersVisible = value;
}
}
/// <summary>
/// Gets or sets the selection mode.
/// </summary>
/// <value>
/// The selection mode.
/// </value>
public SelectionMode SelectionMode {
get {
return mode;
}
set {
mode = value;
Backend.SetSelectionMode (mode);
}
}
/// <summary>
/// Gets or sets the row the current event applies to.
/// The behavior of this property is undefined when used outside an
/// event that supports it.
/// </summary>
/// <value>
/// The current event row.
/// </value>
public TreePosition CurrentEventRow {
get {
return Backend.CurrentEventRow;
}
}
/// <summary>
/// Gets the selected row.
/// </summary>
/// <value>
/// The selected row.
/// </value>
public TreePosition SelectedRow {
get {
var items = SelectedRows;
if (items.Length == 0)
return null;
else
return items [0];
}
}
/// <summary>
/// Gets the selected rows.
/// </summary>
/// <value>
/// The selected rows.
/// </value>
public TreePosition[] SelectedRows {
get {
return Backend.SelectedRows;
}
}
/// <summary>
/// Selects a row.
/// </summary>
/// <param name='pos'>
/// Position of the row
/// </param>
public void SelectRow (TreePosition pos)
{
Backend.SelectRow (pos);
}
/// <summary>
/// Unselects a row.
/// </summary>
/// <param name='pos'>
/// Position of the row
/// </param>
public void UnselectRow (TreePosition pos)
{
Backend.UnselectRow (pos);
}
/// <summary>
/// Selects all rows
/// </summary>
public void SelectAll ()
{
Backend.SelectAll ();
}
/// <summary>
/// Unselects all rows
/// </summary>
public void UnselectAll ()
{
Backend.UnselectAll ();
}
/// <summary>
/// Determines whether the row at the specified position is selected
/// </summary>
/// <returns>
/// <c>true</c> if the row is selected, <c>false</c> otherwise.
/// </returns>
/// <param name='pos'>
/// Row position
/// </param>
public bool IsRowSelected (TreePosition pos)
{
return Backend.IsRowSelected (pos);
}
/// <summary>
/// Determines whether the row at the specified position is expanded
/// </summary>
/// <returns>
/// <c>true</c> if the row is expanded, <c>false</c> otherwise.
/// </returns>
/// <param name='pos'>
/// Row position
/// </param>
public bool IsRowExpanded (TreePosition pos)
{
return Backend.IsRowExpanded (pos);
}
/// <summary>
/// Expands a row.
/// </summary>
/// <param name='pos'>
/// Position of the row
/// </param>
/// <param name='expandChildren'>
/// If True, all children are recursively expanded
/// </param>
public void ExpandRow (TreePosition pos, bool expandChildren)
{
Backend.ExpandRow (pos, expandChildren);
}
/// <summary>
/// Collapses a row.
/// </summary>
/// <param name='pos'>
/// Position of the row
/// </param>
public void CollapseRow (TreePosition pos)
{
Backend.CollapseRow (pos);
}
/// <summary>
/// Recursively expands all nodes of the tree
/// </summary>
public void ExpandAll ()
{
if (DataSource != null) {
var nc = DataSource.GetChildrenCount (null);
for (int n=0; n<nc; n++) {
var p = DataSource.GetChild (null, n);
Backend.ExpandRow (p, true);
}
}
}
/// <summary>
/// Saves the status of the tree
/// </summary>
/// <returns>
/// A status object
/// </returns>
/// <param name='idField'>
/// Field to be used to identify each row
/// </param>
/// <remarks>
/// The status information includes node expansion and selection status. The returned object
/// can be used to restore the status by calling RestoreStatus.
/// The provided field is used to generate an identifier for each row. When restoring the
/// status, those ids are used to find matching rows.
/// </remarks>
public TreeViewStatus SaveStatus (IDataField idField)
{
return new TreeViewStatus (this, idField.Index);
}
/// <summary>
/// Restores the status of the tree
/// </summary>
/// <param name='status'>
/// Status object
/// </param>
/// <remarks>
/// The status information includes node expansion and selection status. The provided object
/// must have been generated with a SaveStatus call on this same tree.
/// </remarks>
public void RestoreStatus (TreeViewStatus status)
{
status.Load (this);
}
public void ScrollToRow (TreePosition pos)
{
Backend.ScrollToRow (pos);
}
public void ExpandToRow (TreePosition pos)
{
Backend.ExpandToRow (pos);
}
public bool GetDropTargetRow (double x, double y, out RowDropPosition pos, out TreePosition nodePosition)
{
return Backend.GetDropTargetRow (x, y, out pos, out nodePosition);
}
internal protected sealed override bool SupportsCustomScrolling {
get {
return false;
}
}
void IColumnContainer.NotifyColumnsChanged ()
{
}
/// <summary>
/// Raises the selection changed event.
/// </summary>
/// <param name='a'>
/// Event arguments
/// </param>
protected virtual void OnSelectionChanged (EventArgs a)
{
if (selectionChanged != null)
selectionChanged (this, a);
}
EventHandler selectionChanged;
/// <summary>
/// Occurs when the selection changes
/// </summary>
public event EventHandler SelectionChanged {
add {
BackendHost.OnBeforeEventAdd (TableViewEvent.SelectionChanged, selectionChanged);
selectionChanged += value;
}
remove {
selectionChanged -= value;
BackendHost.OnAfterEventRemove (TableViewEvent.SelectionChanged, selectionChanged);
}
}
/// <summary>
/// Raises the row activated event.
/// </summary>
/// <param name="a">The alpha component.</param>
protected virtual void OnRowActivated (TreeViewRowEventArgs a)
{
if (rowActivated != null)
rowActivated (this, a);
}
EventHandler<TreeViewRowEventArgs> rowActivated;
/// <summary>
/// Occurs when the user double-clicks on a row
/// </summary>
public event EventHandler<TreeViewRowEventArgs> RowActivated {
add {
BackendHost.OnBeforeEventAdd (TreeViewEvent.RowActivated, rowActivated);
rowActivated += value;
}
remove {
rowActivated -= value;
BackendHost.OnAfterEventRemove (TreeViewEvent.RowActivated, rowActivated);
}
}
/// <summary>
/// Raises the row expanding event.
/// </summary>
/// <param name="a">The alpha component.</param>
protected virtual void OnRowExpanding (TreeViewRowEventArgs a)
{
if (rowExpanding != null)
rowExpanding (this, a);
}
EventHandler<TreeViewRowEventArgs> rowExpanding;
/// <summary>
/// Occurs just before a row is expanded
/// </summary>
public event EventHandler<TreeViewRowEventArgs> RowExpanding {
add {
BackendHost.OnBeforeEventAdd (TreeViewEvent.RowExpanding, rowExpanding);
rowExpanding += value;
}
remove {
rowExpanding -= value;
BackendHost.OnAfterEventRemove (TreeViewEvent.RowExpanding, rowExpanding);
}
}
/// <summary>
/// Raises the row expanding event.
/// </summary>
/// <param name="a">The alpha component.</param>
protected virtual void OnRowExpanded (TreeViewRowEventArgs a)
{
if (rowExpanded != null)
rowExpanded (this, a);
}
EventHandler<TreeViewRowEventArgs> rowExpanded;
/// <summary>
/// Occurs just before a row is expanded
/// </summary>
public event EventHandler<TreeViewRowEventArgs> RowExpanded {
add {
BackendHost.OnBeforeEventAdd (TreeViewEvent.RowExpanded, rowExpanded);
rowExpanded += value;
}
remove {
rowExpanded -= value;
BackendHost.OnAfterEventRemove (TreeViewEvent.RowExpanded, rowExpanded);
}
}
}
interface IColumnContainer
{
void NotifyColumnsChanged ();
}
interface ICellContainer
{
void NotifyCellChanged ();
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
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.OpsWorks.Model
{
/// <summary>
/// Container for the parameters to the CreateStack operation.
/// <para>Creates a new stack. For more information, see Create a New Stack.</para>
/// </summary>
/// <seealso cref="Amazon.OpsWorks.AmazonOpsWorks.CreateStack"/>
public class CreateStackRequest : AmazonWebServiceRequest
{
private string name;
private string region;
private string vpcId;
private Dictionary<string,string> attributes = new Dictionary<string,string>();
private string serviceRoleArn;
private string defaultInstanceProfileArn;
private string defaultOs;
private string hostnameTheme;
private string defaultAvailabilityZone;
private string defaultSubnetId;
private string customJson;
private StackConfigurationManager configurationManager;
private bool? useCustomCookbooks;
private Source customCookbooksSource;
private string defaultSshKeyName;
private string defaultRootDeviceType;
/// <summary>
/// The stack name.
///
/// </summary>
public string Name
{
get { return this.name; }
set { this.name = value; }
}
/// <summary>
/// Sets the Name property
/// </summary>
/// <param name="name">The value to set for the Name property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateStackRequest WithName(string name)
{
this.name = name;
return this;
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this.name != null;
}
/// <summary>
/// The stack AWS region, such as "us-east-1". For more information about Amazon regions, see <a
/// href="http://docs.aws.amazon.com/general/latest/gr/rande.html">Regions and Endpoints</a>.
///
/// </summary>
public string Region
{
get { return this.region; }
set { this.region = value; }
}
/// <summary>
/// Sets the Region property
/// </summary>
/// <param name="region">The value to set for the Region property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateStackRequest WithRegion(string region)
{
this.region = region;
return this;
}
// Check to see if Region property is set
internal bool IsSetRegion()
{
return this.region != null;
}
/// <summary>
/// The ID of the VPC that the stack is to be launched into. It must be in the specified region. All instances will be launched into this VPC,
/// and you cannot change the ID later. <ul> <li>If your account supports EC2 Classic, the default value is no VPC.</li> <li>If you account does
/// not support EC2 Classic, the default value is the default VPC for the specified region.</li> </ul> If the VPC ID corresponds to a default
/// VPC and you have specified either the <c>DefaultAvailabilityZone</c> or the <c>DefaultSubnetId</c> parameter only, AWS OpsWorks infers the
/// value of the other parameter. If you specify neither parameter, AWS OpsWorks sets these parameters to the first valid Availability Zone for
/// the specified region and the corresponding default VPC subnet ID, respectively. If you specify a nondefault VPC ID, note the following: <ul>
/// <li>It must belong to a VPC in your account that is in the specified region.</li> <li>You must specify a value for
/// <c>DefaultSubnetId</c>.</li> </ul> For more information on how to use AWS OpsWorks with a VPC, see <a
/// href="http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-vpc.html">Running a Stack in a VPC</a>. For more information on
/// default VPC and EC2 Classic, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-platforms.html">Supported
/// Platforms</a>.
///
/// </summary>
public string VpcId
{
get { return this.vpcId; }
set { this.vpcId = value; }
}
/// <summary>
/// Sets the VpcId property
/// </summary>
/// <param name="vpcId">The value to set for the VpcId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateStackRequest WithVpcId(string vpcId)
{
this.vpcId = vpcId;
return this;
}
// Check to see if VpcId property is set
internal bool IsSetVpcId()
{
return this.vpcId != null;
}
/// <summary>
/// One or more user-defined key/value pairs to be added to the stack attributes bag.
///
/// </summary>
public Dictionary<string,string> Attributes
{
get { return this.attributes; }
set { this.attributes = value; }
}
/// <summary>
/// Adds the KeyValuePairs to the Attributes dictionary.
/// </summary>
/// <param name="pairs">The pairs to be added to the Attributes dictionary.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateStackRequest WithAttributes(params KeyValuePair<string, string>[] pairs)
{
foreach (KeyValuePair<string, string> pair in pairs)
{
this.Attributes[pair.Key] = pair.Value;
}
return this;
}
// Check to see if Attributes property is set
internal bool IsSetAttributes()
{
return this.attributes != null;
}
/// <summary>
/// The stack AWS Identity and Access Management (IAM) role, which allows AWS OpsWorks to work with AWS resources on your behalf. You must set
/// this parameter to the Amazon Resource Name (ARN) for an existing IAM role. For more information about IAM ARNs, see <a
/// href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html">Using Identifiers</a>.
///
/// </summary>
public string ServiceRoleArn
{
get { return this.serviceRoleArn; }
set { this.serviceRoleArn = value; }
}
/// <summary>
/// Sets the ServiceRoleArn property
/// </summary>
/// <param name="serviceRoleArn">The value to set for the ServiceRoleArn property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateStackRequest WithServiceRoleArn(string serviceRoleArn)
{
this.serviceRoleArn = serviceRoleArn;
return this;
}
// Check to see if ServiceRoleArn property is set
internal bool IsSetServiceRoleArn()
{
return this.serviceRoleArn != null;
}
/// <summary>
/// The ARN of an IAM profile that is the default profile for all of the stack's EC2 instances. For more information about IAM ARNs, see <a
/// href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html">Using Identifiers</a>.
///
/// </summary>
public string DefaultInstanceProfileArn
{
get { return this.defaultInstanceProfileArn; }
set { this.defaultInstanceProfileArn = value; }
}
/// <summary>
/// Sets the DefaultInstanceProfileArn property
/// </summary>
/// <param name="defaultInstanceProfileArn">The value to set for the DefaultInstanceProfileArn property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateStackRequest WithDefaultInstanceProfileArn(string defaultInstanceProfileArn)
{
this.defaultInstanceProfileArn = defaultInstanceProfileArn;
return this;
}
// Check to see if DefaultInstanceProfileArn property is set
internal bool IsSetDefaultInstanceProfileArn()
{
return this.defaultInstanceProfileArn != null;
}
/// <summary>
/// The stack's default operating system, which must be set to <c>Amazon Linux</c> or <c>Ubuntu 12.04 LTS</c>. The default option is <c>Amazon
/// Linux</c>.
///
/// </summary>
public string DefaultOs
{
get { return this.defaultOs; }
set { this.defaultOs = value; }
}
/// <summary>
/// Sets the DefaultOs property
/// </summary>
/// <param name="defaultOs">The value to set for the DefaultOs property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateStackRequest WithDefaultOs(string defaultOs)
{
this.defaultOs = defaultOs;
return this;
}
// Check to see if DefaultOs property is set
internal bool IsSetDefaultOs()
{
return this.defaultOs != null;
}
/// <summary>
/// The stack's host name theme, with spaces are replaced by underscores. The theme is used to generate host names for the stack's instances. By
/// default, <c>HostnameTheme</c> is set to Layer_Dependent, which creates host names by appending integers to the layer's short name. The other
/// themes are: <ul> <li>Baked_Goods</li> <li>Clouds</li> <li>European_Cities</li> <li>Fruits</li> <li>Greek_Deities</li>
/// <li>Legendary_Creatures_from_Japan</li> <li>Planets_and_Moons</li> <li>Roman_Deities</li> <li>Scottish_Islands</li> <li>US_Cities</li>
/// <li>Wild_Cats</li> </ul> To obtain a generated host name, call <c>GetHostNameSuggestion</c>, which returns a host name based on the current
/// theme.
///
/// </summary>
public string HostnameTheme
{
get { return this.hostnameTheme; }
set { this.hostnameTheme = value; }
}
/// <summary>
/// Sets the HostnameTheme property
/// </summary>
/// <param name="hostnameTheme">The value to set for the HostnameTheme property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateStackRequest WithHostnameTheme(string hostnameTheme)
{
this.hostnameTheme = hostnameTheme;
return this;
}
// Check to see if HostnameTheme property is set
internal bool IsSetHostnameTheme()
{
return this.hostnameTheme != null;
}
/// <summary>
/// The stack's default Availability Zone, which must be in the specified region. For more information, see <a
/// href="http://docs.aws.amazon.com/general/latest/gr/rande.html">Regions and Endpoints</a>. If you also specify a value for
/// <c>DefaultSubnetId</c>, the subnet must be in the same zone. For more information, see the <c>VpcId</c> parameter description.
///
/// </summary>
public string DefaultAvailabilityZone
{
get { return this.defaultAvailabilityZone; }
set { this.defaultAvailabilityZone = value; }
}
/// <summary>
/// Sets the DefaultAvailabilityZone property
/// </summary>
/// <param name="defaultAvailabilityZone">The value to set for the DefaultAvailabilityZone property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateStackRequest WithDefaultAvailabilityZone(string defaultAvailabilityZone)
{
this.defaultAvailabilityZone = defaultAvailabilityZone;
return this;
}
// Check to see if DefaultAvailabilityZone property is set
internal bool IsSetDefaultAvailabilityZone()
{
return this.defaultAvailabilityZone != null;
}
/// <summary>
/// The stack's default subnet ID. All instances will be launched into this subnet unless you specify otherwise when you create the instance. If
/// you also specify a value for <c>DefaultAvailabilityZone</c>, the subnet must be in that zone. For information on default values and when
/// this parameter is required, see the <c>VpcId</c> parameter description.
///
/// </summary>
public string DefaultSubnetId
{
get { return this.defaultSubnetId; }
set { this.defaultSubnetId = value; }
}
/// <summary>
/// Sets the DefaultSubnetId property
/// </summary>
/// <param name="defaultSubnetId">The value to set for the DefaultSubnetId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateStackRequest WithDefaultSubnetId(string defaultSubnetId)
{
this.defaultSubnetId = defaultSubnetId;
return this;
}
// Check to see if DefaultSubnetId property is set
internal bool IsSetDefaultSubnetId()
{
return this.defaultSubnetId != null;
}
/// <summary>
/// A string that contains user-defined, custom JSON. It is used to override the corresponding default stack configuration JSON values. The
/// string should be in the following format and must escape characters such as '"'.: <c>"{\"key1\": \"value1\", \"key2\": \"value2\",...}"</c>
/// For more information on custom JSON, see <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-json.html">Use Custom
/// JSON to Modify the Stack Configuration JSON</a>.
///
/// </summary>
public string CustomJson
{
get { return this.customJson; }
set { this.customJson = value; }
}
/// <summary>
/// Sets the CustomJson property
/// </summary>
/// <param name="customJson">The value to set for the CustomJson property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateStackRequest WithCustomJson(string customJson)
{
this.customJson = customJson;
return this;
}
// Check to see if CustomJson property is set
internal bool IsSetCustomJson()
{
return this.customJson != null;
}
/// <summary>
/// The configuration manager. When you create a stack we recommend that you use the configuration manager to specify the Chef version, 0.9 or
/// 11.4. The default value is currently 0.9. However, we expect to change the default value to 11.4 in late August 2013.
///
/// </summary>
public StackConfigurationManager ConfigurationManager
{
get { return this.configurationManager; }
set { this.configurationManager = value; }
}
/// <summary>
/// Sets the ConfigurationManager property
/// </summary>
/// <param name="configurationManager">The value to set for the ConfigurationManager property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateStackRequest WithConfigurationManager(StackConfigurationManager configurationManager)
{
this.configurationManager = configurationManager;
return this;
}
// Check to see if ConfigurationManager property is set
internal bool IsSetConfigurationManager()
{
return this.configurationManager != null;
}
/// <summary>
/// Whether the stack uses custom cookbooks.
///
/// </summary>
public bool UseCustomCookbooks
{
get { return this.useCustomCookbooks ?? default(bool); }
set { this.useCustomCookbooks = value; }
}
/// <summary>
/// Sets the UseCustomCookbooks property
/// </summary>
/// <param name="useCustomCookbooks">The value to set for the UseCustomCookbooks property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateStackRequest WithUseCustomCookbooks(bool useCustomCookbooks)
{
this.useCustomCookbooks = useCustomCookbooks;
return this;
}
// Check to see if UseCustomCookbooks property is set
internal bool IsSetUseCustomCookbooks()
{
return this.useCustomCookbooks.HasValue;
}
/// <summary>
/// Contains the information required to retrieve an app or cookbook from a repository. For more information, see <a
/// href="http://docs.aws.amazon.com/opsworks/latest/userguide/workingapps-creating.html">Creating Apps</a> or <a
/// href="http://docs.aws.amazon.com/opsworks/latest/userguide/workingcookbook.html">Custom Recipes and Cookbooks</a>.
///
/// </summary>
public Source CustomCookbooksSource
{
get { return this.customCookbooksSource; }
set { this.customCookbooksSource = value; }
}
/// <summary>
/// Sets the CustomCookbooksSource property
/// </summary>
/// <param name="customCookbooksSource">The value to set for the CustomCookbooksSource property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateStackRequest WithCustomCookbooksSource(Source customCookbooksSource)
{
this.customCookbooksSource = customCookbooksSource;
return this;
}
// Check to see if CustomCookbooksSource property is set
internal bool IsSetCustomCookbooksSource()
{
return this.customCookbooksSource != null;
}
/// <summary>
/// A default SSH key for the stack instances. You can override this value when you create or update an instance.
///
/// </summary>
public string DefaultSshKeyName
{
get { return this.defaultSshKeyName; }
set { this.defaultSshKeyName = value; }
}
/// <summary>
/// Sets the DefaultSshKeyName property
/// </summary>
/// <param name="defaultSshKeyName">The value to set for the DefaultSshKeyName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateStackRequest WithDefaultSshKeyName(string defaultSshKeyName)
{
this.defaultSshKeyName = defaultSshKeyName;
return this;
}
// Check to see if DefaultSshKeyName property is set
internal bool IsSetDefaultSshKeyName()
{
return this.defaultSshKeyName != null;
}
/// <summary>
/// The default root device type. This value is used by default for all instances in the cloned stack, but you can override it when you create
/// an instance. For more information, see <a
/// href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ComponentsAMIs.html#storage-for-the-root-device">Storage for the Root Device</a>.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Allowed Values</term>
/// <description>ebs, instance-store</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string DefaultRootDeviceType
{
get { return this.defaultRootDeviceType; }
set { this.defaultRootDeviceType = value; }
}
/// <summary>
/// Sets the DefaultRootDeviceType property
/// </summary>
/// <param name="defaultRootDeviceType">The value to set for the DefaultRootDeviceType property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateStackRequest WithDefaultRootDeviceType(string defaultRootDeviceType)
{
this.defaultRootDeviceType = defaultRootDeviceType;
return this;
}
// Check to see if DefaultRootDeviceType property is set
internal bool IsSetDefaultRootDeviceType()
{
return this.defaultRootDeviceType != null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Text;
namespace Microsoft.DotNet.Build.Tasks
{
public class GenerateResourcesCode : Task
{
private TargetLanguage _targetLanguage = TargetLanguage.CSharp;
private StreamWriter _targetStream;
private StringBuilder _debugCode = new StringBuilder();
private Dictionary<string, int> _keys;
private String _resourcesName;
[Required]
public string ResxFilePath { get; set; }
[Required]
public string OutputSourceFilePath { get; set; }
[Required]
public string AssemblyName { get; set; }
public bool DebugOnly { get; set; }
public override bool Execute()
{
try
{
_resourcesName = "FxResources." + AssemblyName;
using (_targetStream = File.CreateText(OutputSourceFilePath))
{
if (String.Equals(Path.GetExtension(OutputSourceFilePath), ".vb", StringComparison.OrdinalIgnoreCase))
{
_targetLanguage = TargetLanguage.VB;
}
_keys = new Dictionary<string, int>();
WriteClassHeader();
RunOnResFile();
WriteDebugCode();
WriteGetTypeProperty();
WriteClassEnd();
WriteResourceTypeClass();
}
}
catch (Exception e)
{
Log.LogError("Failed to generate the resource code with error:\n" + e.Message);
return false; // fail the task
}
return true;
}
private void WriteClassHeader()
{
string commentPrefix = _targetLanguage == TargetLanguage.CSharp ? "// " : "' ";
_targetStream.WriteLine(commentPrefix + "Do not edit this file manually it is auto-generated during the build based on the .resx file for this project.");
if (_targetLanguage == TargetLanguage.CSharp)
{
_targetStream.WriteLine("namespace System");
_targetStream.WriteLine("{");
_targetStream.WriteLine(" internal static partial class SR");
_targetStream.WriteLine(" {");
_targetStream.WriteLine("#pragma warning disable 0414");
_targetStream.WriteLine(" private const string s_resourcesName = \"{0}\";", _resourcesName + ".SR");
_targetStream.WriteLine("#pragma warning restore 0414");
_targetStream.WriteLine("");
if (!DebugOnly)
_targetStream.WriteLine("#if !DEBUGRESOURCES");
}
else
{
_targetStream.WriteLine("Namespace System");
_targetStream.WriteLine(" Friend Partial Class SR");
_targetStream.WriteLine(" ");
_targetStream.WriteLine(" Private Const s_resourcesName As String = \"{0}\"", _resourcesName + ".SR");
_targetStream.WriteLine("");
if (!DebugOnly)
_targetStream.WriteLine("#If Not DEBUGRESOURCES Then");
}
}
private void RunOnResFile()
{
foreach(KeyValuePair<string, string> pair in GetResources(ResxFilePath))
{
StoreValues((string)pair.Key, (string)pair.Value);
}
}
private void StoreValues(string leftPart, string rightPart)
{
int value;
if (_keys.TryGetValue(leftPart, out value))
{
return;
}
_keys[leftPart] = 0;
StringBuilder sb = new StringBuilder(rightPart.Length);
for (var i = 0; i < rightPart.Length; i++)
{
// duplicate '"' for VB and C#
if (rightPart[i] == '\"' && (_targetLanguage == TargetLanguage.VB || _targetLanguage == TargetLanguage.CSharp))
{
sb.Append("\"");
}
sb.Append(rightPart[i]);
}
if (_targetLanguage == TargetLanguage.CSharp)
{
_debugCode.AppendFormat(" internal static string {0} {2}{4} get {2} return SR.GetResourceString(\"{0}\", @\"{1}\"); {3}{4} {3}{4}", leftPart, sb.ToString(), "{", "}", Environment.NewLine);
}
else
{
_debugCode.AppendFormat(" Friend Shared ReadOnly Property {0} As String{2} Get{2} Return SR.GetResourceString(\"{0}\", \"{1}\"){2} End Get{2} End Property{2}", leftPart, sb.ToString(), Environment.NewLine);
}
if (!DebugOnly)
{
if (_targetLanguage == TargetLanguage.CSharp)
{
_targetStream.WriteLine(" internal static string {0} {2}{4} get {2} return SR.GetResourceString(\"{0}\", {1}); {3}{4} {3}", leftPart, "null", "{", "}", Environment.NewLine);
}
else
{
_targetStream.WriteLine(" Friend Shared ReadOnly Property {0} As String{2} Get{2} Return SR.GetResourceString(\"{0}\", {1}){2} End Get{2} End Property", leftPart, "Nothing", Environment.NewLine);
}
}
}
private void WriteDebugCode()
{
if (_targetLanguage == TargetLanguage.CSharp)
{
if (!DebugOnly)
_targetStream.WriteLine("#else");
_targetStream.WriteLine(_debugCode.ToString());
if (!DebugOnly)
_targetStream.WriteLine("#endif");
}
else
{
if (!DebugOnly)
_targetStream.WriteLine("#Else");
_targetStream.WriteLine(_debugCode.ToString());
if (!DebugOnly)
_targetStream.WriteLine("#End If");
}
}
private void WriteGetTypeProperty()
{
if (_targetLanguage == TargetLanguage.CSharp)
{
_targetStream.WriteLine(" internal static Type ResourceType {1}{3} get {1} return typeof({0}); {2}{3} {2}", _resourcesName + ".SR", "{", "}", Environment.NewLine);
}
else
{
_targetStream.WriteLine(" Friend Shared ReadOnly Property ResourceType As Type{1} Get{1} Return GetType({0}){1} End Get{1} End Property", _resourcesName + ".SR", Environment.NewLine);
}
}
private void WriteClassEnd()
{
if (_targetLanguage == TargetLanguage.CSharp)
{
_targetStream.WriteLine(" }");
_targetStream.WriteLine("}");
}
else
{
_targetStream.WriteLine(" End Class");
_targetStream.WriteLine("End Namespace");
}
}
private void WriteResourceTypeClass()
{
if (_targetLanguage == TargetLanguage.CSharp)
{
_targetStream.WriteLine("namespace {0}", _resourcesName);
_targetStream.WriteLine("{");
_targetStream.WriteLine(" // The type of this class is used to create the ResourceManager instance as the type name matches the name of the embedded resources file");
_targetStream.WriteLine(" internal static class SR");
_targetStream.WriteLine(" {");
_targetStream.WriteLine(" }");
_targetStream.WriteLine("}");
}
else
{
_targetStream.WriteLine("Namespace {0}", _resourcesName);
_targetStream.WriteLine(" ' The type of this class is used to create the ResourceManager instance as the type name matches the name of the embedded resources file");
_targetStream.WriteLine(" Friend Class SR");
_targetStream.WriteLine(" ");
_targetStream.WriteLine(" End Class");
_targetStream.WriteLine("End Namespace");
}
}
private enum TargetLanguage
{
CSharp, VB
}
internal static IEnumerable<KeyValuePair<string, string>> GetResources(string fileName)
{
XDocument doc = XDocument.Load(fileName, LoadOptions.PreserveWhitespace);
foreach (XElement dataElem in doc.Element("root").Elements("data"))
{
string name = dataElem.Attribute("name").Value;
string value = dataElem.Element("value").Value;
yield return new KeyValuePair<string, string>(name, value);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Newtonsoft.Json.Linq;
using NuGet.Client.Installation;
using NuGet.Client.Resolution;
using NuGet.Versioning;
using NuGet.VisualStudio;
using NuGetConsole;
using Resx = NuGet.Client.VisualStudio.UI.Resources;
namespace NuGet.Client.VisualStudio.UI
{
/// <summary>
/// Interaction logic for PackageManagerControl.xaml
/// </summary>
public partial class PackageManagerControl : UserControl
{
private const int PageSize = 10;
// Copied from file Constants.cs in NuGet.Core:
// This is temporary until we fix the gallery to have proper first class support for this.
// The magic unpublished date is 1900-01-01T00:00:00
public static readonly DateTimeOffset Unpublished = new DateTimeOffset(1900, 1, 1, 0, 0, 0, TimeSpan.FromHours(-8));
private bool _initialized;
// used to prevent starting new search when we update the package sources
// list in response to PackageSourcesChanged event.
private bool _dontStartNewSearch;
private int _busyCount;
public PackageManagerModel Model { get; private set; }
public SourceRepositoryManager Sources
{
get
{
return Model.Sources;
}
}
public InstallationTarget Target
{
get
{
return Model.Target;
}
}
private IConsole _outputConsole;
internal IUserInterfaceService UI { get; private set; }
private PackageRestoreBar _restoreBar;
private IPackageRestoreManager _packageRestoreManager;
public PackageManagerControl(PackageManagerModel model, IUserInterfaceService ui)
{
UI = ui;
Model = model;
InitializeComponent();
_searchControl.Text = model.SearchText;
_filter.Items.Add(Resx.Resources.Filter_All);
_filter.Items.Add(Resx.Resources.Filter_Installed);
_filter.Items.Add(Resx.Resources.Filter_UpdateAvailable);
// TODO: Relocate to v3 API.
_packageRestoreManager = ServiceLocator.GetInstance<IPackageRestoreManager>();
AddRestoreBar();
_packageDetail.Visibility = System.Windows.Visibility.Collapsed;
_packageDetail.Control = this;
_packageSolutionDetail.Visibility = System.Windows.Visibility.Collapsed;
_packageSolutionDetail.Control = this;
_busyCount = 0;
if (Target.IsSolution)
{
_packageSolutionDetail.Visibility = System.Windows.Visibility.Visible;
}
else
{
_packageDetail.Visibility = System.Windows.Visibility.Visible;
}
var outputConsoleProvider = ServiceLocator.GetInstance<IOutputConsoleProvider>();
_outputConsole = outputConsoleProvider.CreateOutputConsole(requirePowerShellHost: false);
InitSourceRepoList();
this.Unloaded += PackageManagerControl_Unloaded;
_initialized = true;
Model.Sources.PackageSourcesChanged += Sources_PackageSourcesChanged;
}
// Set the PackageStatus property of the given package.
private static void SetPackageStatus(
UiSearchResultPackage package,
InstallationTarget target)
{
var latestStableVersion = package.AllVersions
.Where(p => !p.Version.IsPrerelease)
.Max(p => p.Version);
// Get the minimum version installed in any target project/solution
var minimumInstalledPackage = target.GetAllTargetsRecursively()
.Select(t => t.InstalledPackages.GetInstalledPackage(Id))
.Where(p => p != null)
.OrderBy(r => r.Identity.Version)
.FirstOrDefault();
PackageStatus status;
if (minimumInstalledPackage != null)
{
if (minimumInstalledPackage.Identity.Version < latestStableVersion)
{
status = PackageStatus.UpdateAvailable;
}
else
{
status = PackageStatus.Installed;
}
}
else
{
status = PackageStatus.NotInstalled;
}
}
private void Sources_PackageSourcesChanged(object sender, EventArgs e)
{
package.Status = status;
if (!Target.IsSolution)
{
var installedPackage = Target.InstalledPackages.GetInstalledPackage(Id);
var installedVersion = installedPackage == null ? null : installedPackage.Identity.Version;
_packageDetail.DataContext = new PackageDetailControlModel(selectedPackage, installedVersion);
}
else
{
_packageSolutionDetail.DataContext = new PackageSolutionDetailControlModel(selectedPackage, (VsSolution)Target);
}
// Set _dontStartNewSearch to true to prevent a new search started in
// _sourceRepoList_SelectionChanged(). This method will start the new
// search when needed by itself.
_dontStartNewSearch = true;
try
{
var oldActiveSource = _sourceRepoList.SelectedItem as PackageSource;
var newSources = new List<PackageSource>(Sources.AvailableSources);
// Update the source repo list with the new value.
_sourceRepoList.Items.Clear();
foreach (var source in newSources)
{
_sourceRepoList.Items.Add(source);
}
if (oldActiveSource != null && newSources.Contains(oldActiveSource))
{
// active source is not changed. Set _dontStartNewSearch to true
// to prevent a new search when _sourceRepoList.SelectedItem is set.
_sourceRepoList.SelectedItem = oldActiveSource;
}
else
{
// active source changed.
_sourceRepoList.SelectedItem =
newSources.Count > 0 ?
newSources[0] :
null;
// start search explicitly.
SearchPackageInActivePackageSource();
}
}
finally
{
_dontStartNewSearch = false;
}
}
private void PackageManagerControl_Unloaded(object sender, RoutedEventArgs e)
{
RemoveRestoreBar();
}
private void AddRestoreBar()
{
_restoreBar = new PackageRestoreBar(_packageRestoreManager);
_root.Children.Add(_restoreBar);
_packageRestoreManager.PackagesMissingStatusChanged += packageRestoreManager_PackagesMissingStatusChanged;
}
private void RemoveRestoreBar()
{
_restoreBar.CleanUp();
_packageRestoreManager.PackagesMissingStatusChanged -= packageRestoreManager_PackagesMissingStatusChanged;
}
private void packageRestoreManager_PackagesMissingStatusChanged(object sender, PackagesMissingStatusEventArgs e)
{
// PackageRestoreManager fires this event even when solution is closed.
// Don't do anything if solution is closed.
if (!Target.IsAvailable)
{
return;
}
if (!e.PackagesMissing)
{
// packages are restored. Update the UI
if (Target.IsSolution)
{
// TODO: update UI here
}
else
{
// TODO: update UI here
}
}
}
private void InitSourceRepoList()
{
_label.Text = string.Format(
CultureInfo.CurrentCulture,
Resx.Resources.Label_PackageManager,
Target.Name);
// init source repo list
_sourceRepoList.Items.Clear();
foreach (var source in Sources.AvailableSources)
{
_sourceRepoList.Items.Add(source);
}
if (Sources.ActiveRepository != null)
{
_sourceRepoList.SelectedItem = Sources.ActiveRepository.Source;
}
}
private void SetBusy(bool busy)
{
if (busy)
{
_busyCount++;
if (_busyCount > 0)
{
_busyControl.Visibility = System.Windows.Visibility.Visible;
this.IsEnabled = false;
}
}
else
{
_busyCount--;
if (_busyCount <= 0)
{
_busyControl.Visibility = System.Windows.Visibility.Collapsed;
this.IsEnabled = true;
}
}
}
private class PackageLoaderOption
{
public bool IncludePrerelease { get; set; }
public bool ShowUpdatesAvailable { get; set; }
}
private class PackageLoader : ILoader
{
// where to get the package list
private Func<int, CancellationToken, Task<IEnumerable<JObject>>> _loader;
private InstallationTarget _target;
private PackageLoaderOption _option;
public PackageLoader(
Func<int, CancellationToken, Task<IEnumerable<JObject>>> loader,
InstallationTarget target,
PackageLoaderOption option,
string searchText)
{
_loader = loader;
_target = target;
_option = option;
LoadingMessage = string.IsNullOrWhiteSpace(searchText) ?
Resx.Resources.Text_Loading :
string.Format(
CultureInfo.CurrentCulture,
Resx.Resources.Text_Searching,
searchText);
}
public string LoadingMessage
{
get;
private set;
}
private Task<List<JObject>> InternalLoadItems(
int startIndex,
CancellationToken ct,
Func<int, CancellationToken, Task<IEnumerable<JObject>>> loader)
{
return Task.Factory.StartNew(() =>
{
var r1 = _loader(startIndex, ct);
return r1.Result.ToList();
});
}
private UiDetailedPackage ToDetailedPackage(UiSearchResultPackage package)
{
var detailedPackage = new UiDetailedPackage();
detailedPackage.Id = package.Id;
detailedPackage.Version = package.Version;
detailedPackage.Summary = package.Summary;
return detailedPackage;
}
public async Task<LoadResult> LoadItems(int startIndex, CancellationToken ct)
{
var results = await InternalLoadItems(startIndex, ct, _loader);
List<UiSearchResultPackage> packages = new List<UiSearchResultPackage>();
foreach (var package in results)
{
ct.ThrowIfCancellationRequested();
// As a debugging aide, I am intentionally NOT using an object initializer -anurse
var searchResultPackage = new UiSearchResultPackage();
searchResultPackage.Id = package.Value<string>(Properties.PackageId);
searchResultPackage.Version = NuGetVersion.Parse(package.Value<string>(Properties.LatestVersion));
if (searchResultPackage.Version.IsPrerelease && !_option.IncludePrerelease)
{
// don't include prerelease version if includePrerelease is false
continue;
}
searchResultPackage.IconUrl = GetUri(package, Properties.IconUrl);
var allVersions = LoadVersions(
package.Value<JArray>(Properties.Packages),
searchResultPackage.Version);
if (!allVersions.Select(v => v.Version).Contains(searchResultPackage.Version))
{
// make sure allVersions contains searchResultPackage itself.
allVersions.Add(ToDetailedPackage(searchResultPackage));
}
searchResultPackage.AllVersions = allVersions;
SetPackageStatus(searchResultPackage, _target);
if (_option.ShowUpdatesAvailable &&
searchResultPackage.Status != PackageStatus.UpdateAvailable)
{
continue;
}
searchResultPackage.Summary = package.Value<string>(Properties.Summary);
if (string.IsNullOrWhiteSpace(searchResultPackage.Summary))
{
// summary is empty. Use its description instead.
var self = searchResultPackage.AllVersions.FirstOrDefault(p => p.Version == searchResultPackage.Version);
if (self != null)
{
searchResultPackage.Summary = self.Description;
}
}
packages.Add(searchResultPackage);
}
ct.ThrowIfCancellationRequested();
return new LoadResult()
{
Items = packages,
HasMoreItems = packages.Count == PageSize
};
}
// Get all versions of the package
private List<UiDetailedPackage> LoadVersions(JArray versions, NuGetVersion searchResultVersion)
{
var retValue = new List<UiDetailedPackage>();
// If repo is AggregateRepository, the package duplicates can be returned by
// FindPackagesById(), so Distinct is needed here to remove the duplicates.
foreach (var token in versions)
{
Debug.Assert(token.Type == JTokenType.Object);
JObject version = (JObject)token;
var detailedPackage = new UiDetailedPackage();
detailedPackage.Id = version.Value<string>(Properties.PackageId);
detailedPackage.Version = NuGetVersion.Parse(version.Value<string>(Properties.Version));
if (detailedPackage.Version.IsPrerelease &&
!_option.IncludePrerelease &&
detailedPackage.Version != searchResultVersion)
{
// don't include prerelease version if includePrerelease is false
continue;
}
string publishedStr = version.Value<string>(Properties.Published);
if (!String.IsNullOrEmpty(publishedStr))
{
detailedPackage.Published = DateTime.Parse(publishedStr);
if (detailedPackage.Published <= Unpublished &&
detailedPackage.Version != searchResultVersion)
{
// don't include unlisted package
continue;
}
}
detailedPackage.Summary = version.Value<string>(Properties.Summary);
detailedPackage.Description = version.Value<string>(Properties.Description);
detailedPackage.Authors = version.Value<string>(Properties.Authors);
detailedPackage.Owners = version.Value<string>(Properties.Owners);
detailedPackage.IconUrl = GetUri(version, Properties.IconUrl);
detailedPackage.LicenseUrl = GetUri(version, Properties.LicenseUrl);
detailedPackage.ProjectUrl = GetUri(version, Properties.ProjectUrl);
detailedPackage.Tags = String.Join(" ", (version.Value<JArray>(Properties.Tags) ?? Enumerable.Empty<JToken>()).Select(t => t.ToString()));
detailedPackage.DownloadCount = version.Value<int>(Properties.DownloadCount);
detailedPackage.DependencySets = (version.Value<JArray>(Properties.DependencyGroups) ?? Enumerable.Empty<JToken>()).Select(obj => LoadDependencySet((JObject)obj));
detailedPackage.HasDependencies = detailedPackage.DependencySets.Any(
set => set.Dependencies != null && set.Dependencies.Count > 0);
retValue.Add(detailedPackage);
}
return retValue;
}
private Uri GetUri(JObject json, string property)
{
if (json[property] == null)
{
return null;
}
string str = json[property].ToString();
if (String.IsNullOrEmpty(str))
{
return null;
}
return new Uri(str);
}
private UiPackageDependencySet LoadDependencySet(JObject set)
{
var fxName = set.Value<string>(Properties.TargetFramework);
return new UiPackageDependencySet(
String.IsNullOrEmpty(fxName) ? null : FrameworkNameHelper.ParsePossiblyShortenedFrameworkName(fxName),
(set.Value<JArray>(Properties.Dependencies) ?? Enumerable.Empty<JToken>()).Select(obj => LoadDependency((JObject)obj)));
}
private UiPackageDependency LoadDependency(JObject dep)
{
var ver = dep.Value<string>(Properties.Range);
return new UiPackageDependency(
dep.Value<string>(Properties.PackageId),
String.IsNullOrEmpty(ver) ? null : VersionRange.Parse(ver));
}
private string StringCollectionToString(JArray v)
{
if (v == null)
{
return null;
}
string retValue = String.Join(", ", v.Select(t => t.ToString()));
if (retValue == String.Empty)
{
return null;
}
return retValue;
}
}
private bool ShowInstalled
{
get
{
return Resx.Resources.Filter_Installed.Equals(_filter.SelectedItem);
}
}
private bool ShowUpdatesAvailable
{
get
{
return Resx.Resources.Filter_UpdateAvailable.Equals(_filter.SelectedItem);
}
}
public bool IncludePrerelease
{
get
{
return _checkboxPrerelease.IsChecked == true;
}
}
internal SourceRepository CreateActiveRepository()
{
var activeSource = _sourceRepoList.SelectedItem as PackageSource;
if (activeSource == null)
{
return null;
}
return Sources.CreateSourceRepository(activeSource);
}
private void SearchPackageInActivePackageSource()
{
var searchText = _searchControl.Text;
var supportedFrameworks = Target.GetSupportedFrameworks();
// search online
var activeSource = _sourceRepoList.SelectedItem as PackageSource;
var sourceRepository = Sources.CreateSourceRepository(activeSource);
PackageLoaderOption option = new PackageLoaderOption()
{
IncludePrerelease = this.IncludePrerelease,
ShowUpdatesAvailable = this.ShowUpdatesAvailable
};
if (ShowInstalled || ShowUpdatesAvailable)
{
// search installed packages
var loader = new PackageLoader(
(startIndex, ct) =>
Target.SearchInstalled(
sourceRepository,
searchText,
startIndex,
PageSize,
ct),
Target,
option,
searchText);
_packageList.Loader = loader;
}
else
{
// search in active package source
if (activeSource == null)
{
var loader = new PackageLoader(
(startIndex, ct) =>
{
return Task.Factory.StartNew(() =>
{
return Enumerable.Empty<JObject>();
});
},
Target,
option,
searchText);
_packageList.Loader = loader;
}
else
{
var loader = new PackageLoader(
(startIndex, ct) =>
sourceRepository.Search(
searchText,
new SearchFilter()
{
SupportedFrameworks = supportedFrameworks,
IncludePrerelease = option.IncludePrerelease
},
startIndex,
PageSize,
ct),
Target,
option,
searchText);
_packageList.Loader = loader;
}
}
}
private void SettingsButtonClick(object sender, RoutedEventArgs e)
{
UI.LaunchNuGetOptionsDialog();
}
private void PackageList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
UpdateDetailPane();
}
/// <summary>
/// Updates the detail pane based on the selected package
/// </summary>
private void UpdateDetailPane()
{
var selectedPackage = _packageList.SelectedItem as UiSearchResultPackage;
if (selectedPackage == null)
{
_packageDetail.DataContext = null;
_packageSolutionDetail.DataContext = null;
}
else
{
if (!Target.IsSolution)
{
var installedPackage = Target.InstalledPackages.GetInstalledPackage(selectedPackage.Id);
var installedVersion = installedPackage == null ? null : installedPackage.Identity.Version;
_packageDetail.DataContext = new PackageDetailControlModel(selectedPackage, installedVersion);
}
else
{
_packageSolutionDetail.DataContext = new PackageSolutionDetailControlModel(selectedPackage, (VsSolution)Target);
}
}
}
private void _sourceRepoList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_dontStartNewSearch)
{
return;
}
var newSource = _sourceRepoList.SelectedItem as PackageSource;
if (newSource != null)
{
Sources.ChangeActiveSource(newSource);
}
SearchPackageInActivePackageSource();
}
private void _filter_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_initialized)
{
SearchPackageInActivePackageSource();
}
}
internal void UpdatePackageStatus()
{
if (ShowInstalled || ShowUpdatesAvailable)
{
// refresh the whole package list
_packageList.Reload();
}
else
{
// in this case, we only need to update PackageStatus of
// existing items in the package list
foreach (var item in _packageList.Items)
{
var package = item as UiSearchResultPackage;
if (package == null)
{
continue;
}
SetPackageStatus(package, Target);
}
}
}
public bool ShowLicenseAgreement(IEnumerable<PackageAction> operations)
{
var licensePackages = operations.Where(op =>
op.ActionType == PackageActionType.Install &&
op.Package.Value<bool>("requireLicenseAcceptance"));
// display license window if necessary
if (licensePackages.Any())
{
// Hacky distinct without writing a custom comparer
var licenseModels = licensePackages
.GroupBy(a => Tuple.Create(a.Package["id"], a.Package["version"]))
.Select(g =>
{
dynamic p = g.First().Package;
string licenseUrl = (string)p.licenseUrl;
string id = (string)p.id;
string authors = (string)p.authors;
return new PackageLicenseInfo(
id,
licenseUrl == null ? null : new Uri(licenseUrl),
authors);
})
.Where(pli => pli.LicenseUrl != null); // Shouldn't get nulls, but just in case
bool accepted = this.UI.PromptForLicenseAcceptance(licenseModels);
if (!accepted)
{
return false;
}
}
return true;
}
private void PreviewActions(IEnumerable<PackageAction> actions)
{
var w = new PreviewWindow();
w.DataContext = new PreviewWindowModel(actions, Target);
w.ShowModal();
}
// preview user selected action
internal async void Preview(IDetailControl detailControl)
{
SetBusy(true);
try
{
_outputConsole.Clear();
var actions = await detailControl.ResolveActionsAsync();
PreviewActions(actions);
}
catch (Exception ex)
{
var errorDialog = new ErrorReportingDialog(
ex.Message,
ex.ToString());
errorDialog.ShowModal();
}
finally
{
SetBusy(false);
}
}
// perform the user selected action
internal async void PerformAction(IDetailControl detailControl)
{
SetBusy(true);
_outputConsole.Clear();
var progressDialog = new ProgressDialog(_outputConsole);
progressDialog.Owner = Window.GetWindow(this);
progressDialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;
try
{
var actions = await detailControl.ResolveActionsAsync();
// show license agreeement
bool acceptLicense = ShowLicenseAgreement(actions);
if (!acceptLicense)
{
return;
}
// Create the executor and execute the actions
progressDialog.FileConflictAction = detailControl.FileConflictAction;
progressDialog.Show();
var executor = new ActionExecutor();
await executor.ExecuteActionsAsync(actions, logger: progressDialog, cancelToken: CancellationToken.None);
UpdatePackageStatus();
detailControl.Refresh();
}
catch (Exception ex)
{
var errorDialog = new ErrorReportingDialog(
ex.Message,
ex.ToString());
errorDialog.ShowModal();
}
finally
{
progressDialog.RequestToClose();
SetBusy(false);
}
}
private void _searchControl_SearchStart(object sender, EventArgs e)
{
if (!_initialized)
{
return;
}
SearchPackageInActivePackageSource();
}
private void _checkboxPrerelease_CheckChanged(object sender, RoutedEventArgs e)
{
if (!_initialized)
{
return;
}
SearchPackageInActivePackageSource();
}
}
}
| |
/*
* Copyright (c) 2006-2014, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org 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 OpenMetaverse.Packets;
namespace OpenMetaverse
{
[Serializable]
public class TerrainPatch
{
#region Enums and Structs
public enum LayerType : byte
{
Land = 0x4C, // 'L'
LandExtended = 0x4D, // 'M'
Water = 0x57, // 'W'
WaterExtended = 0x57, // 'X'
Wind = 0x37, // '7'
WindExtended = 0x39, // '9'
Cloud = 0x38, // '8'
CloudExtended = 0x3A // ':'
}
public struct GroupHeader
{
public int Stride;
public int PatchSize;
public LayerType Type;
}
public struct Header
{
public float DCOffset;
public int Range;
public int QuantWBits;
public int PatchIDs;
public uint WordBits;
public int X
{
get { return PatchIDs >> 5; }
set { PatchIDs += (value << 5); }
}
public int Y
{
get { return PatchIDs & 0x1F; }
set { PatchIDs |= value & 0x1F; }
}
}
#endregion Enums and Structs
/// <summary>X position of this patch</summary>
public int X;
/// <summary>Y position of this patch</summary>
public int Y;
/// <summary>A 16x16 array of floats holding decompressed layer data</summary>
public float[] Data;
}
public static class TerrainCompressor
{
public const int PATCHES_PER_EDGE = 16;
public const int END_OF_PATCHES = 97;
private const float OO_SQRT2 = 0.7071067811865475244008443621049f;
private const int STRIDE = 264;
private const int ZERO_CODE = 0x0;
private const int ZERO_EOB = 0x2;
private const int POSITIVE_VALUE = 0x6;
private const int NEGATIVE_VALUE = 0x7;
private static readonly float[] DequantizeTable16 = new float[16 * 16];
private static readonly float[] DequantizeTable32 = new float[16 * 16];
private static readonly float[] CosineTable16 = new float[16 * 16];
//private static readonly float[] CosineTable32 = new float[16 * 16];
private static readonly int[] CopyMatrix16 = new int[16 * 16];
private static readonly int[] CopyMatrix32 = new int[16 * 16];
private static readonly float[] QuantizeTable16 = new float[16 * 16];
static TerrainCompressor()
{
// Initialize the decompression tables
BuildDequantizeTable16();
SetupCosines16();
BuildCopyMatrix16();
BuildQuantizeTable16();
}
public static LayerDataPacket CreateLayerDataPacket(TerrainPatch[] patches, TerrainPatch.LayerType type)
{
LayerDataPacket layer = new LayerDataPacket();
layer.LayerID.Type = (byte)type;
TerrainPatch.GroupHeader header = new TerrainPatch.GroupHeader();
header.Stride = STRIDE;
header.PatchSize = 16;
header.Type = type;
// Should be enough to fit even the most poorly packed data
byte[] data = new byte[patches.Length * 16 * 16 * 2];
BitPack bitpack = new BitPack(data, 0);
bitpack.PackBits(header.Stride, 16);
bitpack.PackBits(header.PatchSize, 8);
bitpack.PackBits((int)header.Type, 8);
for (int i = 0; i < patches.Length; i++)
CreatePatch(bitpack, patches[i].Data, patches[i].X, patches[i].Y);
bitpack.PackBits(END_OF_PATCHES, 8);
layer.LayerData.Data = new byte[bitpack.BytePos + 1];
Buffer.BlockCopy(bitpack.Data, 0, layer.LayerData.Data, 0, bitpack.BytePos + 1);
return layer;
}
/// <summary>
/// Creates a LayerData packet for compressed land data given a full
/// simulator heightmap and an array of indices of patches to compress
/// </summary>
/// <param name="heightmap">A 256 * 256 array of floating point values
/// specifying the height at each meter in the simulator</param>
/// <param name="patches">Array of indexes in the 16x16 grid of patches
/// for this simulator. For example if 1 and 17 are specified, patches
/// x=1,y=0 and x=1,y=1 are sent</param>
/// <returns></returns>
public static LayerDataPacket CreateLandPacket(float[] heightmap, int[] patches)
{
LayerDataPacket layer = new LayerDataPacket();
layer.LayerID.Type = (byte)TerrainPatch.LayerType.Land;
TerrainPatch.GroupHeader header = new TerrainPatch.GroupHeader();
header.Stride = STRIDE;
header.PatchSize = 16;
header.Type = TerrainPatch.LayerType.Land;
byte[] data = new byte[1536];
BitPack bitpack = new BitPack(data, 0);
bitpack.PackBits(header.Stride, 16);
bitpack.PackBits(header.PatchSize, 8);
bitpack.PackBits((int)header.Type, 8);
for (int i = 0; i < patches.Length; i++)
CreatePatchFromHeightmap(bitpack, heightmap, patches[i] % 16, (patches[i] - (patches[i] % 16)) / 16);
bitpack.PackBits(END_OF_PATCHES, 8);
layer.LayerData.Data = new byte[bitpack.BytePos + 1];
Buffer.BlockCopy(bitpack.Data, 0, layer.LayerData.Data, 0, bitpack.BytePos + 1);
return layer;
}
public static LayerDataPacket CreateLandPacket(float[] patchData, int x, int y)
{
LayerDataPacket layer = new LayerDataPacket();
layer.LayerID.Type = (byte)TerrainPatch.LayerType.Land;
TerrainPatch.GroupHeader header = new TerrainPatch.GroupHeader();
header.Stride = STRIDE;
header.PatchSize = 16;
header.Type = TerrainPatch.LayerType.Land;
byte[] data = new byte[1536];
BitPack bitpack = new BitPack(data, 0);
bitpack.PackBits(header.Stride, 16);
bitpack.PackBits(header.PatchSize, 8);
bitpack.PackBits((int)header.Type, 8);
CreatePatch(bitpack, patchData, x, y);
bitpack.PackBits(END_OF_PATCHES, 8);
layer.LayerData.Data = new byte[bitpack.BytePos + 1];
Buffer.BlockCopy(bitpack.Data, 0, layer.LayerData.Data, 0, bitpack.BytePos + 1);
return layer;
}
public static LayerDataPacket CreateLandPacket(float[,] patchData, int x, int y)
{
LayerDataPacket layer = new LayerDataPacket();
layer.LayerID.Type = (byte)TerrainPatch.LayerType.Land;
TerrainPatch.GroupHeader header = new TerrainPatch.GroupHeader();
header.Stride = STRIDE;
header.PatchSize = 16;
header.Type = TerrainPatch.LayerType.Land;
byte[] data = new byte[1536];
BitPack bitpack = new BitPack(data, 0);
bitpack.PackBits(header.Stride, 16);
bitpack.PackBits(header.PatchSize, 8);
bitpack.PackBits((int)header.Type, 8);
CreatePatch(bitpack, patchData, x, y);
bitpack.PackBits(END_OF_PATCHES, 8);
layer.LayerData.Data = new byte[bitpack.BytePos + 1];
Buffer.BlockCopy(bitpack.Data, 0, layer.LayerData.Data, 0, bitpack.BytePos + 1);
return layer;
}
public static void CreatePatch(BitPack output, float[] patchData, int x, int y)
{
if (patchData.Length != 16 * 16)
throw new ArgumentException("Patch data must be a 16x16 array");
TerrainPatch.Header header = PrescanPatch(patchData);
header.QuantWBits = 136;
header.PatchIDs = (y & 0x1F);
header.PatchIDs += (x << 5);
// NOTE: No idea what prequant and postquant should be or what they do
int[] patch = CompressPatch(patchData, header, 10);
int wbits = EncodePatchHeader(output, header, patch);
EncodePatch(output, patch, 0, wbits);
}
public static void CreatePatch(BitPack output, float[,] patchData, int x, int y)
{
if (patchData.Length != 16 * 16)
throw new ArgumentException("Patch data must be a 16x16 array");
TerrainPatch.Header header = PrescanPatch(patchData);
header.QuantWBits = 136;
header.PatchIDs = (y & 0x1F);
header.PatchIDs += (x << 5);
// NOTE: No idea what prequant and postquant should be or what they do
int[] patch = CompressPatch(patchData, header, 10);
int wbits = EncodePatchHeader(output, header, patch);
EncodePatch(output, patch, 0, wbits);
}
/// <summary>
/// Add a patch of terrain to a BitPacker
/// </summary>
/// <param name="output">BitPacker to write the patch to</param>
/// <param name="heightmap">Heightmap of the simulator, must be a 256 *
/// 256 float array</param>
/// <param name="x">X offset of the patch to create, valid values are
/// from 0 to 15</param>
/// <param name="y">Y offset of the patch to create, valid values are
/// from 0 to 15</param>
public static void CreatePatchFromHeightmap(BitPack output, float[] heightmap, int x, int y)
{
if (heightmap.Length != 256 * 256)
throw new ArgumentException("Heightmap data must be 256x256");
if (x < 0 || x > 15 || y < 0 || y > 15)
throw new ArgumentException("X and Y patch offsets must be from 0 to 15");
TerrainPatch.Header header = PrescanPatch(heightmap, x, y);
header.QuantWBits = 136;
header.PatchIDs = (y & 0x1F);
header.PatchIDs += (x << 5);
// NOTE: No idea what prequant and postquant should be or what they do
int[] patch = CompressPatch(heightmap, x, y, header, 10);
int wbits = EncodePatchHeader(output, header, patch);
EncodePatch(output, patch, 0, wbits);
}
private static TerrainPatch.Header PrescanPatch(float[] patch)
{
TerrainPatch.Header header = new TerrainPatch.Header();
float zmax = -99999999.0f;
float zmin = 99999999.0f;
for (int j = 0; j < 16; j++)
{
for (int i = 0; i < 16; i++)
{
float val = patch[j * 16 + i];
if (val > zmax) zmax = val;
if (val < zmin) zmin = val;
}
}
header.DCOffset = zmin;
header.Range = (int)((zmax - zmin) + 1.0f);
return header;
}
private static TerrainPatch.Header PrescanPatch(float[,] patch)
{
TerrainPatch.Header header = new TerrainPatch.Header();
float zmax = -99999999.0f;
float zmin = 99999999.0f;
for (int j = 0; j < 16; j++)
{
for (int i = 0; i < 16; i++)
{
float val = patch[j, i];
if (val > zmax) zmax = val;
if (val < zmin) zmin = val;
}
}
header.DCOffset = zmin;
header.Range = (int)((zmax - zmin) + 1.0f);
return header;
}
private static TerrainPatch.Header PrescanPatch(float[] heightmap, int patchX, int patchY)
{
TerrainPatch.Header header = new TerrainPatch.Header();
float zmax = -99999999.0f;
float zmin = 99999999.0f;
for (int j = patchY * 16; j < (patchY + 1) * 16; j++)
{
for (int i = patchX * 16; i < (patchX + 1) * 16; i++)
{
float val = heightmap[j * 256 + i];
if (val > zmax) zmax = val;
if (val < zmin) zmin = val;
}
}
header.DCOffset = zmin;
header.Range = (int)((zmax - zmin) + 1.0f);
return header;
}
public static TerrainPatch.Header DecodePatchHeader(BitPack bitpack)
{
TerrainPatch.Header header = new TerrainPatch.Header();
// Quantized word bits
header.QuantWBits = bitpack.UnpackBits(8);
if (header.QuantWBits == END_OF_PATCHES)
return header;
// DC offset
header.DCOffset = bitpack.UnpackFloat();
// Range
header.Range = bitpack.UnpackBits(16);
// Patch IDs (10 bits)
header.PatchIDs = bitpack.UnpackBits(10);
// Word bits
header.WordBits = (uint)((header.QuantWBits & 0x0f) + 2);
return header;
}
private static int EncodePatchHeader(BitPack output, TerrainPatch.Header header, int[] patch)
{
int temp;
int wbits = (header.QuantWBits & 0x0f) + 2;
uint maxWbits = (uint)wbits + 5;
uint minWbits = ((uint)wbits >> 1);
wbits = (int)minWbits;
for (int i = 0; i < patch.Length; i++)
{
temp = patch[i];
if (temp != 0)
{
// Get the absolute value
if (temp < 0) temp *= -1;
for (int j = (int)maxWbits; j > (int)minWbits; j--)
{
if ((temp & (1 << j)) != 0)
{
if (j > wbits) wbits = j;
break;
}
}
}
}
wbits += 1;
header.QuantWBits &= 0xf0;
if (wbits > 17 || wbits < 2)
{
Logger.Log("Bits needed per word in EncodePatchHeader() are outside the allowed range",
Helpers.LogLevel.Error);
}
header.QuantWBits |= (wbits - 2);
output.PackBits(header.QuantWBits, 8);
output.PackFloat(header.DCOffset);
output.PackBits(header.Range, 16);
output.PackBits(header.PatchIDs, 10);
return wbits;
}
private static void IDCTColumn16(float[] linein, float[] lineout, int column)
{
float total;
int usize;
for (int n = 0; n < 16; n++)
{
total = OO_SQRT2 * linein[column];
for (int u = 1; u < 16; u++)
{
usize = u * 16;
total += linein[usize + column] * CosineTable16[usize + n];
}
lineout[16 * n + column] = total;
}
}
private static void IDCTLine16(float[] linein, float[] lineout, int line)
{
const float oosob = 2.0f / 16.0f;
int lineSize = line * 16;
float total;
for (int n = 0; n < 16; n++)
{
total = OO_SQRT2 * linein[lineSize];
for (int u = 1; u < 16; u++)
{
total += linein[lineSize + u] * CosineTable16[u * 16 + n];
}
lineout[lineSize + n] = total * oosob;
}
}
private static void DCTLine16(float[] linein, float[] lineout, int line)
{
float total = 0.0f;
int lineSize = line * 16;
for (int n = 0; n < 16; n++)
{
total += linein[lineSize + n];
}
lineout[lineSize] = OO_SQRT2 * total;
for (int u = 1; u < 16; u++)
{
total = 0.0f;
for (int n = 0; n < 16; n++)
{
total += linein[lineSize + n] * CosineTable16[u * 16 + n];
}
lineout[lineSize + u] = total;
}
}
private static void DCTColumn16(float[] linein, int[] lineout, int column)
{
float total = 0.0f;
const float oosob = 2.0f / 16.0f;
for (int n = 0; n < 16; n++)
{
total += linein[16 * n + column];
}
lineout[CopyMatrix16[column]] = (int)(OO_SQRT2 * total * oosob * QuantizeTable16[column]);
for (int u = 1; u < 16; u++)
{
total = 0.0f;
for (int n = 0; n < 16; n++)
{
total += linein[16 * n + column] * CosineTable16[u * 16 + n];
}
lineout[CopyMatrix16[16 * u + column]] = (int)(total * oosob * QuantizeTable16[16 * u + column]);
}
}
public static void DecodePatch(int[] patches, BitPack bitpack, TerrainPatch.Header header, int size)
{
int temp;
for (int n = 0; n < size * size; n++)
{
// ?
temp = bitpack.UnpackBits(1);
if (temp != 0)
{
// Value or EOB
temp = bitpack.UnpackBits(1);
if (temp != 0)
{
// Value
temp = bitpack.UnpackBits(1);
if (temp != 0)
{
// Negative
temp = bitpack.UnpackBits((int)header.WordBits);
patches[n] = temp * -1;
}
else
{
// Positive
temp = bitpack.UnpackBits((int)header.WordBits);
patches[n] = temp;
}
}
else
{
// Set the rest to zero
// TODO: This might not be necessary
for (int o = n; o < size * size; o++)
{
patches[o] = 0;
}
break;
}
}
else
{
patches[n] = 0;
}
}
}
private static void EncodePatch(BitPack output, int[] patch, int postquant, int wbits)
{
int temp;
bool eob;
if (postquant > 16 * 16 || postquant < 0)
{
Logger.Log("Postquant is outside the range of allowed values in EncodePatch()", Helpers.LogLevel.Error);
return;
}
if (postquant != 0) patch[16 * 16 - postquant] = 0;
for (int i = 0; i < 16 * 16; i++)
{
eob = false;
temp = patch[i];
if (temp == 0)
{
eob = true;
for (int j = i; j < 16 * 16 - postquant; j++)
{
if (patch[j] != 0)
{
eob = false;
break;
}
}
if (eob)
{
output.PackBits(ZERO_EOB, 2);
return;
}
else
{
output.PackBits(ZERO_CODE, 1);
}
}
else
{
if (temp < 0)
{
temp *= -1;
if (temp > (1 << wbits)) temp = (1 << wbits);
output.PackBits(NEGATIVE_VALUE, 3);
output.PackBits(temp, wbits);
}
else
{
if (temp > (1 << wbits)) temp = (1 << wbits);
output.PackBits(POSITIVE_VALUE, 3);
output.PackBits(temp, wbits);
}
}
}
}
public static float[] DecompressPatch(int[] patches, TerrainPatch.Header header, TerrainPatch.GroupHeader group)
{
float[] block = new float[group.PatchSize * group.PatchSize];
float[] output = new float[group.PatchSize * group.PatchSize];
int prequant = (header.QuantWBits >> 4) + 2;
int quantize = 1 << prequant;
float ooq = 1.0f / (float)quantize;
float mult = ooq * (float)header.Range;
float addval = mult * (float)(1 << (prequant - 1)) + header.DCOffset;
if (group.PatchSize == 16)
{
for (int n = 0; n < 16 * 16; n++)
{
block[n] = patches[CopyMatrix16[n]] * DequantizeTable16[n];
}
float[] ftemp = new float[16 * 16];
for (int o = 0; o < 16; o++)
IDCTColumn16(block, ftemp, o);
for (int o = 0; o < 16; o++)
IDCTLine16(ftemp, block, o);
}
else
{
for (int n = 0; n < 32 * 32; n++)
{
block[n] = patches[CopyMatrix32[n]] * DequantizeTable32[n];
}
Logger.Log("Implement IDCTPatchLarge", Helpers.LogLevel.Error);
}
for (int j = 0; j < block.Length; j++)
{
output[j] = block[j] * mult + addval;
}
return output;
}
private static int[] CompressPatch(float[] patchData, TerrainPatch.Header header, int prequant)
{
float[] block = new float[16 * 16];
int wordsize = prequant;
float oozrange = 1.0f / (float)header.Range;
float range = (float)(1 << prequant);
float premult = oozrange * range;
float sub = (float)(1 << (prequant - 1)) + header.DCOffset * premult;
header.QuantWBits = wordsize - 2;
header.QuantWBits |= (prequant - 2) << 4;
int k = 0;
for (int j = 0; j < 16; j++)
{
for (int i = 0; i < 16; i++)
block[k++] = patchData[j * 16 + i] * premult - sub;
}
float[] ftemp = new float[16 * 16];
int[] itemp = new int[16 * 16];
for (int o = 0; o < 16; o++)
DCTLine16(block, ftemp, o);
for (int o = 0; o < 16; o++)
DCTColumn16(ftemp, itemp, o);
return itemp;
}
private static int[] CompressPatch(float[,] patchData, TerrainPatch.Header header, int prequant)
{
float[] block = new float[16 * 16];
int wordsize = prequant;
float oozrange = 1.0f / (float)header.Range;
float range = (float)(1 << prequant);
float premult = oozrange * range;
float sub = (float)(1 << (prequant - 1)) + header.DCOffset * premult;
header.QuantWBits = wordsize - 2;
header.QuantWBits |= (prequant - 2) << 4;
int k = 0;
for (int j = 0; j < 16; j++)
{
for (int i = 0; i < 16; i++)
block[k++] = patchData[j, i] * premult - sub;
}
float[] ftemp = new float[16 * 16];
int[] itemp = new int[16 * 16];
for (int o = 0; o < 16; o++)
DCTLine16(block, ftemp, o);
for (int o = 0; o < 16; o++)
DCTColumn16(ftemp, itemp, o);
return itemp;
}
private static int[] CompressPatch(float[] heightmap, int patchX, int patchY, TerrainPatch.Header header, int prequant)
{
float[] block = new float[16 * 16];
int wordsize = prequant;
float oozrange = 1.0f / (float)header.Range;
float range = (float)(1 << prequant);
float premult = oozrange * range;
float sub = (float)(1 << (prequant - 1)) + header.DCOffset * premult;
header.QuantWBits = wordsize - 2;
header.QuantWBits |= (prequant - 2) << 4;
int k = 0;
for (int j = patchY * 16; j < (patchY + 1) * 16; j++)
{
for (int i = patchX * 16; i < (patchX + 1) * 16; i++)
block[k++] = heightmap[j * 256 + i] * premult - sub;
}
float[] ftemp = new float[16 * 16];
int[] itemp = new int[16 * 16];
for (int o = 0; o < 16; o++)
DCTLine16(block, ftemp, o);
for (int o = 0; o < 16; o++)
DCTColumn16(ftemp, itemp, o);
return itemp;
}
#region Initialization
private static void BuildDequantizeTable16()
{
for (int j = 0; j < 16; j++)
{
for (int i = 0; i < 16; i++)
{
DequantizeTable16[j * 16 + i] = 1.0f + 2.0f * (float)(i + j);
}
}
}
private static void BuildQuantizeTable16()
{
for (int j = 0; j < 16; j++)
{
for (int i = 0; i < 16; i++)
{
QuantizeTable16[j * 16 + i] = 1.0f / (1.0f + 2.0f * ((float)i + (float)j));
}
}
}
private static void SetupCosines16()
{
const float hposz = (float)Math.PI * 0.5f / 16.0f;
for (int u = 0; u < 16; u++)
{
for (int n = 0; n < 16; n++)
{
CosineTable16[u * 16 + n] = (float)Math.Cos((2.0f * (float)n + 1.0f) * (float)u * hposz);
}
}
}
private static void BuildCopyMatrix16()
{
bool diag = false;
bool right = true;
int i = 0;
int j = 0;
int count = 0;
while (i < 16 && j < 16)
{
CopyMatrix16[j * 16 + i] = count++;
if (!diag)
{
if (right)
{
if (i < 16 - 1) i++;
else j++;
right = false;
diag = true;
}
else
{
if (j < 16 - 1) j++;
else i++;
right = true;
diag = true;
}
}
else
{
if (right)
{
i++;
j--;
if (i == 16 - 1 || j == 0) diag = false;
}
else
{
i--;
j++;
if (j == 16 - 1 || i == 0) diag = false;
}
}
}
}
#endregion Initialization
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions;
using osu.Framework.MathUtils;
using osu.Framework.Platform;
using osu.Framework.Screens;
using osu.Game.Beatmaps;
using osu.Game.Database;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Rulesets.Taiko;
using osu.Game.Screens.Select;
using osu.Game.Screens.Select.Carousel;
using osu.Game.Screens.Select.Filter;
namespace osu.Game.Tests.Visual
{
[TestFixture]
public class TestCasePlaySongSelect : ScreenTestCase
{
private BeatmapManager manager;
private RulesetStore rulesets;
private WorkingBeatmap defaultBeatmap;
private DatabaseContextFactory factory;
[Cached]
[Cached(Type = typeof(IBindable<IEnumerable<Mod>>))]
private readonly Bindable<IEnumerable<Mod>> selectedMods = new Bindable<IEnumerable<Mod>>(new Mod[] { });
public override IReadOnlyList<Type> RequiredTypes => new[]
{
typeof(SongSelect),
typeof(BeatmapCarousel),
typeof(CarouselItem),
typeof(CarouselGroup),
typeof(CarouselGroupEagerSelect),
typeof(CarouselBeatmap),
typeof(CarouselBeatmapSet),
typeof(DrawableCarouselItem),
typeof(CarouselItemState),
typeof(DrawableCarouselBeatmap),
typeof(DrawableCarouselBeatmapSet),
};
private class TestSongSelect : PlaySongSelect
{
public Action StartRequested;
public new Bindable<RulesetInfo> Ruleset => base.Ruleset;
public WorkingBeatmap CurrentBeatmap => Beatmap.Value;
public WorkingBeatmap CurrentBeatmapDetailsBeatmap => BeatmapDetails.Beatmap;
public new BeatmapCarousel Carousel => base.Carousel;
protected override bool OnStart()
{
StartRequested?.Invoke();
return base.OnStart();
}
}
private TestSongSelect songSelect;
protected override void Dispose(bool isDisposing)
{
factory.ResetDatabase();
base.Dispose(isDisposing);
}
[BackgroundDependencyLoader]
private void load(GameHost host)
{
factory = new DatabaseContextFactory(LocalStorage);
factory.ResetDatabase();
using (var usage = factory.Get())
usage.Migrate();
factory.ResetDatabase();
using (var usage = factory.Get())
usage.Migrate();
Dependencies.Cache(rulesets = new RulesetStore(factory));
Dependencies.Cache(manager = new BeatmapManager(LocalStorage, factory, rulesets, null, null, host, defaultBeatmap = Beatmap.Default));
Beatmap.SetDefault();
}
[SetUp]
public virtual void SetUp() =>
Schedule(() => { manager?.Delete(manager.GetAllUsableBeatmapSets()); });
[Test]
public void TestDummy()
{
createSongSelect();
AddAssert("dummy selected", () => songSelect.CurrentBeatmap == defaultBeatmap);
AddUntilStep(() => songSelect.CurrentBeatmapDetailsBeatmap == defaultBeatmap, "dummy shown on wedge");
addManyTestMaps();
AddWaitStep(3);
AddAssert("random map selected", () => songSelect.CurrentBeatmap != defaultBeatmap);
}
[Test]
public void TestSorting()
{
createSongSelect();
addManyTestMaps();
AddWaitStep(3);
AddAssert("random map selected", () => songSelect.CurrentBeatmap != defaultBeatmap);
AddStep(@"Sort by Artist", delegate { songSelect.FilterControl.Sort = SortMode.Artist; });
AddStep(@"Sort by Title", delegate { songSelect.FilterControl.Sort = SortMode.Title; });
AddStep(@"Sort by Author", delegate { songSelect.FilterControl.Sort = SortMode.Author; });
AddStep(@"Sort by Difficulty", delegate { songSelect.FilterControl.Sort = SortMode.Difficulty; });
}
[Test]
[Ignore("needs fixing")]
public void TestImportUnderDifferentRuleset()
{
createSongSelect();
changeRuleset(2);
importForRuleset(0);
AddUntilStep(() => songSelect.Carousel.SelectedBeatmap == null, "no selection");
}
[Test]
public void TestImportUnderCurrentRuleset()
{
createSongSelect();
changeRuleset(2);
importForRuleset(2);
importForRuleset(1);
AddUntilStep(() => songSelect.Carousel.SelectedBeatmap.RulesetID == 2, "has selection");
changeRuleset(1);
AddUntilStep(() => songSelect.Carousel.SelectedBeatmap.RulesetID == 1, "has selection");
changeRuleset(0);
AddUntilStep(() => songSelect.Carousel.SelectedBeatmap == null, "no selection");
}
[Test]
public void TestRulesetChangeResetsMods()
{
createSongSelect();
changeRuleset(0);
changeMods(new OsuModHardRock());
int actionIndex = 0;
int modChangeIndex = 0;
int rulesetChangeIndex = 0;
AddStep("change ruleset", () =>
{
songSelect.CurrentBeatmap.Mods.ValueChanged += onModChange;
songSelect.Ruleset.ValueChanged += onRulesetChange;
Ruleset.Value = new TaikoRuleset().RulesetInfo;
songSelect.CurrentBeatmap.Mods.ValueChanged -= onModChange;
songSelect.Ruleset.ValueChanged -= onRulesetChange;
});
AddAssert("mods changed before ruleset", () => modChangeIndex < rulesetChangeIndex);
AddAssert("empty mods", () => !selectedMods.Value.Any());
void onModChange(ValueChangedEvent<IEnumerable<Mod>> e) => modChangeIndex = actionIndex++;
void onRulesetChange(ValueChangedEvent<RulesetInfo> e) => rulesetChangeIndex = actionIndex--;
}
[Test]
public void TestStartAfterUnMatchingFilterDoesNotStart()
{
createSongSelect();
addManyTestMaps();
AddUntilStep(() => songSelect.Carousel.SelectedBeatmap != null, "has selection");
bool startRequested = false;
AddStep("set filter and finalize", () =>
{
songSelect.StartRequested = () => startRequested = true;
songSelect.Carousel.Filter(new FilterCriteria { SearchText = "somestringthatshouldn'tbematchable" });
songSelect.FinaliseSelection();
songSelect.StartRequested = null;
});
AddAssert("start not requested", () => !startRequested);
}
private void importForRuleset(int id) => AddStep($"import test map for ruleset {id}", () => manager.Import(createTestBeatmapSet(getImportId(), rulesets.AvailableRulesets.Where(r => r.ID == id).ToArray())));
private static int importId;
private int getImportId() => ++importId;
private void changeMods(params Mod[] mods) => AddStep($"change mods to {string.Join(", ", mods.Select(m => m.Acronym))}", () => selectedMods.Value = mods);
private void changeRuleset(int id) => AddStep($"change ruleset to {id}", () => Ruleset.Value = rulesets.AvailableRulesets.First(r => r.ID == id));
private void createSongSelect()
{
AddStep("create song select", () => LoadScreen(songSelect = new TestSongSelect()));
AddUntilStep(() => songSelect.IsCurrentScreen(), "wait for present");
}
private void addManyTestMaps()
{
AddStep("import test maps", () =>
{
var usableRulesets = rulesets.AvailableRulesets.Where(r => r.ID != 2).ToArray();
for (int i = 0; i < 100; i += 10)
manager.Import(createTestBeatmapSet(i, usableRulesets));
});
}
private BeatmapSetInfo createTestBeatmapSet(int setId, RulesetInfo[] rulesets)
{
int j = 0;
RulesetInfo getRuleset() => rulesets[j++ % rulesets.Length];
var beatmaps = new List<BeatmapInfo>();
for (int i = 0; i < 6; i++)
{
int beatmapId = setId * 10 + i;
beatmaps.Add(new BeatmapInfo
{
Ruleset = getRuleset(),
OnlineBeatmapID = beatmapId,
Path = "normal.osu",
Version = $"{beatmapId}",
BaseDifficulty = new BeatmapDifficulty
{
OverallDifficulty = 3.5f,
}
});
}
return new BeatmapSetInfo
{
OnlineBeatmapSetID = setId,
Hash = new MemoryStream(Encoding.UTF8.GetBytes(Guid.NewGuid().ToString())).ComputeMD5Hash(),
Metadata = new BeatmapMetadata
{
// Create random metadata, then we can check if sorting works based on these
Artist = "Some Artist " + RNG.Next(0, 9),
Title = $"Some Song (set id {setId})",
AuthorString = "Some Guy " + RNG.Next(0, 9),
},
Beatmaps = beatmaps
};
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////
// //
// MIT X11 license, Copyright (c) 2005-2006 by: //
// //
// Authors: //
// Michael Dominic K. <[email protected]> //
// //
// Permission is hereby granted, free of charge, to any person obtaining a //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation //
// the rights to use, copy, modify, merge, publish, distribute, sublicense, //
// and/or sell copies of the Software, and to permit persons to whom the //
// Software is furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included //
// in all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS //
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF //
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN //
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, //
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR //
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE //
// USE OR OTHER DEALINGS IN THE SOFTWARE. //
// //
////////////////////////////////////////////////////////////////////////////////
namespace Diva.Editor.Gui {
using System;
using Gtk;
using Mono.Unix;
using Widgets;
using Util;
public sealed class TagsWindow : Gtk.Window, IUnbindable {
// Translatable ////////////////////////////////////////////////
readonly static string titleSS = Catalog.GetString
("Tags");
readonly static string isAppliedSS = Catalog.GetString
("Tag '{0}' that you're trying to remove is applied to one or more items. " +
"Are you sure that you want to remove it?");
readonly static string isAppliedHeaderSS = Catalog.GetString
("Remove tag?");
// Fields //////////////////////////////////////////////////////
Model.Root modelRoot = null; // App model
VBox mainVBox = null;
HBox topHBox = null;
VButtonBox rightBox = null;
HButtonBox bottomBox = null;
Button closeButton = null;
Button helpButton = null;
Button newButton = null;
Button editButton = null;
Button removeButton = null;
TagsTreeView tagsTree = null;
Frame tagsFrame = null;
// Public methods //////////////////////////////////////////////
/* CONSTRUCTOR */
public TagsWindow (Model.Root root, Gtk.Window parent) : base (titleSS)
{
BorderWidth = 6;
modelRoot = root;
TransientFor = parent;
// Bottom buttons
closeButton = new Button (Stock.Close);
closeButton.Clicked += OnCloseClicked;
helpButton = new Button (Stock.Help);
// Bottom box
bottomBox = new HButtonBox ();
bottomBox.Spacing = 6;
bottomBox.Add (helpButton);
bottomBox.Add (closeButton);
// Right buttons
newButton = new Button (Stock.New);
newButton.Clicked += OnNewClicked;
editButton = new Button (Stock.Edit);
editButton.Clicked += OnEditClicked;
removeButton = new Button (Stock.Remove);
removeButton.Clicked += OnRemoveClicked;
// Right button box
rightBox = new VButtonBox ();
rightBox.Spacing = 6;
rightBox.Layout = ButtonBoxStyle.Start;
rightBox.Add (newButton);
rightBox.Add (editButton);
rightBox.Add (removeButton);
// Tags tree
tagsTree = new TagsTreeView (root);
tagsTree.Controller.StateChange += OnControllerStateChange;
tagsTree.RowActivated += OnTagsTreeRowActivated;
editButton.Sensitive = tagsTree.Controller.Valid;
removeButton.Sensitive = tagsTree.Controller.Valid;
// Frame
tagsFrame = new Frame ();
tagsFrame.Shadow = ShadowType.In;
tagsFrame.Add (tagsTree);
// Top HBox
topHBox = new HBox (false, 6);
topHBox.PackStart (tagsFrame, true, true, 0);
topHBox.PackEnd (rightBox, false, false, 0);
// Main VBox
mainVBox = new VBox (false, 12);
mainVBox.PackStart (topHBox, true, true, 0);
mainVBox.PackEnd (bottomBox, false, false, 0);
Add (mainVBox);
GtkFu.ParseGeometry (this, Config.Ui.TagsWindowGeometry);
ShowAll ();
}
public void Unbind ()
{
tagsTree.Unbind ();
}
public void SaveGeometry ()
{
Config.Ui.TagsWindowGeometry = GtkFu.GetGeometry (this);
}
// Private methods /////////////////////////////////////////////
void OnControllerStateChange (object o, EmptyModelControllerStateArgs args)
{
removeButton.Sensitive = args.Valid;
editButton.Sensitive = args.Valid;
}
void OnCloseClicked (object o, EventArgs args)
{
modelRoot.Window.HideTagsWindow ();
}
protected override bool OnDeleteEvent (Gdk.Event evnt)
{
modelRoot.Window.HideTagsWindow ();
return true;
}
void OnTagsTreeRowActivated (object o, RowActivatedArgs args)
{
if (! tagsTree.Controller.Valid)
return;
Core.Tag editedTag = tagsTree.SelectedTag;
if (editedTag == null)
return;
EditTag (editedTag);
}
void EditTag (Core.Tag editedTag)
{
EditTagDialog dialog = new EditTagDialog (modelRoot, this, editedTag);
ResponseType response = (ResponseType) dialog.Run ();
if (response == ResponseType.Ok)
modelRoot.Tags.EditTag (editedTag, dialog.TagName);
dialog.Destroy ();
}
void OnNewClicked (object o, EventArgs args)
{
EditTagDialog dialog = new EditTagDialog (modelRoot, this);
ResponseType response = (ResponseType) dialog.Run ();
if (response == ResponseType.Ok)
modelRoot.Tags.Create (dialog.TagName);
dialog.Destroy ();
}
void OnEditClicked (object o, EventArgs args)
{
if (! tagsTree.Controller.Valid)
return;
Core.Tag editedTag = tagsTree.SelectedTag;
if (editedTag == null)
return;
EditTag (editedTag);
}
void OnRemoveClicked (object o, EventArgs args)
{
if (! tagsTree.Controller.Valid)
return;
Core.Tag removedTag = tagsTree.SelectedTag;
if (removedTag == null)
return;
// Display warning
if (modelRoot.Tags.GetAppliedCount (removedTag) != 0) {
string msg = String.Format (isAppliedSS, removedTag.Name);
ResponseType response = FastDialog.WarningYesNo (this,
isAppliedHeaderSS,
msg);
if (response != ResponseType.Yes)
return;
}
modelRoot.Tags.Delete (removedTag);
tagsTree.Controller.EmitStateChange ();
}
}
}
| |
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 FTIUploadServer.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
//! \file WarcEncryption.cs
//! \date Mon Aug 15 08:56:04 2016
//! \brief ShiinaRio archives encryption.
//
// Copyright (C) 2015-2016 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Runtime.InteropServices;
using GameRes.Utility;
namespace GameRes.Formats.ShiinaRio
{
[Serializable]
public class EncryptionScheme
{
public string Name { get; set; }
public string OriginalTitle { get; set; }
public int Version { get; set; }
public int EntryNameSize;
public byte[] CryptKey;
public uint[] HelperKey;
public byte[] Region;
public byte[] DecodeBin;
public IByteArray ShiinaImage;
public IDecryptExtra ExtraCrypt;
public static readonly EncryptionScheme Warc110 = new EncryptionScheme { EntryNameSize = 0x10 };
}
public interface IByteArray
{
int Length { get; }
byte this[int i] { get; }
}
public interface IDecryptExtra
{
void Decrypt (byte[] data, int index, uint length, uint flags);
void Encrypt (byte[] data, int index, uint length, uint flags);
}
internal class Decoder
{
EncryptionScheme m_scheme;
public int SchemeVersion { get { return m_scheme.Version; } }
public int WarcVersion { get; private set; }
public uint MaxIndexLength { get; private set; }
public int EntryNameSize { get { return m_scheme.EntryNameSize; } }
public IDecryptExtra ExtraCrypt { get { return m_scheme.ExtraCrypt; } }
private uint Rand { get; set; }
public Decoder (int version, EncryptionScheme scheme)
{
m_scheme = scheme;
WarcVersion = version;
MaxIndexLength = GetMaxIndexLength (version);
}
public void Decrypt (byte[] data, int index, uint data_length)
{
DoEncryption (data, index, data_length, DecryptContent);
}
public void Encrypt (byte[] data, int index, uint data_length)
{
DoEncryption (data, index, data_length, EncryptContent);
}
public void DecryptIndex (uint index_offset, byte[] index)
{
Decrypt (index, 0, (uint)index.Length);
XorIndex (index_offset, index);
}
public void EncryptIndex (uint index_offset, byte[] index)
{
XorIndex (index_offset, index);
Encrypt (index, 0, (uint)index.Length);
}
void DecryptContent (int x, byte[] data, int index, uint length)
{
int n = 0;
for (int i = 2; i < length; ++i)
{
byte d = data[index+i];
if (WarcVersion > 120)
d ^= (byte)((double)NextRand() / 16777216.0);
d = Binary.RotByteR (d, 1);
d ^= (byte)(m_scheme.CryptKey[n++] ^ m_scheme.CryptKey[x]);
data[index+i] = d;
x = d % m_scheme.CryptKey.Length;
if (n >= m_scheme.CryptKey.Length)
n = 0;
}
}
void EncryptContent (int x, byte[] data, int index, uint length)
{
int n = 0;
for (int i = 2; i < length; ++i)
{
byte k = (byte)(m_scheme.CryptKey[n++] ^ m_scheme.CryptKey[x]);
byte d = data[index+i];
x = d % m_scheme.CryptKey.Length;
d ^= k;
d = Binary.RotByteL (d, 1);
if (WarcVersion > 120)
d ^= (byte)((double)NextRand() / 16777216.0);
data[index+i] = d;
if (n >= m_scheme.CryptKey.Length)
n = 0;
}
}
delegate void ContentEncryptor (int start_key, byte[] data, int index, uint length);
void DoEncryption (byte[] data, int index, uint data_length, ContentEncryptor encryptor)
{
if (data_length < 3 || WarcVersion < 120)
return;
uint effective_length = Math.Min (data_length, 1024u);
int a, b;
uint fac = 0;
Rand = data_length;
if (WarcVersion > 120)
{
a = (sbyte)data[index] ^ (sbyte)data_length;
b = (sbyte)data[index+1] ^ (sbyte)(data_length / 2);
if (data_length != MaxIndexLength && (WarcVersion > 130 || m_scheme.Version > 2150))
{
// ... regular entry decryption
int idx = (int)((double)NextRand() * (m_scheme.ShiinaImage.Length / 4294967296.0));
if (WarcVersion >= 160)
{
fac = Rand + m_scheme.ShiinaImage[idx];
fac = DecryptHelper3 (fac) & 0xfffffff;
if (effective_length > 0x80 && SchemeVersion > 2350)
{
DecryptHelper4 (data, index+4, m_scheme.HelperKey);
index += 0x80;
effective_length -= 0x80;
}
}
else if (150 == WarcVersion)
{
fac = Rand + m_scheme.ShiinaImage[idx];
fac ^= (fac & 0xfff) * (fac & 0xfff);
uint v = 0;
for (int i = 0; i < 32; ++i)
{
uint bit = fac & 1;
fac >>= 1;
if (0 != bit)
v += fac;
}
fac = v;
}
else if (140 == WarcVersion)
{
fac = m_scheme.ShiinaImage[idx];
}
else if (130 == WarcVersion)
{
fac = m_scheme.ShiinaImage[idx & 0xff];
}
}
}
else
{
a = data[index];
b = data[index+1];
}
Rand ^= (uint)(DecryptHelper1 (a) * 100000000.0);
double token = 0.0;
if (0 != (a|b))
{
token = Math.Acos ((double)a / Math.Sqrt ((double)(a*a + b*b)));
token = token / Math.PI * 180.0;
}
if (b < 0)
token = 360.0 - token;
int x = (int)((fac + (byte)DecryptHelper2 (token)) % (uint)m_scheme.CryptKey.Length);
encryptor (x, data, index, effective_length);
}
unsafe void XorIndex (uint index_offset, byte[] index)
{
fixed (byte* buf_raw = index)
{
uint* encoded = (uint*)buf_raw;
for (int i = 0; i < index.Length/4; ++i)
encoded[i] ^= index_offset;
if (WarcVersion >= 170)
{
byte key = (byte)~WarcVersion;
for (int i = 0; i < index.Length; ++i)
buf_raw[i] ^= key;
}
}
}
public void Decrypt2 (byte[] data, int index, uint length)
{
if (length < 0x400 || null == m_scheme.DecodeBin)
return;
uint crc = Crc32Normal.UpdateCrc (0xFFFFFFFF, data, index, 0x100);
index += 0x100;
for (int i = 0; i < 0x40; ++i)
{
uint src = LittleEndian.ToUInt32 (data, index) & 0x1ffcu;
src = LittleEndian.ToUInt32 (m_scheme.DecodeBin, (int)src);
uint key = src ^ crc;
data[index++ + 0x100] ^= (byte)key;
data[index++ + 0x100] ^= (byte)(key >> 8);
data[index++ + 0x100] ^= (byte)(key >> 16);
data[index++ + 0x100] ^= (byte)(key >> 24);
}
}
double DecryptHelper1 (double a)
{
if (a < 0)
return -DecryptHelper1 (-a);
double v0;
double v1;
if (a < 18.0)
{
v0 = a;
v1 = a;
double v2 = -(a * a);
for (int j = 3; j < 1000; j += 2)
{
v1 *= v2 / (j * (j - 1));
v0 += v1 / j;
if (v0 == v2)
break;
}
return v0;
}
int flags = 0;
double v0_l = 0;
v1 = 0;
double div = 1 / a;
double v1_h = 2.0;
double v0_h = 2.0;
double v1_l = 0;
v0 = 0;
int i = 0;
do
{
v0 += div;
div *= ++i / a;
if (v0 < v0_h)
v0_h = v0;
else
flags |= 1;
v1 += div;
div *= ++i / a;
if (v1 < v1_h)
v1_h = v1;
else
flags |= 2;
v0 -= div;
div *= ++i / a;
if (v0 > v0_l)
v0_l = v0;
else
flags |= 4;
v1 -= div;
div *= ++i / a;
if (v1 > v1_l)
v1_l = v1;
else
flags |= 8;
}
while (flags != 0xf);
return ((Math.PI - Math.Cos(a) * (v0_l + v0_h)) - (Math.Sin(a) * (v1_l + v1_h))) / 2.0;
}
uint DecryptHelper2 (double a)
{
double v0, v1, v2, v3;
if (a > 1.0)
{
v0 = Math.Sqrt (a * 2 - 1);
for (;;)
{
v1 = 1 - (double)NextRand() / 4294967296.0;
v2 = 2.0 * (double)NextRand() / 4294967296.0 - 1.0;
if (v1 * v1 + v2 * v2 > 1.0)
continue;
v2 /= v1;
v3 = v2 * v0 + a - 1.0;
if (v3 <= 0)
continue;
v1 = (a - 1.0) * Math.Log (v3 / (a - 1.0)) - v2 * v0;
if (v1 < -50.0)
continue;
if (((double)NextRand() / 4294967296.0) <= (Math.Exp(v1) * (v2 * v2 + 1.0)))
break;
}
}
else
{
v0 = Math.Exp(1.0) / (a + Math.Exp(1.0));
do
{
v1 = (double)NextRand() / 4294967296.0;
v2 = (double)NextRand() / 4294967296.0;
if (v1 < v0)
{
v3 = Math.Pow(v2, 1.0 / a);
v1 = Math.Exp(-v3);
} else
{
v3 = 1.0 - Math.Log(v2);
v1 = Math.Pow(v3, a - 1.0);
}
}
while ((double)NextRand() / 4294967296.0 >= v1);
}
if (WarcVersion > 120)
return (uint)(v3 * 256.0);
else
return (byte)((double)NextRand() / 4294967296.0);
}
[StructLayout(LayoutKind.Explicit)]
struct Union
{
[FieldOffset(0)]
public int i;
[FieldOffset (0)]
public uint u;
[FieldOffset(0)]
public float f;
[FieldOffset(0)]
public byte b0;
[FieldOffset(1)]
public byte b1;
[FieldOffset(2)]
public byte b2;
[FieldOffset(3)]
public byte b3;
}
uint DecryptHelper3 (uint key)
{
var p = new Union();
p.u = key;
var fv = new Union();
fv.f = (float)(1.5 * (double)p.b0 + 0.1);
uint v0 = Binary.BigEndian (fv.u);
fv.f = (float)(1.5 * (double)p.b1 + 0.1);
uint v1 = (uint)fv.f;
fv.f = (float)(1.5 * (double)p.b2 + 0.1);
uint v2 = (uint)-fv.i;
fv.f = (float)(1.5 * (double)p.b3 + 0.1);
uint v3 = ~fv.u;
return ((v0 + v1) | (v2 - v3));
}
void DecryptHelper4 (byte[] data, int index, uint[] key_src)
{
uint[] buf = new uint[0x50];
int i;
for (i = 0; i < 0x10; ++i)
{
buf[i] = BigEndian.ToUInt32 (data, index+40+4*i);
}
for (; i < 0x50; ++i)
{
uint v = buf[i-16];
v ^= buf[i-14];
v ^= buf[i-8];
v ^= buf[i-3];
buf[i] = Binary.RotL (v, 1);
}
uint[] key = new uint[10];
Array.Copy (key_src, key, 5);
uint k0 = key[0];
uint k1 = key[1];
uint k2 = key[2];
uint k3 = key[3];
uint k4 = key[4];
for (int buf_idx = 0; buf_idx < 0x50; ++buf_idx)
{
uint f, c;
if (buf_idx < 0x10)
{
f = k1 ^ k2 ^ k3;
c = 0;
}
else if (buf_idx < 0x20)
{
f = k1 & k2 | k3 & ~k1;
c = 0x5A827999;
}
else if (buf_idx < 0x30)
{
f = k3 ^ (k1 | ~k2);
c = 0x6ED9EBA1;
}
else if (buf_idx < 0x40)
{
f = k1 & k3 | k2 & ~k3;
c = 0x8F1BBCDC;
}
else
{
f = k1 ^ (k2 | ~k3);
c = 0xA953FD4E;
}
uint new_k0 = buf[buf_idx] + k4 + f + c + Binary.RotL (k0, 5);
uint new_k2 = Binary.RotR (k1, 2);
k1 = k0;
k4 = k3;
k3 = k2;
k2 = new_k2;
k0 = new_k0;
}
key[0] += k0;
key[1] += k1;
key[2] += k2;
key[3] += k3;
key[4] += k4;
var ft = new FILETIME {
DateTimeLow = key[1],
DateTimeHigh = key[0] & 0x7FFFFFFF
};
var sys_time = new SYSTEMTIME (ft);
key[5] = (uint)(sys_time.Year | sys_time.Month << 16);
key[7] = (uint)(sys_time.Hour | sys_time.Minute << 16);
key[8] = (uint)(sys_time.Second | sys_time.Milliseconds << 16);
uint flags = LittleEndian.ToUInt32 (data, index+40) | 0x80000000;
uint rgb = buf[1] >> 8; // BigEndian.ToUInt32 (data, index+44) >> 8;
if (0 == (flags & 0x78000000))
flags |= 0x98000000;
key[6] = RegionCrc32 (m_scheme.Region, flags, rgb);
key[9] = (uint)(((int)key[2] * (long)(int)key[3]) >> 8);
if (m_scheme.Version >= 2390)
key[6] += key[9];
unsafe
{
fixed (byte* data_fixed = data)
{
uint* encoded = (uint*)(data_fixed+index);
for (i = 0; i < 10; ++i)
{
encoded[i] ^= key[i];
}
}
}
}
static readonly uint[] CustomCrcTable = InitCrcTable();
static uint[] InitCrcTable ()
{
var table = new uint[0x100];
for (uint i = 0; i != 256; ++i)
{
uint poly = i;
for (int j = 0; j < 8; ++j)
{
uint bit = poly & 1;
poly = Binary.RotR (poly, 1);
if (0 == bit)
poly ^= 0x6DB88320;
}
table[i] = poly;
}
return table;
}
uint RegionCrc32 (byte[] src, uint flags, uint rgb)
{
int src_alpha = (int)flags & 0x1ff;
int dst_alpha = (int)(flags >> 12) & 0x1ff;
flags >>= 24;
if (0 == (flags & 0x10))
dst_alpha = 0;
if (0 == (flags & 8))
src_alpha = 0x100;
int y_step = 0;
int x_step = 4;
int width = 48;
int pos = 0;
if (0 != (flags & 0x40)) // horizontal flip
{
y_step += width;
pos += (width-1)*4;
x_step = -x_step;
}
if (0 != (flags & 0x20)) // vertical flip
{
y_step -= width;
pos += width*0x2f*4; // width*(height-1)*4;
}
y_step <<= 3;
uint checksum = 0;
for (int y = 0; y < 48; ++y)
{
for (int x = 0; x < 48; ++x)
{
int alpha = src[pos+3] * src_alpha;
alpha >>= 8;
uint color = rgb;
for (int i = 0; i < 3; ++i)
{
int v = src[pos+i];
int c = (int)(color & 0xff); // rgb[i];
c -= v;
c = (c * dst_alpha) >> 8;
c = (c + v) & 0xff;
c = (c * alpha) >> 8;
checksum = (checksum >> 8) ^ CustomCrcTable[(c ^ checksum) & 0xff];
color >>= 8;
}
pos += x_step;
}
pos += y_step;
}
return checksum;
}
[StructLayout(LayoutKind.Sequential)]
private struct FILETIME
{
public uint DateTimeLow;
public uint DateTimeHigh;
}
[StructLayout(LayoutKind.Sequential)]
private struct SYSTEMTIME
{
[MarshalAs(UnmanagedType.U2)] public ushort Year;
[MarshalAs(UnmanagedType.U2)] public ushort Month;
[MarshalAs(UnmanagedType.U2)] public ushort DayOfWeek;
[MarshalAs(UnmanagedType.U2)] public ushort Day;
[MarshalAs(UnmanagedType.U2)] public ushort Hour;
[MarshalAs(UnmanagedType.U2)] public ushort Minute;
[MarshalAs(UnmanagedType.U2)] public ushort Second;
[MarshalAs(UnmanagedType.U2)] public ushort Milliseconds;
public SYSTEMTIME (FILETIME ft)
{
FileTimeToSystemTime (ref ft, out this);
}
[DllImport ("kernel32.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true)]
static extern bool FileTimeToSystemTime (ref FILETIME lpFileTime, out SYSTEMTIME lpSystemTime);
}
uint NextRand ()
{
Rand = 1566083941u * Rand + 1u;
return Rand;
}
uint GetMaxIndexLength (int version)
{
int max_index_entries = version < 150 || SchemeVersion < 2310 ? 8192 : 16384;
return (uint)((m_scheme.EntryNameSize + 0x18) * max_index_entries);
}
public static EncryptionScheme[] KnownSchemes = new EncryptionScheme[0];
}
[Serializable]
public class ImageArray : IByteArray
{
private byte[] m_common;
private byte[] m_extra;
private int m_common_length;
public ImageArray (byte[] common) : this (common, common.Length, Array.Empty<byte>())
{
}
public ImageArray (byte[] common, byte[] extra) : this (common, common.Length, extra)
{
}
public ImageArray (byte[] common, int common_length, byte[] extra)
{
if (common_length > common.Length)
throw new IndexOutOfRangeException();
m_common = common;
m_extra = extra;
m_common_length = common_length;
}
public int Length { get { return m_common_length + m_extra.Length; } }
public byte this[int i]
{
get
{
if (i < m_common_length)
return m_common[i];
else
return m_extra[i - m_common_length];
}
}
}
[Serializable]
public abstract class KeyDecryptBase : IDecryptExtra
{
protected readonly uint Seed;
protected readonly byte[] DecodeTable;
protected uint MinLength = 0x400;
protected int PostDataOffset = 0x200;
public KeyDecryptBase (uint seed, byte[] decode_bin)
{
Seed = seed;
DecodeTable = decode_bin;
}
public void Decrypt (byte[] data, int index, uint length, uint flags)
{
if (length < MinLength)
return;
if ((flags & 0x202) == 0x202)
DecryptPre (data, index, length);
if ((flags & 0x204) == 0x204)
DecryptPost (data, index, length);
}
public void Encrypt (byte[] data, int index, uint length, uint flags)
{
if (length < MinLength)
return;
if ((flags & 0x104) == 0x104)
DecryptPost (data, index, length);
if ((flags & 0x102) == 0x102)
DecryptPre (data, index, length);
}
protected abstract void DecryptPre (byte[] data, int index, uint length);
protected virtual void DecryptPost (byte[] data, int index, uint length)
{
int pos = index + PostDataOffset;
data[pos ] ^= (byte)Seed;
data[pos+1] ^= (byte)(Seed >> 8);
data[pos+2] ^= (byte)(Seed >> 16);
data[pos+3] ^= (byte)(Seed >> 24);
}
}
[Serializable]
public abstract class KeyDecryptExtra : KeyDecryptBase
{
protected int EncryptedSize = 0xFF;
public KeyDecryptExtra (uint seed, byte[] decode_bin) : base (seed, decode_bin)
{
}
protected override void DecryptPre (byte[] data, int index, uint length)
{
var k = new uint[4];
InitKey (Seed, k);
for (int i = 0; i < EncryptedSize; ++i)
{
uint j = k[3] ^ (k[3] << 11) ^ k[0] ^ ((k[3] ^ (k[3] << 11) ^ (k[0] >> 11)) >> 8);
k[3] = k[2];
k[2] = k[1];
k[1] = k[0];
k[0] = j;
data[index + i] ^= DecodeTable[j % DecodeTable.Length];
}
}
protected abstract void InitKey (uint key, uint[] k);
}
[Serializable]
public class ShojoMamaCrypt : KeyDecryptExtra
{
public ShojoMamaCrypt (uint key, byte[] bin) : base (key, bin)
{
}
protected override void InitKey (uint key, uint[] k)
{
k[0] = key + 1;
k[1] = key + 4;
k[2] = key + 2;
k[3] = key + 3;
}
}
[Serializable]
public class YuruPlusCrypt : KeyDecryptExtra
{
public YuruPlusCrypt (uint key, byte[] bin) : base (key, bin)
{
EncryptedSize = 0x100;
PostDataOffset = 0x204;
}
protected override void InitKey (uint key, uint[] k)
{
k[0] = key + 4;
k[1] = key + 3;
k[2] = key + 2;
k[3] = key + 1;
}
}
[Serializable]
public class TestamentCrypt : KeyDecryptExtra // Shinigami no Testament
{
public TestamentCrypt (uint key, byte[] bin) : base (key, bin)
{
}
protected override void InitKey (uint key, uint[] k)
{
k[0] = key + 3;
k[1] = key + 2;
k[2] = key + 1;
k[3] = key;
}
}
[Serializable]
public class MakiFesCrypt : KeyDecryptBase
{
public MakiFesCrypt (uint seed, byte[] key) : base (seed, key)
{
}
protected override void DecryptPre (byte[] data, int index, uint length)
{
uint k = Seed;
for (int i = 0; i < 0x100; ++i)
{
k = 0x343FD * k + 0x269EC3;
data[index+i] ^= DecodeTable[((int)(k >> 16) & 0x7FFF) % DecodeTable.Length];
}
}
}
[Serializable]
public class MajimeCrypt : IDecryptExtra
{
public void Decrypt (byte[] data, int index, uint length, uint flags)
{
if (length < 0x200)
return;
if ((flags & 0x202) == 0x202)
{
int sum = RotateBytesRight (data, index, 0x100);
data[index + 0x104] ^= (byte)sum;
data[index + 0x105] ^= (byte)(sum >> 8);
}
}
public void Encrypt (byte[] data, int index, uint length, uint flags)
{
if (length < 0x200)
return;
if ((flags & 0x102) == 0x102)
{
int sum = RotateBytesLeft (data, index, 0x100);
data[index + 0x104] ^= (byte)sum;
data[index + 0x105] ^= (byte)(sum >> 8);
}
}
internal int RotateBytesRight (byte[] data, int index, int length)
{
int sum = 0;
int bit = 0;
for (int i = 0; i < length; ++i)
{
byte v = data[index+i];
sum += v >> 1;
data[index+i] = (byte)(v >> 1 | bit);
bit = v << 7;
}
data[index] |= (byte)bit;
return sum;
}
internal int RotateBytesLeft (byte[] data, int index, int length)
{
int sum = 0;
int bit = 0;
for (int i = length-1; i >= 0; --i)
{
byte v = data[index+i];
sum += v & 0x7F;
data[index+i] = (byte)(v << 1 | bit);
bit = v >> 7;
}
data[index + length-1] |= (byte)bit;
return sum;
}
}
[Serializable]
public class NyaruCrypt : MajimeCrypt, IDecryptExtra
{
new public void Decrypt (byte[] data, int index, uint length, uint flags)
{
if (length < 0x200)
return;
if ((flags & 0x204) == 0x204)
{
int sum = RotateBytesRight (data, index, 0x100);
data[index + 0x100] ^= (byte)sum;
data[index + 0x101] ^= (byte)(sum >> 8);
}
}
new public void Encrypt (byte[] data, int index, uint length, uint flags)
{
if (length < 0x200)
return;
if ((flags & 0x104) == 0x104)
{
int sum = RotateBytesLeft (data, index, 0x100);
data[index + 0x100] ^= (byte)sum;
data[index + 0x101] ^= (byte)(sum >> 8);
}
}
}
[Serializable]
public class AlcotCrypt : IDecryptExtra
{
public void Decrypt (byte[] data, int index, uint length, uint flags)
{
if (length >= 0x400 && (flags & 0x204) == 0x204)
Crc16Crypt (data, index, (int)length);
}
public void Encrypt (byte[] data, int index, uint length, uint flags)
{
if (length >= 0x400 && (flags & 0x104) == 0x104)
Crc16Crypt (data, index, (int)length);
}
void Crc16Crypt (byte[] data, int index, int length)
{
var crc16 = new Crc16();
crc16.Update (data, index, length & 0x7E | 1);
var sum = crc16.Value ^ 0xFFFF;
data[index + 0x104] ^= (byte)sum;
data[index + 0x105] ^= (byte)(sum >> 8);
}
}
[Serializable]
public class DodakureCrypt : IDecryptExtra
{
public void Decrypt (byte[] data, int index, uint length, uint flags)
{
if (length < 0x200)
return;
if ((flags & 0x204) == 0x204)
{
if (0x718E958D == LittleEndian.ToUInt32 (data, index))
{
var input = new byte[0x200];
Buffer.BlockCopy (data, index, input, 0, 0x200);
int remaining = LittleEndian.ToInt32 (input, 8);
int src = 12;
int dst = index;
bool rle = false;
while (remaining > 0)
{
int count = input[src++];
if (rle)
{
byte v = data[dst-1];
for (int i = 0; i < count; ++i)
data[dst++] = v;
}
else
{
Buffer.BlockCopy (input, src, data, dst, count);
src += count;
dst += count;
}
remaining -= count;
if (count < 0xFF)
rle = !rle;
}
}
if (length > 0x200)
data[index + 0x200] ^= (byte)length;
if (length > 0x201)
data[index + 0x201] ^= (byte)(length >> 8);
if (length > 0x202)
data[index + 0x202] ^= (byte)(length >> 16);
if (length > 0x203)
data[index + 0x203] ^= (byte)(length >> 24);
}
}
public void Encrypt (byte[] data, int index, uint length, uint flags)
{
if (length < 0x200)
return;
if ((flags & 0x104) == 0x104)
{
throw new NotImplementedException();
}
}
}
[Serializable]
public class JokersCrypt : IDecryptExtra
{
public void Decrypt (byte[] data, int index, uint length, uint flags)
{
if (length < 0x400)
return;
if ((flags & 0x204) == 0x204)
{
if (0x718E958D == LittleEndian.ToUInt32 (data, index))
{
var input = new byte[0x200];
Buffer.BlockCopy (data, index, input, 0, 0x200);
int remaining = LittleEndian.ToInt32 (input, 8);
int src = 12;
int dst = index;
var ranges_hi = new uint[0x100];
var ranges_lo = new uint[0x101];
for (int i = 0; i < 0x100; ++i)
{
uint v = input[src++];
ranges_hi[i] = v;
ranges_lo[i+1] = v + ranges_lo[i];
}
uint denominator = ranges_lo[0x100];
var symbol_table = new byte[denominator];
uint low, high;
for (int i = 0; i < 0x100; ++i)
{
low = ranges_lo[i];
high = ranges_lo[i + 1];
int count = (int)(high - low);
for (int j = 0; j < count; ++j)
symbol_table[low + j] = (byte)i;
}
low = 0;
high = 0xFFFFFFFF;
uint current = BigEndian.ToUInt32 (input, src);
src += 4;
for (int i = 0; i < remaining; ++i)
{
uint range = high / denominator;
byte symbol = symbol_table[(current - low) / range];
data[index+i] = symbol;
low += ranges_lo[symbol] * range;
high = ranges_hi[symbol] * range;
while (0 == ((low ^ (high + low)) & 0xFF000000u))
{
low <<= 8;
high <<= 8;
current <<= 8;
current |= input[src++];
}
while (high < 0x10000)
{
low <<= 8;
high = 0x1000000 - (low & 0xFFFF00);
current <<= 8;
current |= input[src++];
}
}
}
data[index + 0x200] ^= (byte)length;
data[index + 0x201] ^= (byte)(length >> 8);
data[index + 0x202] ^= (byte)(length >> 16);
data[index + 0x203] ^= (byte)(length >> 24);
}
}
public void Encrypt (byte[] data, int index, uint length, uint flags)
{
if (length < 0x400)
return;
if ((flags & 0x104) == 0x104)
{
throw new NotImplementedException();
}
}
}
[Serializable]
public class KeyAdlerCrypt : KeyDecryptBase
{
public KeyAdlerCrypt (uint key) : base (key, null)
{
}
protected override void DecryptPre (byte[] data, int index, uint length)
{
uint key = Adler32.Compute (data, index, 0x100);
data[index + 0x204] ^= (byte)key;
data[index + 0x205] ^= (byte)(key >> 8);
data[index + 0x206] ^= (byte)(key >> 16);
data[index + 0x207] ^= (byte)(key >> 24);
}
}
[Serializable]
public class AdlerCrypt
{
internal void Transform (byte[] data, int index, int length)
{
uint key = Adler32.Compute (data, index, length);
data[index + 0x200] ^= (byte)key;
data[index + 0x201] ^= (byte)(key >> 8);
data[index + 0x202] ^= (byte)(key >> 16);
data[index + 0x203] ^= (byte)(key >> 24);
}
}
[Serializable]
public class PostAdlerCrypt : AdlerCrypt, IDecryptExtra
{
public void Decrypt (byte[] data, int index, uint length, uint flags)
{
if (length >= 0x400 && (flags & 0x204) == 0x204)
Transform (data, index, 0xFF);
}
public void Encrypt (byte[] data, int index, uint length, uint flags)
{
if (length >= 0x400 && (flags & 0x104) == 0x104)
Transform (data, index, 0xFF);
}
}
[Serializable]
public class PreAdlerCrypt : AdlerCrypt, IDecryptExtra
{
public void Decrypt (byte[] data, int index, uint length, uint flags)
{
if (length >= 0x400 && (flags & 0x202) == 0x202)
Transform (data, index, 0xFF);
}
public void Encrypt (byte[] data, int index, uint length, uint flags)
{
if (length >= 0x400 && (flags & 0x102) == 0x102)
Transform (data, index, 0xFF);
}
}
[Serializable]
public class BinboCrypt : IDecryptExtra
{
public void Decrypt (byte[] data, int index, uint length, uint flags)
{
if (length < 0x200)
return;
if ((flags & 0x204) == 0x204)
{
if (0x718E958D == LittleEndian.ToUInt32 (data, index))
{
var input = new byte[0x200];
Buffer.BlockCopy (data, index, input, 0, 0x200);
var reader = new LzComp (input, 8);
reader.Unpack (data, index);
}
if (length > 0x200)
data[index + 0x200] ^= (byte)length;
if (length > 0x201)
data[index + 0x201] ^= (byte)(length >> 8);
if (length > 0x202)
data[index + 0x202] ^= (byte)(length >> 16);
if (length > 0x203)
data[index + 0x203] ^= (byte)(length >> 24);
}
}
public void Encrypt (byte[] data, int index, uint length, uint flags)
{
if (length < 0x200)
return;
if ((flags & 0x104) == 0x104)
{
throw new NotImplementedException();
}
}
sealed class LzComp
{
byte[] m_input;
int m_src;
uint m_bits;
int m_bits_count;
public LzComp (byte[] input, int index)
{
m_input = input;
m_src = index;
}
public void Unpack (byte[] output, int dst)
{
FillBitCache();
while (m_src < m_input.Length)
{
if (GetBit() != 0)
{
output[dst++] = m_input[m_src++];
continue;
}
int count, offset;
if (GetBit() != 0)
{
count = LittleEndian.ToUInt16 (m_input, m_src);
m_src += 2;
offset = count >> 3 | -0x2000;
count &= 7;
if (count > 0)
{
count += 2;
}
else
{
count = m_input[m_src++];
if (0 == count)
break;
count += 9;
}
}
else
{
count = GetBit() << 1;
count |= GetBit();
count += 2;
offset = m_input[m_src++] | -0x100;
}
Binary.CopyOverlapped (output, dst+offset, dst, count);
dst += count;
}
}
int GetBit ()
{
uint v = m_bits >> --m_bits_count;
if (m_bits_count <= 0)
{
FillBitCache();
}
return (int)(v & 1);
}
void FillBitCache ()
{
m_bits = LittleEndian.ToUInt32 (m_input, m_src);
m_src += 4;
m_bits_count = 32;
}
}
}
[Serializable]
public class CountCrypt : IDecryptExtra
{
public void Decrypt (byte[] data, int index, uint length, uint flags)
{
if ((flags & 0x204) == 0x204)
DoCountCrypt (data, index, (int)length);
}
public void Encrypt (byte[] data, int index, uint length, uint flags)
{
if ((flags & 0x104) == 0x104)
DoCountCrypt (data, index, (int)length);
}
void DoCountCrypt (byte[] data, int index, int length)
{
if (length < 0x200)
return;
length = (length & 0x7E) | 1;
byte count_00 = 0, count_FF = 0;
for (int i = 0; i < length; ++i)
{
if (0xFF == data[index+i])
count_FF++;
else if (0 == data[index+i])
count_00++;
}
data[index + 0x100] ^= count_00;
data[index + 0x104] ^= count_FF;
}
}
[Serializable]
public class AltCountCrypt : IDecryptExtra
{
public void Decrypt (byte[] data, int index, uint length, uint flags)
{
if ((flags & 0x204) == 0x204)
DoCountCrypt (data, index, (int)length);
}
public void Encrypt (byte[] data, int index, uint length, uint flags)
{
if ((flags & 0x104) == 0x104)
DoCountCrypt (data, index, (int)length);
}
void DoCountCrypt (byte[] data, int index, int length)
{
if (length < 0x400)
return;
length = (length & 0x7E) | 1;
byte count_00 = 0, count_FF = 0;
for (int i = 0; i < length; ++i)
{
if (0xFF == data[index+i])
count_FF++;
else if (0 == data[index+i])
count_00++;
}
data[index + 0x100] ^= count_FF;
data[index + 0x104] ^= count_00;
}
}
[Serializable]
public class UshimitsuCrypt : IDecryptExtra
{
protected readonly uint m_key;
public UshimitsuCrypt (uint key)
{
m_key = key;
}
public void Decrypt (byte[] data, int index, uint length, uint flags)
{
if ((flags & 0x204) == 0x204)
DoCrypt (data, index, length);
}
public void Encrypt (byte[] data, int index, uint length, uint flags)
{
if ((flags & 0x104) == 0x104)
DoCrypt (data, index, length);
}
unsafe void DoCrypt (byte[] data, int index, uint length)
{
if (length < 0x100)
return;
fixed (byte* data8 = &data[index])
{
uint* data32 = (uint*)data8;
for (int i = 0; i < 0x40; ++i)
{
data32[i] ^= m_key;
}
}
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// VirtualNetworksOperations operations.
/// </summary>
public partial interface IVirtualNetworksOperations
{
/// <summary>
/// Deletes the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified virtual network by resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetwork>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a virtual network in the specified resource
/// group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update virtual network
/// operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetwork>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all virtual networks in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all virtual networks in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Checks whether a private IP address is available for use.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='ipAddress'>
/// The private IP address to be verified.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPAddressAvailabilityResult>> CheckIPAddressAvailabilityWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string ipAddress = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a virtual network in the specified resource
/// group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update virtual network
/// operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetwork>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all virtual networks in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all virtual networks in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
//
// Generated by NativeModuleBaseTests.tt
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using ReactNative.Bridge;
using System.Linq;
namespace ReactNative.Tests.Bridge
{
public partial class NativeModuleBaseTests
{
[Test]
public void NativeModuleBase_ReactMethod_ArgumentCountChecks()
{
var module = new ArgumentCountTestNativeModule();
var nopCallback = new InvokeCallback((_, __) => { });
var args = Enumerable.Range(0, 17);
module.Methods[nameof(ArgumentCountTestNativeModule.test0)].Invoke(nopCallback, JArray.FromObject(args.Take(0).ToArray()));
Assert.AreEqual(1, module.test0Calls);
module.Methods[nameof(ArgumentCountTestNativeModule.test1)].Invoke(nopCallback, JArray.FromObject(args.Take(1).ToArray()));
Assert.AreEqual(1, module.test1Calls);
module.Methods[nameof(ArgumentCountTestNativeModule.test2)].Invoke(nopCallback, JArray.FromObject(args.Take(2).ToArray()));
Assert.AreEqual(1, module.test2Calls);
module.Methods[nameof(ArgumentCountTestNativeModule.test3)].Invoke(nopCallback, JArray.FromObject(args.Take(3).ToArray()));
Assert.AreEqual(1, module.test3Calls);
module.Methods[nameof(ArgumentCountTestNativeModule.test4)].Invoke(nopCallback, JArray.FromObject(args.Take(4).ToArray()));
Assert.AreEqual(1, module.test4Calls);
module.Methods[nameof(ArgumentCountTestNativeModule.test5)].Invoke(nopCallback, JArray.FromObject(args.Take(5).ToArray()));
Assert.AreEqual(1, module.test5Calls);
module.Methods[nameof(ArgumentCountTestNativeModule.test6)].Invoke(nopCallback, JArray.FromObject(args.Take(6).ToArray()));
Assert.AreEqual(1, module.test6Calls);
module.Methods[nameof(ArgumentCountTestNativeModule.test7)].Invoke(nopCallback, JArray.FromObject(args.Take(7).ToArray()));
Assert.AreEqual(1, module.test7Calls);
module.Methods[nameof(ArgumentCountTestNativeModule.test8)].Invoke(nopCallback, JArray.FromObject(args.Take(8).ToArray()));
Assert.AreEqual(1, module.test8Calls);
module.Methods[nameof(ArgumentCountTestNativeModule.test9)].Invoke(nopCallback, JArray.FromObject(args.Take(9).ToArray()));
Assert.AreEqual(1, module.test9Calls);
module.Methods[nameof(ArgumentCountTestNativeModule.test10)].Invoke(nopCallback, JArray.FromObject(args.Take(10).ToArray()));
Assert.AreEqual(1, module.test10Calls);
module.Methods[nameof(ArgumentCountTestNativeModule.test11)].Invoke(nopCallback, JArray.FromObject(args.Take(11).ToArray()));
Assert.AreEqual(1, module.test11Calls);
module.Methods[nameof(ArgumentCountTestNativeModule.test12)].Invoke(nopCallback, JArray.FromObject(args.Take(12).ToArray()));
Assert.AreEqual(1, module.test12Calls);
module.Methods[nameof(ArgumentCountTestNativeModule.test13)].Invoke(nopCallback, JArray.FromObject(args.Take(13).ToArray()));
Assert.AreEqual(1, module.test13Calls);
module.Methods[nameof(ArgumentCountTestNativeModule.test14)].Invoke(nopCallback, JArray.FromObject(args.Take(14).ToArray()));
Assert.AreEqual(1, module.test14Calls);
module.Methods[nameof(ArgumentCountTestNativeModule.test15)].Invoke(nopCallback, JArray.FromObject(args.Take(15).ToArray()));
Assert.AreEqual(1, module.test15Calls);
module.Methods[nameof(ArgumentCountTestNativeModule.test16)].Invoke(nopCallback, JArray.FromObject(args.Take(16).ToArray()));
Assert.AreEqual(1, module.test16Calls);
module.Methods[nameof(ArgumentCountTestNativeModule.test17)].Invoke(nopCallback, JArray.FromObject(args.Take(17).ToArray()));
Assert.AreEqual(1, module.test17Calls);
}
class ArgumentCountTestNativeModule : NativeModuleBase
{
public override string Name => "Test";
public int test0Calls;
[ReactMethod]
public void test0()
{
test0Calls++;
}
public int test1Calls;
[ReactMethod]
public void test1(int arg0)
{
test1Calls++;
Assert.AreEqual(0, arg0);
}
public int test2Calls;
[ReactMethod]
public void test2(int arg0, int arg1)
{
test2Calls++;
Assert.AreEqual(0, arg0);
Assert.AreEqual(1, arg1);
}
public int test3Calls;
[ReactMethod]
public void test3(int arg0, int arg1, int arg2)
{
test3Calls++;
Assert.AreEqual(0, arg0);
Assert.AreEqual(1, arg1);
Assert.AreEqual(2, arg2);
}
public int test4Calls;
[ReactMethod]
public void test4(int arg0, int arg1, int arg2, int arg3)
{
test4Calls++;
Assert.AreEqual(0, arg0);
Assert.AreEqual(1, arg1);
Assert.AreEqual(2, arg2);
Assert.AreEqual(3, arg3);
}
public int test5Calls;
[ReactMethod]
public void test5(int arg0, int arg1, int arg2, int arg3, int arg4)
{
test5Calls++;
Assert.AreEqual(0, arg0);
Assert.AreEqual(1, arg1);
Assert.AreEqual(2, arg2);
Assert.AreEqual(3, arg3);
Assert.AreEqual(4, arg4);
}
public int test6Calls;
[ReactMethod]
public void test6(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5)
{
test6Calls++;
Assert.AreEqual(0, arg0);
Assert.AreEqual(1, arg1);
Assert.AreEqual(2, arg2);
Assert.AreEqual(3, arg3);
Assert.AreEqual(4, arg4);
Assert.AreEqual(5, arg5);
}
public int test7Calls;
[ReactMethod]
public void test7(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6)
{
test7Calls++;
Assert.AreEqual(0, arg0);
Assert.AreEqual(1, arg1);
Assert.AreEqual(2, arg2);
Assert.AreEqual(3, arg3);
Assert.AreEqual(4, arg4);
Assert.AreEqual(5, arg5);
Assert.AreEqual(6, arg6);
}
public int test8Calls;
[ReactMethod]
public void test8(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7)
{
test8Calls++;
Assert.AreEqual(0, arg0);
Assert.AreEqual(1, arg1);
Assert.AreEqual(2, arg2);
Assert.AreEqual(3, arg3);
Assert.AreEqual(4, arg4);
Assert.AreEqual(5, arg5);
Assert.AreEqual(6, arg6);
Assert.AreEqual(7, arg7);
}
public int test9Calls;
[ReactMethod]
public void test9(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8)
{
test9Calls++;
Assert.AreEqual(0, arg0);
Assert.AreEqual(1, arg1);
Assert.AreEqual(2, arg2);
Assert.AreEqual(3, arg3);
Assert.AreEqual(4, arg4);
Assert.AreEqual(5, arg5);
Assert.AreEqual(6, arg6);
Assert.AreEqual(7, arg7);
Assert.AreEqual(8, arg8);
}
public int test10Calls;
[ReactMethod]
public void test10(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9)
{
test10Calls++;
Assert.AreEqual(0, arg0);
Assert.AreEqual(1, arg1);
Assert.AreEqual(2, arg2);
Assert.AreEqual(3, arg3);
Assert.AreEqual(4, arg4);
Assert.AreEqual(5, arg5);
Assert.AreEqual(6, arg6);
Assert.AreEqual(7, arg7);
Assert.AreEqual(8, arg8);
Assert.AreEqual(9, arg9);
}
public int test11Calls;
[ReactMethod]
public void test11(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10)
{
test11Calls++;
Assert.AreEqual(0, arg0);
Assert.AreEqual(1, arg1);
Assert.AreEqual(2, arg2);
Assert.AreEqual(3, arg3);
Assert.AreEqual(4, arg4);
Assert.AreEqual(5, arg5);
Assert.AreEqual(6, arg6);
Assert.AreEqual(7, arg7);
Assert.AreEqual(8, arg8);
Assert.AreEqual(9, arg9);
Assert.AreEqual(10, arg10);
}
public int test12Calls;
[ReactMethod]
public void test12(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11)
{
test12Calls++;
Assert.AreEqual(0, arg0);
Assert.AreEqual(1, arg1);
Assert.AreEqual(2, arg2);
Assert.AreEqual(3, arg3);
Assert.AreEqual(4, arg4);
Assert.AreEqual(5, arg5);
Assert.AreEqual(6, arg6);
Assert.AreEqual(7, arg7);
Assert.AreEqual(8, arg8);
Assert.AreEqual(9, arg9);
Assert.AreEqual(10, arg10);
Assert.AreEqual(11, arg11);
}
public int test13Calls;
[ReactMethod]
public void test13(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11, int arg12)
{
test13Calls++;
Assert.AreEqual(0, arg0);
Assert.AreEqual(1, arg1);
Assert.AreEqual(2, arg2);
Assert.AreEqual(3, arg3);
Assert.AreEqual(4, arg4);
Assert.AreEqual(5, arg5);
Assert.AreEqual(6, arg6);
Assert.AreEqual(7, arg7);
Assert.AreEqual(8, arg8);
Assert.AreEqual(9, arg9);
Assert.AreEqual(10, arg10);
Assert.AreEqual(11, arg11);
Assert.AreEqual(12, arg12);
}
public int test14Calls;
[ReactMethod]
public void test14(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11, int arg12, int arg13)
{
test14Calls++;
Assert.AreEqual(0, arg0);
Assert.AreEqual(1, arg1);
Assert.AreEqual(2, arg2);
Assert.AreEqual(3, arg3);
Assert.AreEqual(4, arg4);
Assert.AreEqual(5, arg5);
Assert.AreEqual(6, arg6);
Assert.AreEqual(7, arg7);
Assert.AreEqual(8, arg8);
Assert.AreEqual(9, arg9);
Assert.AreEqual(10, arg10);
Assert.AreEqual(11, arg11);
Assert.AreEqual(12, arg12);
Assert.AreEqual(13, arg13);
}
public int test15Calls;
[ReactMethod]
public void test15(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11, int arg12, int arg13, int arg14)
{
test15Calls++;
Assert.AreEqual(0, arg0);
Assert.AreEqual(1, arg1);
Assert.AreEqual(2, arg2);
Assert.AreEqual(3, arg3);
Assert.AreEqual(4, arg4);
Assert.AreEqual(5, arg5);
Assert.AreEqual(6, arg6);
Assert.AreEqual(7, arg7);
Assert.AreEqual(8, arg8);
Assert.AreEqual(9, arg9);
Assert.AreEqual(10, arg10);
Assert.AreEqual(11, arg11);
Assert.AreEqual(12, arg12);
Assert.AreEqual(13, arg13);
Assert.AreEqual(14, arg14);
}
public int test16Calls;
[ReactMethod]
public void test16(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11, int arg12, int arg13, int arg14, int arg15)
{
test16Calls++;
Assert.AreEqual(0, arg0);
Assert.AreEqual(1, arg1);
Assert.AreEqual(2, arg2);
Assert.AreEqual(3, arg3);
Assert.AreEqual(4, arg4);
Assert.AreEqual(5, arg5);
Assert.AreEqual(6, arg6);
Assert.AreEqual(7, arg7);
Assert.AreEqual(8, arg8);
Assert.AreEqual(9, arg9);
Assert.AreEqual(10, arg10);
Assert.AreEqual(11, arg11);
Assert.AreEqual(12, arg12);
Assert.AreEqual(13, arg13);
Assert.AreEqual(14, arg14);
Assert.AreEqual(15, arg15);
}
public int test17Calls;
[ReactMethod]
public void test17(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11, int arg12, int arg13, int arg14, int arg15, int arg16)
{
test17Calls++;
Assert.AreEqual(0, arg0);
Assert.AreEqual(1, arg1);
Assert.AreEqual(2, arg2);
Assert.AreEqual(3, arg3);
Assert.AreEqual(4, arg4);
Assert.AreEqual(5, arg5);
Assert.AreEqual(6, arg6);
Assert.AreEqual(7, arg7);
Assert.AreEqual(8, arg8);
Assert.AreEqual(9, arg9);
Assert.AreEqual(10, arg10);
Assert.AreEqual(11, arg11);
Assert.AreEqual(12, arg12);
Assert.AreEqual(13, arg13);
Assert.AreEqual(14, arg14);
Assert.AreEqual(15, arg15);
Assert.AreEqual(16, arg16);
}
}
}
}
| |
using System;
using System.Collections.Generic;
class SequenceInMatrix
{
public static void Main()
{
string input = Console.ReadLine();
string[] dimensions = input.Split(new char[] { ' ' });
int N = int.Parse(dimensions[0]);
int M = int.Parse(dimensions[1]);
string[,] matrix = new string[N, M];
// Initialize matrix
for (int i = 0; i < N; i++)
{
input = Console.ReadLine();
string[] elements = input.Split(new char[] { ' ' });
for (int j = 0; j < M; j++)
{
matrix[i, j] = elements[j];
}
}
// DFS
// https://zeroreversesoft.wordpress.com/2013/02/17/searching-for-the-largest-area-of-equal-elements-in-a-matrix-using-bfsdfs-hybrid-algorithm/
bool[,] visitedCells = new bool[N, M];
Stack<int> branchingCellRow = new Stack<int>();
Stack<int> branchingCellCol = new Stack<int>();
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
int maxSequenceLength = 0;
int currentSequenceLength = 0;
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < cols; col++)
{
string currentValue = matrix[row, col];
bool isBranching = false;
bool isVisited = visitedCells[row, col];
if (col - 1 >= 0 && matrix[row, col - 1] == currentValue &&
visitedCells[row, col - 1] == false) // left
{
isBranching = true;
}
else if (col + 1 < cols && matrix[row, col + 1] == currentValue &&
visitedCells[row, col + 1] == false) // right
{
isBranching = true;
}
else if (row - 1 >= 0 && matrix[row - 1, col] == currentValue &&
visitedCells[row - 1, col] == false) // up
{
isBranching = true;
}
else if (row + 1 < rows && matrix[row + 1, col] == currentValue &&
visitedCells[row + 1, col] == false) // down
{
isBranching = true;
}
else if (col - 1 >= 0 && row - 1 >= 0 && matrix[row - 1, col - 1] == currentValue &&
visitedCells[row - 1, col - 1] == false) // left up
{
isBranching = true;
}
else if (col + 1 < cols && row - 1 >= 0 && matrix[row - 1, col + 1] == currentValue &&
visitedCells[row - 1, col + 1] == false) //right up
{
isBranching = true;
}
else if (col - 1 >= 0 && row + 1 < rows && matrix[row + 1, col - 1] == currentValue &&
visitedCells[row + 1, col - 1] == false) // left down
{
isBranching = true;
}
else if (col + 1 < cols && row + 1 < rows && matrix[row + 1, col + 1] == currentValue &&
visitedCells[row + 1, col + 1] == false) // right down
{
isBranching = true;
}
if (!isVisited && isBranching)
{
branchingCellRow.Push(row);
branchingCellCol.Push(col);
while (branchingCellRow.Count > 0 && branchingCellRow.Count > 0)
{
row = branchingCellRow.Pop();
col = branchingCellCol.Pop();
int tempRow = row;
int tempCol = col;
// ---------- Vertical/Horizontal ------------
while (tempCol - 1 >= 0 && matrix[tempRow, tempCol - 1] == currentValue &&
visitedCells[tempRow, tempCol - 1] == false) // left
{
tempCol = tempCol - 1;
branchingCellRow.Push(tempRow);
branchingCellCol.Push(tempCol);
visitedCells[tempRow, tempCol] = true;
currentSequenceLength++;
}
tempRow = row;
tempCol = col;
while (tempCol + 1 < cols && matrix[tempRow, tempCol + 1] == currentValue &&
visitedCells[tempRow, tempCol + 1] == false) //right
{
tempCol = tempCol + 1;
branchingCellCol.Push(tempCol);
branchingCellRow.Push(tempRow);
visitedCells[tempRow, tempCol] = true;
currentSequenceLength++;
}
tempRow = row;
tempCol = col;
while (tempRow - 1 >= 0 && matrix[tempRow - 1, tempCol] == currentValue &&
visitedCells[tempRow - 1, tempCol] == false) //up
{
tempRow = tempRow - 1;
branchingCellCol.Push(tempCol);
branchingCellRow.Push(tempRow);
visitedCells[tempRow, tempCol] = true;
currentSequenceLength++;
}
tempRow = row;
tempCol = col;
while (tempRow + 1 < rows && matrix[tempRow + 1, tempCol] == currentValue &&
visitedCells[tempRow + 1, tempCol] == false) //down
{
tempRow = tempRow + 1;
branchingCellCol.Push(tempCol);
branchingCellRow.Push(tempRow);
visitedCells[tempRow, tempCol] = true;
currentSequenceLength++;
}
tempRow = row;
tempCol = col;
// ---------- Diagonals ------------
while (tempCol - 1 >= 0 && tempRow - 1 >= 0
&& matrix[tempRow - 1, tempCol - 1] == currentValue &&
visitedCells[tempRow - 1, tempCol - 1] == false) // left up
{
tempCol = tempCol - 1;
tempRow = tempRow - 1;
branchingCellRow.Push(tempRow);
branchingCellCol.Push(tempCol);
visitedCells[tempRow, tempCol] = true;
currentSequenceLength++;
}
tempRow = row;
tempCol = col;
while (tempCol + 1 < cols && tempRow - 1 >= 0 &&
matrix[tempRow - 1, tempCol + 1] == currentValue &&
visitedCells[tempRow - 1, tempCol + 1] == false) //right up
{
tempCol = tempCol + 1;
tempRow = tempRow - 1;
branchingCellCol.Push(tempCol);
branchingCellRow.Push(tempRow);
visitedCells[tempRow, tempCol] = true;
currentSequenceLength++;
}
tempRow = row;
tempCol = col;
while (tempRow + 1 < rows && tempCol - 1 >= 0 &&
matrix[tempRow + 1, tempCol - 1] == currentValue &&
visitedCells[tempRow + 1, tempCol - 1] == false) // left down
{
tempRow = tempRow + 1;
tempCol = tempCol - 1;
branchingCellCol.Push(tempCol);
branchingCellRow.Push(tempRow);
visitedCells[tempRow, tempCol] = true;
currentSequenceLength++;
}
tempRow = row;
tempCol = col;
while (tempRow + 1 < rows && tempCol + 1 < cols &&
matrix[tempRow + 1, tempCol + 1] == currentValue &&
visitedCells[tempRow + 1, tempCol + 1] == false) //right down
{
tempRow = tempRow + 1;
tempCol = tempCol + 1;
branchingCellCol.Push(tempCol);
branchingCellRow.Push(tempRow);
visitedCells[tempRow, tempCol] = true;
currentSequenceLength++;
}
}
if (currentSequenceLength > maxSequenceLength)
{
maxSequenceLength = currentSequenceLength;
}
currentSequenceLength = 0;
}
}
}
Console.WriteLine(maxSequenceLength);
}
}
| |
// Copyright (c) rubicon IT GmbH, www.rubicon.eu
//
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership. rubicon 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.Generic;
using System.Collections.ObjectModel;
using System.Linq.Expressions;
using System.Reflection;
using TITcs.SharePoint.Query.LinqProvider.Clauses.Expressions;
using TITcs.SharePoint.Query.SharedSource.Utilities;
namespace TITcs.SharePoint.Query.LinqProvider.Parsing
{
/// <summary>
/// Provides a base class that can be used for visiting and optionally transforming each node of an <see cref="Expression"/> tree in a
/// strongly typed fashion.
/// This is the base class of many transformation classes.
/// </summary>
public abstract class ExpressionTreeVisitor
{
/// <summary>
/// Determines whether the given <see cref="Expression"/> is one of the expressions defined by <see cref="ExpressionType"/> for which
/// <see cref="ExpressionTreeVisitor"/> has a Visit method. <see cref="VisitExpression"/> handles those by calling the respective Visit method.
/// </summary>
/// <param name="expression">The expression to check. Must not be <see langword="null" />.</param>
/// <returns>
/// <see langword="true"/> if <paramref name="expression"/> is one of the expressions defined by <see cref="ExpressionType"/> and
/// <see cref="ExpressionTreeVisitor"/> has a Visit method for it; otherwise, <see langword="false"/>.
/// </returns>
// Note: Do not use Enum.IsDefined here - this method must only return true if we have a dedicated Visit method. (Which may not be the case for
// future extensions of ExpressionType.)
public static bool IsSupportedStandardExpression (Expression expression)
{
ArgumentUtility.CheckNotNull ("expression", expression);
switch (expression.NodeType)
{
case ExpressionType.ArrayLength:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.Not:
case ExpressionType.Quote:
case ExpressionType.TypeAs:
case ExpressionType.UnaryPlus:
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.Divide:
case ExpressionType.Modulo:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.Power:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
case ExpressionType.And:
case ExpressionType.Or:
case ExpressionType.ExclusiveOr:
case ExpressionType.LeftShift:
case ExpressionType.RightShift:
case ExpressionType.AndAlso:
case ExpressionType.OrElse:
case ExpressionType.Equal:
case ExpressionType.NotEqual:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.Coalesce:
case ExpressionType.ArrayIndex:
case ExpressionType.Conditional:
case ExpressionType.Constant:
case ExpressionType.Invoke:
case ExpressionType.Lambda:
case ExpressionType.MemberAccess:
case ExpressionType.Call:
case ExpressionType.New:
case ExpressionType.NewArrayBounds:
case ExpressionType.NewArrayInit:
case ExpressionType.MemberInit:
case ExpressionType.ListInit:
case ExpressionType.Parameter:
case ExpressionType.TypeIs:
return true;
}
return false;
}
/// <summary>
/// Determines whether the given <see cref="Expression"/> is one of the base expressions defined by re-linq.
/// <see cref="VisitExpression"/> handles those by calling the respective Visit method.
/// </summary>
/// <param name="expression">The expression to check.</param>
/// <returns>
/// <see langword="true"/> if <paramref name="expression"/> is a re-linq base expression (<see cref="SubQueryExpression"/>,
/// <see cref="QuerySourceReferenceExpression"/>) for which <see cref="ExpressionTreeVisitor"/> has dedicated Visit methods;
/// otherwise, <see langword="false"/>.
/// </returns>
public static bool IsRelinqExpression (Expression expression)
{
ArgumentUtility.CheckNotNull ("expression", expression);
switch (expression.NodeType)
{
case SubQueryExpression.ExpressionType:
case QuerySourceReferenceExpression.ExpressionType:
return true;
default:
return false;
}
}
/// <summary>
/// Determines whether the given <see cref="Expression"/> is an <see cref="ExtensionExpression"/>. <see cref="VisitExpression"/> handles such
/// expressions by calling <see cref="ExtensionExpression.Accept"/>.
/// </summary>
/// <param name="expression">The expression to check.</param>
/// <returns>
/// <see langword="true"/> if <paramref name="expression"/> is an <see cref="ExtensionExpression"/>; otherwise, <see langword="false"/>.
/// </returns>
public static bool IsExtensionExpression (Expression expression)
{
ArgumentUtility.CheckNotNull ("expression", expression);
return expression is ExtensionExpression;
}
/// <summary>
/// Determines whether the given <see cref="Expression"/> is an unknown expression not derived from <see cref="ExtensionExpression"/>.
/// <see cref="VisitExpression"/> cannot handle such expressions at all and will call <see cref="VisitUnknownNonExtensionExpression"/> for them.
/// </summary>
/// <param name="expression">The expression to check.</param>
/// <returns>
/// <see langword="true"/> if <paramref name="expression"/> is an unknown expression not derived from <see cref="ExtensionExpression"/>;
/// otherwise, <see langword="false"/>.
/// </returns>
public static bool IsUnknownNonExtensionExpression (Expression expression)
{
ArgumentUtility.CheckNotNull ("expression", expression);
return !IsSupportedStandardExpression (expression) && !IsExtensionExpression (expression) && !IsRelinqExpression (expression);
}
/// <summary>
/// Adjusts the arguments for a <see cref="NewExpression"/> so that they match the given members.
/// </summary>
/// <param name="arguments">The arguments to adjust.</param>
/// <param name="members">The members defining the required argument types.</param>
/// <returns>
/// A sequence of expressions that are equivalent to <paramref name="arguments"/>, but converted to the associated member's
/// result type if needed.
/// </returns>
public static IEnumerable<Expression> AdjustArgumentsForNewExpression (IList<Expression> arguments, IList<MemberInfo> members)
{
ArgumentUtility.CheckNotNull ("arguments", arguments);
ArgumentUtility.CheckNotNull ("members", members);
Assertion.IsTrue (arguments.Count == members.Count);
for (int i = 0; i < arguments.Count; ++i)
{
var memberReturnType = ReflectionUtility.GetMemberReturnType (members[i]);
if (arguments[i].Type == memberReturnType)
yield return arguments[i];
else
yield return Expression.Convert (arguments[i], memberReturnType);
}
}
public virtual Expression VisitExpression (Expression expression)
{
if (expression == null)
return null;
var extensionExpression = expression as ExtensionExpression;
if (extensionExpression != null)
return extensionExpression.Accept (this);
switch (expression.NodeType)
{
case ExpressionType.ArrayLength:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.Not:
case ExpressionType.Quote:
case ExpressionType.TypeAs:
case ExpressionType.UnaryPlus:
return VisitUnaryExpression ((UnaryExpression) expression);
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.Divide:
case ExpressionType.Modulo:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.Power:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
case ExpressionType.And:
case ExpressionType.Or:
case ExpressionType.ExclusiveOr:
case ExpressionType.LeftShift:
case ExpressionType.RightShift:
case ExpressionType.AndAlso:
case ExpressionType.OrElse:
case ExpressionType.Equal:
case ExpressionType.NotEqual:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.Coalesce:
case ExpressionType.ArrayIndex:
return VisitBinaryExpression ((BinaryExpression) expression);
case ExpressionType.Conditional:
return VisitConditionalExpression ((ConditionalExpression) expression);
case ExpressionType.Constant:
return VisitConstantExpression ((ConstantExpression) expression);
case ExpressionType.Invoke:
return VisitInvocationExpression ((InvocationExpression) expression);
case ExpressionType.Lambda:
return VisitLambdaExpression ((LambdaExpression) expression);
case ExpressionType.MemberAccess:
return VisitMemberExpression ((MemberExpression) expression);
case ExpressionType.Call:
return VisitMethodCallExpression ((MethodCallExpression) expression);
case ExpressionType.New:
return VisitNewExpression ((NewExpression) expression);
case ExpressionType.NewArrayBounds:
case ExpressionType.NewArrayInit:
return VisitNewArrayExpression ((NewArrayExpression) expression);
case ExpressionType.MemberInit:
return VisitMemberInitExpression ((MemberInitExpression) expression);
case ExpressionType.ListInit:
return VisitListInitExpression ((ListInitExpression) expression);
case ExpressionType.Parameter:
return VisitParameterExpression ((ParameterExpression) expression);
case ExpressionType.TypeIs:
return VisitTypeBinaryExpression ((TypeBinaryExpression) expression);
case SubQueryExpression.ExpressionType:
return VisitSubQueryExpression ((SubQueryExpression) expression);
case QuerySourceReferenceExpression.ExpressionType:
return VisitQuerySourceReferenceExpression ((QuerySourceReferenceExpression) expression);
default:
return VisitUnknownNonExtensionExpression (expression);
}
}
public virtual T VisitAndConvert<T> (T expression, string methodName) where T : Expression
{
ArgumentUtility.CheckNotNull ("methodName", methodName);
if (expression == null)
return null;
var newExpression = VisitExpression (expression) as T;
if (newExpression == null)
{
var message = string.Format (
"When called from '{0}', expressions of type '{1}' can only be replaced with other non-null expressions of type '{2}'.",
methodName,
typeof (T).Name,
typeof (T).Name);
throw new InvalidOperationException (message);
}
return newExpression;
}
public virtual ReadOnlyCollection<T> VisitAndConvert<T> (ReadOnlyCollection<T> expressions, string callerName) where T : Expression
{
ArgumentUtility.CheckNotNull ("expressions", expressions);
ArgumentUtility.CheckNotNullOrEmpty ("callerName", callerName);
return VisitList (expressions, expression => VisitAndConvert (expression, callerName));
}
public ReadOnlyCollection<T> VisitList<T> (ReadOnlyCollection<T> list, Func<T, T> visitMethod)
where T : class
{
ArgumentUtility.CheckNotNull ("list", list);
ArgumentUtility.CheckNotNull ("visitMethod", visitMethod);
List<T> newList = null;
for (int i = 0; i < list.Count; i++)
{
T element = list[i];
T newElement = visitMethod (element);
if (newElement == null)
throw new NotSupportedException ("The current list only supports objects of type '" + typeof (T).Name + "' as its elements.");
if (element != newElement)
{
if (newList == null)
newList = new List<T> (list);
newList[i] = newElement;
}
}
if (newList != null)
return new ReadOnlyCollection<T> (newList);
else
return list;
}
protected internal virtual Expression VisitExtensionExpression (ExtensionExpression expression)
{
ArgumentUtility.CheckNotNull ("expression", expression);
return expression.VisitChildren (this);
}
protected internal virtual Expression VisitUnknownNonExtensionExpression (Expression expression)
{
ArgumentUtility.CheckNotNull ("expression", expression);
var message = string.Format ("Expression type '{0}' is not supported by this {1}.", expression.GetType().Name, GetType ().Name);
throw new NotSupportedException (message);
}
protected virtual Expression VisitUnaryExpression (UnaryExpression expression)
{
ArgumentUtility.CheckNotNull ("expression", expression);
Expression newOperand = VisitExpression (expression.Operand);
if (newOperand != expression.Operand)
{
if (expression.NodeType == ExpressionType.UnaryPlus)
return Expression.UnaryPlus (newOperand, expression.Method);
else
return Expression.MakeUnary (expression.NodeType, newOperand, expression.Type, expression.Method);
}
else
return expression;
}
protected virtual Expression VisitBinaryExpression (BinaryExpression expression)
{
ArgumentUtility.CheckNotNull ("expression", expression);
Expression newLeft = VisitExpression (expression.Left);
Expression newRight = VisitExpression (expression.Right);
var newConversion = (LambdaExpression) VisitExpression (expression.Conversion);
if (newLeft != expression.Left || newRight != expression.Right || newConversion != expression.Conversion)
return Expression.MakeBinary (expression.NodeType, newLeft, newRight, expression.IsLiftedToNull, expression.Method, newConversion);
return expression;
}
protected virtual Expression VisitTypeBinaryExpression (TypeBinaryExpression expression)
{
ArgumentUtility.CheckNotNull ("expression", expression);
Expression newExpression = VisitExpression (expression.Expression);
if (newExpression != expression.Expression)
return Expression.TypeIs (newExpression, expression.TypeOperand);
return expression;
}
protected virtual Expression VisitConstantExpression (ConstantExpression expression)
{
ArgumentUtility.CheckNotNull ("expression", expression);
return expression;
}
protected virtual Expression VisitConditionalExpression (ConditionalExpression expression)
{
ArgumentUtility.CheckNotNull ("expression", expression);
Expression newTest = VisitExpression (expression.Test);
Expression newFalse = VisitExpression (expression.IfFalse);
Expression newTrue = VisitExpression (expression.IfTrue);
if ((newTest != expression.Test) || (newFalse != expression.IfFalse) || (newTrue != expression.IfTrue))
return Expression.Condition (newTest, newTrue, newFalse, expression.Type);
return expression;
}
protected virtual Expression VisitParameterExpression (ParameterExpression expression)
{
ArgumentUtility.CheckNotNull ("expression", expression);
return expression;
}
protected virtual Expression VisitLambdaExpression (LambdaExpression expression)
{
ArgumentUtility.CheckNotNull ("expression", expression);
ReadOnlyCollection<ParameterExpression> newParameters = VisitAndConvert (expression.Parameters, "VisitLambdaExpression");
Expression newBody = VisitExpression (expression.Body);
if ((newBody != expression.Body) || (newParameters != expression.Parameters))
return Expression.Lambda (expression.Type, newBody, newParameters);
return expression;
}
protected virtual Expression VisitMethodCallExpression (MethodCallExpression expression)
{
ArgumentUtility.CheckNotNull ("expression", expression);
Expression newObject = VisitExpression (expression.Object);
ReadOnlyCollection<Expression> newArguments = VisitAndConvert (expression.Arguments, "VisitMethodCallExpression");
if ((newObject != expression.Object) || (newArguments != expression.Arguments))
return Expression.Call (newObject, expression.Method, newArguments);
return expression;
}
protected virtual Expression VisitInvocationExpression (InvocationExpression expression)
{
ArgumentUtility.CheckNotNull ("expression", expression);
Expression newExpression = VisitExpression (expression.Expression);
ReadOnlyCollection<Expression> newArguments = VisitAndConvert (expression.Arguments, "VisitInvocationExpression");
if ((newExpression != expression.Expression) || (newArguments != expression.Arguments))
return Expression.Invoke (newExpression, newArguments);
return expression;
}
protected virtual Expression VisitMemberExpression (MemberExpression expression)
{
ArgumentUtility.CheckNotNull ("expression", expression);
Expression newExpression = VisitExpression (expression.Expression);
if (newExpression != expression.Expression)
return Expression.MakeMemberAccess (newExpression, expression.Member);
return expression;
}
protected virtual Expression VisitNewExpression (NewExpression expression)
{
ArgumentUtility.CheckNotNull ("expression", expression);
ReadOnlyCollection<Expression> newArguments = VisitAndConvert (expression.Arguments, "VisitNewExpression");
if (newArguments != expression.Arguments)
{
// This ReSharper warning is wrong - expression.Members can be null
// ReSharper disable ConditionIsAlwaysTrueOrFalse
// ReSharper disable HeuristicUnreachableCode
if (expression.Members == null)
return Expression.New (expression.Constructor, newArguments);
// ReSharper restore HeuristicUnreachableCode
// ReSharper restore ConditionIsAlwaysTrueOrFalse
else
return Expression.New (expression.Constructor, AdjustArgumentsForNewExpression (newArguments, expression.Members), expression.Members);
}
return expression;
}
protected virtual Expression VisitNewArrayExpression (NewArrayExpression expression)
{
ArgumentUtility.CheckNotNull ("expression", expression);
ReadOnlyCollection<Expression> newExpressions = VisitAndConvert (expression.Expressions, "VisitNewArrayExpression");
if (newExpressions != expression.Expressions)
{
var elementType = expression.Type.GetElementType();
if (expression.NodeType == ExpressionType.NewArrayInit)
return Expression.NewArrayInit (elementType, newExpressions);
else
return Expression.NewArrayBounds (elementType, newExpressions);
}
return expression;
}
protected virtual Expression VisitMemberInitExpression (MemberInitExpression expression)
{
ArgumentUtility.CheckNotNull ("expression", expression);
var newNewExpression = VisitExpression (expression.NewExpression) as NewExpression;
if (newNewExpression == null)
{
throw new NotSupportedException (
"MemberInitExpressions only support non-null instances of type 'NewExpression' as their NewExpression member.");
}
ReadOnlyCollection<MemberBinding> newBindings = VisitMemberBindingList (expression.Bindings);
if (newNewExpression != expression.NewExpression || newBindings != expression.Bindings)
return Expression.MemberInit (newNewExpression, newBindings);
return expression;
}
protected virtual Expression VisitListInitExpression (ListInitExpression expression)
{
ArgumentUtility.CheckNotNull ("expression", expression);
var newNewExpression = VisitExpression (expression.NewExpression) as NewExpression;
if (newNewExpression == null)
throw new NotSupportedException ("ListInitExpressions only support non-null instances of type 'NewExpression' as their NewExpression member.");
ReadOnlyCollection<ElementInit> newInitializers = VisitElementInitList (expression.Initializers);
if (newNewExpression != expression.NewExpression || newInitializers != expression.Initializers)
return Expression.ListInit (newNewExpression, newInitializers);
return expression;
}
protected virtual ElementInit VisitElementInit (ElementInit elementInit)
{
ArgumentUtility.CheckNotNull ("elementInit", elementInit);
ReadOnlyCollection<Expression> newArguments = VisitAndConvert (elementInit.Arguments, "VisitElementInit");
if (newArguments != elementInit.Arguments)
return Expression.ElementInit (elementInit.AddMethod, newArguments);
return elementInit;
}
protected virtual MemberBinding VisitMemberBinding (MemberBinding memberBinding)
{
ArgumentUtility.CheckNotNull ("memberBinding", memberBinding);
switch (memberBinding.BindingType)
{
case MemberBindingType.Assignment:
return VisitMemberAssignment ((MemberAssignment) memberBinding);
case MemberBindingType.MemberBinding:
return VisitMemberMemberBinding ((MemberMemberBinding) memberBinding);
default:
Assertion.DebugAssert (
memberBinding.BindingType == MemberBindingType.ListBinding, "Invalid member binding type " + memberBinding.GetType().FullName);
return VisitMemberListBinding ((MemberListBinding) memberBinding);
}
}
protected virtual MemberBinding VisitMemberAssignment (MemberAssignment memberAssigment)
{
ArgumentUtility.CheckNotNull ("memberAssigment", memberAssigment);
Expression expression = VisitExpression (memberAssigment.Expression);
if (expression != memberAssigment.Expression)
return Expression.Bind (memberAssigment.Member, expression);
return memberAssigment;
}
protected virtual MemberBinding VisitMemberMemberBinding (MemberMemberBinding binding)
{
ArgumentUtility.CheckNotNull ("binding", binding);
ReadOnlyCollection<MemberBinding> newBindings = VisitMemberBindingList (binding.Bindings);
if (newBindings != binding.Bindings)
return Expression.MemberBind (binding.Member, newBindings);
return binding;
}
protected virtual MemberBinding VisitMemberListBinding (MemberListBinding listBinding)
{
ArgumentUtility.CheckNotNull ("listBinding", listBinding);
ReadOnlyCollection<ElementInit> newInitializers = VisitElementInitList (listBinding.Initializers);
if (newInitializers != listBinding.Initializers)
return Expression.ListBind (listBinding.Member, newInitializers);
return listBinding;
}
protected virtual ReadOnlyCollection<MemberBinding> VisitMemberBindingList (ReadOnlyCollection<MemberBinding> expressions)
{
return VisitList (expressions, VisitMemberBinding);
}
protected virtual ReadOnlyCollection<ElementInit> VisitElementInitList (ReadOnlyCollection<ElementInit> expressions)
{
return VisitList (expressions, VisitElementInit);
}
protected virtual Expression VisitSubQueryExpression (SubQueryExpression expression)
{
return expression;
}
protected virtual Expression VisitQuerySourceReferenceExpression (QuerySourceReferenceExpression expression)
{
return expression;
}
[Obsolete ("This method has been split. Use VisitExtensionExpression or VisitUnknownNonExtensionExpression instead. 1.13.75")]
protected internal virtual Expression VisitUnknownExpression (Expression expression)
{
throw new NotImplementedException ();
}
}
}
| |
#region Licence...
/*
The MIT License (MIT)
Copyright (c) 2014 Oleg Shilo
Permission is hereby granted,
free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion Licence...
using System;
using System.Collections.Generic;
using System.Xml.Linq;
namespace WixSharp
{
/// <summary>
/// This class defines website attributes. It is a close equivalent of WebSite WiX element.
/// </summary>
public partial class WebSite : WixEntity
{
/// <summary>
/// This is the name of the web site that will show up in the IIS management console.
/// </summary>
public string Description = "";
/// <summary>
/// Indicates if the WebSite is to be installed (created on IIS) or existing WebSite should be used to install the corresponding
/// WebApplication. The default <see cref="InstallWebSite"/> value is <c>false</c>
/// <para>Developers should be aware of the WebSite installation model imposed by WiX/MSI and use <see cref="InstallWebSite"/> carefully.</para>
/// <para>If <see cref="InstallWebSite"/> value is set to <c>false</c> the parent WebApplication (<see cref="T:WixSharp.IISVirtualDir"/>)
/// will be installed in the brand new (freshly created) WebSite or in the existing one if a site with the same address/port combination already exists
/// on IIS). The undesirable side affect of this deployment scenario is that if the existing WebSite was used to install the WebApplication it will be
/// deleted on IIS during uninstallation even if this WebSite has other WebApplications installed.</para>
/// <para>The "safer" option is to set <see cref="InstallWebSite"/> value to <c>true</c> (default value). In this case the WebApplication will
/// be installed in an existing WebSite with matching address/port. If the match is not found the installation will fail. During the uninstallation
/// only installed WebApplication will be removed from IIS.</para>
/// </summary>
public bool InstallWebSite = false;
/// <summary>
/// Initializes a new instance of the <see cref="WebSite"/> class.
/// </summary>
/// <param name="name">The name.</param>
public WebSite(string name)
{
this.Name = name;
}
///// <summary>
///// Collection of <see cref="T:WebSite.Certificate"/> associated with website.
///// </summary>
//public Certificate[] Certificates = new Certificate[0];
/// <summary>
/// Initializes a new instance of the <see cref="WebSite"/> class.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="addressDefinition">The address definition.</param>
public WebSite(string name, string addressDefinition)
{
this.Name = name;
this.AddressesDefinition = addressDefinition;
}
/// <summary>
/// Initializes a new instance of the <see cref="WebSite"/> class.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="addressDefinition">The address definition.</param>
/// <param name="description">The description.</param>
public WebSite(string name, string addressDefinition, string description)
{
this.Name = name;
this.AddressesDefinition = addressDefinition;
this.Description = description;
}
internal void ProcessAddressesDefinition()
{
if (!AddressesDefinition.IsEmpty())
{
List<WebAddress> addressesToAdd = new List<WebAddress>();
foreach (string addressDef in AddressesDefinition.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
{
try
{
string[] tokens = addressDef.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
string address = tokens[0];
string port = tokens[1];
if (tokens[1].ContainsWixConstants())
{
addressesToAdd.Add(new WebAddress { Address = address, AttributesDefinition = "Port=" + port });
}
else
{
addressesToAdd.Add(new WebAddress { Address = address, Port = Convert.ToInt32(port) });
}
}
catch (Exception e)
{
throw new Exception("Invalid AddressesDefinition", e);
}
}
this.addresses = addressesToAdd.ToArray();
}
}
/// <summary>
/// This class defines website address. It is a close equivalent of WebAddress WiX element.
/// </summary>
public partial class WebAddress : WixEntity
{
/// <summary>
/// The IP address for the web address. To specify the "All Unassigned" IP address, do not specify
/// this attribute or specify its value as "*". The IP address is also used to determine if the WebSite is already installed.
/// The IP address must match exactly (empty value matches "All Unassigned") unless "*" is used which will match any existing IP (including "All Unassigned").
/// </summary>
public string Address = "*";
/// <summary>
/// Sets the port number.
/// </summary>
public int Port = 0;
/// <summary>
/// Optional attributes of the <c>WebAddress Element</c> (e.g. Secure:YesNoPath).
/// </summary>
/// <example>
/// <code>
/// var address = new WebAddress
/// {
/// Port = 80,
/// Attributes = new Dictionary<string, string> { { "Secure", "Yes" } };
/// ...
/// </code>
/// </example>
public new Dictionary<string, string> Attributes { get { return base.Attributes; } set { base.Attributes = value; } }
}
/// <summary>
/// Specification for auto-generating the <see cref="T:WebSite.WebAddresses"/> collection.
/// <para>If <see cref="AddressesDefinition"/> is specified, the existing content of <see cref="Addresses"/> will be ignored
/// and replaced with the auto-generated one at compile time.</para>
/// </summary>
/// <example>
/// <c>webSite.AddressesDefinition = "*:80;*90";</c> will be parsed and converted to an array of <see cref="T:WixSharp.WebSite.WebAddress"/> as follows:
/// <code>
/// ...
/// webSite.Addresses = new []
/// {
/// new WebSite.WebAddress
/// {
/// Address = "*",
/// Port = 80
/// },
/// new WebSite.WebAddress
/// {
/// Address = "*",
/// Port = 80
/// }
/// }
/// </code>
/// </example>
public string AddressesDefinition = "";
/// <summary>
/// Collection of <see cref="T:WebSite.WebAddresses"/> associated with website.
/// <para>
/// The user specified values of <see cref="Addresses"/> will be ignored and replaced with the
/// auto-generated addresses if <see cref="AddressesDefinition"/> is specified either directly or via appropriate <see cref="WebSite"/> constructor.
/// </para>
/// </summary>
public WebAddress[] Addresses
{
get
{
ProcessAddressesDefinition();
return addresses;
}
set
{
addresses = value;
}
}
WebAddress[] addresses = new WebAddress[0];
}
/// <summary>
/// This class defines WebAppPool WiX element. It is used to specify the application pool for this application in IIS 6 applications.
/// </summary>
public partial class WebAppPool : WixEntity
{
/// <summary>
/// Initializes a new instance of the <see cref="WebAppPool"/> class.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="attributesDefinition">The attributes definition. This parameter is used to set encapsulated <see cref="T:WixSharp.WixEntity.AttributesDefinition"/>.</param>
public WebAppPool(string name, string attributesDefinition)
{
base.Name = name;
base.AttributesDefinition = attributesDefinition;
}
/// <summary>
/// Initializes a new instance of the <see cref="WebAppPool"/> class.
/// </summary>
/// <param name="name">The name.</param>
public WebAppPool(string name)
{
base.Name = name;
}
/// <summary>
/// Initializes a new instance of the <see cref="WebAppPool"/> class.
/// </summary>
public WebAppPool()
{
}
}
/// <summary>
/// This class defines WebDirProperites WiX element. The class itself has no distinctive behaviour nor schema. It is fully relying on
/// encapsulated <see cref="T:WixSharp.WixEntity.AttributesDefinition"/>.
/// </summary>
public partial class WebDirProperties : WixEntity
{
/// <summary>
/// Initializes a new instance of the <see cref="WebDirProperties"/> class.
/// </summary>
/// <param name="attributesDefinition">The attributes definition. This parameter is used to set encapsulated <see cref="T:WixSharp.WixEntity.AttributesDefinition"/>.</param>
public WebDirProperties(string attributesDefinition)
{
base.AttributesDefinition = attributesDefinition;
}
/// <summary>
/// Performs an implicit conversion from <see cref="System.String"/> to <see cref="WebDirProperties"/>.
/// </summary>
/// <param name="attributesDefinition">The attributes definition.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator WebDirProperties(string attributesDefinition)
{
return new WebDirProperties(attributesDefinition);
}
}
/// <summary>
/// This class defines IIS Virtual Directory. It is a close equivalent of WebVirtualDirectory WiX element.
/// </summary>
public class IISVirtualDir : WixEntity
{
/// <summary>
/// WebSite in which this virtual directory belongs.
/// </summary>
public WebSite WebSite = null;
#region WebVirtualDir Element Attributes
/// <summary>
/// Sets the application name, which is the URL relative path used to access this virtual directory. If not set, the <see cref="AppName"/> will be used.
/// </summary>
public string Alias = "";
#endregion WebVirtualDir Element Attributes
//IISVirtualDir-to-WebAppliction is one-to-one relationship
#region WebApplication Element attributes
/// <summary>
/// Sets the name of this Web application.
/// </summary>
public string AppName = "MyWebApp"; //WebApplication element attribute
/// <summary>
/// Sets the Enable Session State option. When enabled, you can set the session timeout using the SessionTimeout attribute.
/// </summary>
public bool? AllowSessions;// YesNoDefaultType //WebApplication element attribute
/// <summary>
/// Sets the option that enables response buffering in the application, which allows ASP script to set response headers anywhere in the script.
/// </summary>
public bool? Buffer;// YesNoDefaultType //WebApplication element attribute
/// <summary>
/// Enable ASP client-side script debugging.
/// </summary>
public bool? ClientDebugging;// YesNoDefaultType //WebApplication element attribute
/// <summary>
/// Sets the default script language for the site.
/// </summary>
public DefaultScript? DefaultScript; //WebApplication element attribute
/// <summary>
/// Sets the application isolation level for this application for pre-IIS 6 applications.
/// </summary>
public Isolation? Isolation; //WebApplication element attribute
/// <summary>
/// Sets the parent paths option, which allows a client to use relative paths to reach parent directories from this application.
/// </summary>
public bool? ParentPaths;// YesNoDefaultType //WebApplication element attribute
/// <summary>
/// Sets the timeout value for executing ASP scripts.
/// </summary>
public int? ScriptTimeout; //WebApplication element attribute
/// <summary>
/// Enable ASP server-side script debugging.
/// </summary>
public bool? ServerDebugging;// YesNoDefaultType //WebApplication element attribute
/// <summary>
/// Sets the timeout value for sessions in minutes.
/// </summary>
public int? SessionTimeout; //WebApplication element attribute
/// <summary>
/// References a WebAppPool instance to use as the application pool for this application in IIS 6 applications.
/// </summary>
public WebAppPool WebAppPool; //WebApplication element attribute
/// <summary>
/// WebDirProperites used by one or more WebSites.
/// </summary>
public WebDirProperties WebDirProperties;
#endregion WebApplication Element attributes
}
}
| |
//---------------------------------------------------------------------------
//
// File: SelectionEditor.cs
//
// Description:
// Provides basic ink editing
// Features:
//
// History:
// 2/14/2003 samgeo: Created
//
// Copyright (C) 2001 by Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
//#define TRACE_MAJOR // DO NOT LEAVE ENABLED IN CHECKED IN CODE
//#define TRACE_ADDITIONAL // DO NOT LEAVE ENABLED IN CHECKED IN CODE
using MS.Internal;
using MS.Internal.Controls;
using System;
using System.Security;
using System.Security.Permissions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Windows;
using System.Windows.Media;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Threading;
using System.Windows.Ink;
namespace MS.Internal.Ink
{
/// <summary>
/// SelectionEditor
/// </summary>
internal class SelectionEditor : EditingBehavior
{
//-------------------------------------------------------------------------------
//
// Constructors
//
//-------------------------------------------------------------------------------
#region Constructors
/// <summary>
/// SelectionEditor constructor
/// </summary>
internal SelectionEditor(EditingCoordinator editingCoordinator, InkCanvas inkCanvas) : base (editingCoordinator, inkCanvas)
{
}
#endregion Constructors
//-------------------------------------------------------------------------------
//
// Internal Methods
//
//-------------------------------------------------------------------------------
#region Internal Methods
/// <summary>
/// InkCanvas' Selection is changed
/// </summary>
internal void OnInkCanvasSelectionChanged()
{
Point currentPosition = Mouse.PrimaryDevice.GetPosition(InkCanvas.SelectionAdorner);
UpdateSelectionCursor(currentPosition);
}
#endregion Internal Methods
//-------------------------------------------------------------------------------
//
// Protected Methods
//
//-------------------------------------------------------------------------------
#region Protected Methods
/// <summary>
/// Attach to new scope as defined by this element.
/// </summary>
protected override void OnActivate()
{
// Add mouse event handles to InkCanvas.SelectionAdorner
InkCanvas.SelectionAdorner.AddHandler(Mouse.MouseDownEvent, new MouseButtonEventHandler(OnAdornerMouseButtonDownEvent));
InkCanvas.SelectionAdorner.AddHandler(Mouse.MouseMoveEvent, new MouseEventHandler(OnAdornerMouseMoveEvent));
InkCanvas.SelectionAdorner.AddHandler(Mouse.MouseEnterEvent, new MouseEventHandler(OnAdornerMouseMoveEvent));
InkCanvas.SelectionAdorner.AddHandler(Mouse.MouseLeaveEvent, new MouseEventHandler(OnAdornerMouseLeaveEvent));
Point currentPosition = Mouse.PrimaryDevice.GetPosition(InkCanvas.SelectionAdorner);
UpdateSelectionCursor(currentPosition);
}
/// <summary>
/// Called when the SelectionEditor is detached
/// </summary>
protected override void OnDeactivate()
{
// Remove all event hanlders.
InkCanvas.SelectionAdorner.RemoveHandler(Mouse.MouseDownEvent, new MouseButtonEventHandler(OnAdornerMouseButtonDownEvent));
InkCanvas.SelectionAdorner.RemoveHandler(Mouse.MouseMoveEvent, new MouseEventHandler(OnAdornerMouseMoveEvent));
InkCanvas.SelectionAdorner.RemoveHandler(Mouse.MouseEnterEvent, new MouseEventHandler(OnAdornerMouseMoveEvent));
InkCanvas.SelectionAdorner.RemoveHandler(Mouse.MouseLeaveEvent, new MouseEventHandler(OnAdornerMouseLeaveEvent));
}
/// <summary>
/// OnCommit
/// </summary>
/// <param name="commit"></param>
protected override void OnCommit(bool commit)
{
// Nothing to do.
}
/// <summary>
/// Retrieve the cursor
/// </summary>
/// <returns></returns>
protected override Cursor GetCurrentCursor()
{
// NTRAID:WINDOWSOS#1648430-2006/05/12-WAYNEZEN,
// We only show the selection related cursor when the mouse is over the SelectionAdorner.
// If mouse is outside of the SelectionAdorner, we let the system to pick up the default cursor.
if ( InkCanvas.SelectionAdorner.IsMouseOver )
{
return PenCursorManager.GetSelectionCursor(_hitResult,
(this.InkCanvas.FlowDirection == FlowDirection.RightToLeft));
}
else
{
return null;
}
}
#endregion Protected Methods
//-------------------------------------------------------------------------------
//
// Private Methods
//
//-------------------------------------------------------------------------------
#region Private Methods
/// <summary>
/// SelectionAdorner MouseButtonDown
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
/// <SecurityNote>
/// Critical: Calls critical method EditingCoordinator.ActivateDynamicBehavior
///
/// TreatAsSafe: Doesn't handle critical data. Also, this method is called by
/// SecurityTransparent code in the input system and can not be marked SecurityCritical.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private void OnAdornerMouseButtonDownEvent(object sender, MouseButtonEventArgs args)
{
// If the ButtonDown is raised by RightMouse, we should just bail out.
if ( (args.StylusDevice == null && args.LeftButton != MouseButtonState.Pressed) )
{
return;
}
Point pointOnSelectionAdorner = args.GetPosition(InkCanvas.SelectionAdorner);
InkCanvasSelectionHitResult hitResult = InkCanvasSelectionHitResult.None;
// Check if we should start resizing/moving
hitResult = HitTestOnSelectionAdorner(pointOnSelectionAdorner);
if ( hitResult != InkCanvasSelectionHitResult.None )
{
// We always use MouseDevice for the selection editing.
EditingCoordinator.ActivateDynamicBehavior(EditingCoordinator.SelectionEditingBehavior, args.Device);
}
else
{
//
//push selection and we're done
//
// If the current captured device is Stylus, we should activate the LassoSelectionBehavior with
// the Stylus. Otherwise, use mouse.
EditingCoordinator.ActivateDynamicBehavior(EditingCoordinator.LassoSelectionBehavior,
args.StylusDevice != null ? args.StylusDevice : args.Device);
}
}
/// <summary>
/// Selection Adorner MouseMove
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
/// <SecurityNote>
/// Critical: Calls critical method EditingCoordinator.ActivateDynamicBehavior
///
/// TreatAsSafe: Doesn't handle critical data. Also, this method is called by
/// SecurityTransparent code in the input system and can not be marked SecurityCritical.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private void OnAdornerMouseMoveEvent(object sender, MouseEventArgs args)
{
Point pointOnSelectionAdorner = args.GetPosition(InkCanvas.SelectionAdorner);
UpdateSelectionCursor(pointOnSelectionAdorner);
}
/// <summary>
/// Adorner MouseLeave Handler
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void OnAdornerMouseLeaveEvent(object sender, MouseEventArgs args)
{
// We are leaving the adorner, update our cursor.
EditingCoordinator.InvalidateBehaviorCursor(this);
}
/// <summary>
/// Hit test for the grab handles
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
private InkCanvasSelectionHitResult HitTestOnSelectionAdorner(Point position)
{
InkCanvasSelectionHitResult hitResult = InkCanvasSelectionHitResult.None;
if ( InkCanvas.InkCanvasSelection.HasSelection )
{
// First, do hit test on the adorner
hitResult = InkCanvas.SelectionAdorner.SelectionHandleHitTest(position);
// Now, check if ResizeEnabled or MoveEnabled has been set.
// If so, reset the grab handle.
if ( hitResult >= InkCanvasSelectionHitResult.TopLeft && hitResult <= InkCanvasSelectionHitResult.Left )
{
hitResult = InkCanvas.ResizeEnabled ? hitResult : InkCanvasSelectionHitResult.None;
}
else if ( hitResult == InkCanvasSelectionHitResult.Selection )
{
hitResult = InkCanvas.MoveEnabled ? hitResult : InkCanvasSelectionHitResult.None;
}
}
return hitResult;
}
/// <summary>
/// This method updates the cursor when the mouse is hovering ont the selection adorner.
/// It is called from
/// OnAdornerMouseLeaveEvent
/// OnAdornerMouseEvent
/// </summary>
/// <param name="hitPoint">the handle is being hit</param>
private void UpdateSelectionCursor(Point hitPoint)
{
InkCanvasSelectionHitResult hitResult = HitTestOnSelectionAdorner(hitPoint);
if ( _hitResult != hitResult )
{
// Keep the current handle
_hitResult = hitResult;
EditingCoordinator.InvalidateBehaviorCursor(this);
}
}
#endregion Private Methods
//-------------------------------------------------------------------------------
//
// Private Fields
//
//-------------------------------------------------------------------------------
#region Private Fields
private InkCanvasSelectionHitResult _hitResult;
#endregion Private Fields
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="FastPropertyAccessor.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using System.Collections;
using System.Security;
using System.Security.Permissions;
namespace System.Web.Util {
/*
* Property Accessor Generator class
*
* The purpose of this class is to generate some IL code on the fly that can efficiently
* access properties (and fields) of objects. This is an alternative to using
* very slow reflection.
*/
internal class FastPropertyAccessor {
private static object s_lockObject = new object();
private static FastPropertyAccessor s_accessorGenerator;
private static Hashtable s_accessorCache;
private static MethodInfo _getPropertyMethod;
private static MethodInfo _setPropertyMethod;
private static Type[] _getPropertyParameterList = new Type[] { typeof(object) };
private static Type[] _setPropertyParameterList = new Type[] { typeof(object), typeof(object) };
private static Type[] _interfacesToImplement;
private static int _uniqueId; // Used to generate unique type ID's.
// Property getter/setter must be public for codegen to access it.
// Static properties are ignored, since this class only works on instances of objects.
// Need to use DeclaredOnly to avoid AmbiguousMatchException if a property with
// a different return type is hidden.
private const BindingFlags _declaredFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly;
private ModuleBuilder _dynamicModule = null;
static FastPropertyAccessor() {
// Get the SetProperty method, and make sure it has
// the correct signature.
_getPropertyMethod = typeof(IWebPropertyAccessor).GetMethod("GetProperty");
_setPropertyMethod = typeof(IWebPropertyAccessor).GetMethod("SetProperty");
// This will be needed later, when building the dynamic class.
_interfacesToImplement = new Type[1];
_interfacesToImplement[0] = typeof(IWebPropertyAccessor);
}
private static String GetUniqueCompilationName() {
return Guid.NewGuid().ToString().Replace('-', '_');
}
Type GetPropertyAccessorTypeWithAssert(Type type, string propertyName,
PropertyInfo propInfo, FieldInfo fieldInfo) {
// Create the dynamic assembly if needed.
Type accessorType;
MethodInfo getterMethodInfo = null;
MethodInfo setterMethodInfo = null;
Type propertyType;
if (propInfo != null) {
// It'a a property
getterMethodInfo = propInfo.GetGetMethod();
setterMethodInfo = propInfo.GetSetMethod();
propertyType = propInfo.PropertyType;
}
else {
// If not, it must be a field
propertyType = fieldInfo.FieldType;
}
if (_dynamicModule == null) {
lock (this) {
if (_dynamicModule == null) {
// Use a unique name for each assembly.
String name = GetUniqueCompilationName();
AssemblyName assemblyName = new AssemblyName();
assemblyName.Name = "A_" + name;
// Create a new assembly.
AssemblyBuilder newAssembly =
Thread.GetDomain().DefineDynamicAssembly(assemblyName,
AssemblyBuilderAccess.Run,
null, //directory to persist assembly
true, //isSynchronized
null //assembly attributes
);
// Create a single module in the assembly.
_dynamicModule = newAssembly.DefineDynamicModule("M_" + name);
}
}
}
// Give the factory a unique name.
String typeName = System.Web.UI.Util.MakeValidTypeNameFromString(type.Name) +
"_" + propertyName + "_" + (_uniqueId++);
TypeBuilder accessorTypeBuilder = _dynamicModule.DefineType("T_" + typeName,
TypeAttributes.Public,
typeof(object),
_interfacesToImplement);
//
// Define the GetProperty method. It must be virtual to be an interface implementation.
//
MethodBuilder method = accessorTypeBuilder.DefineMethod("GetProperty",
MethodAttributes.Public |
MethodAttributes.Virtual,
typeof(Object),
_getPropertyParameterList);
// Generate IL. The generated IL corresponds to:
// "return ((TargetType) target).Blah;"
ILGenerator il = method.GetILGenerator();
if (getterMethodInfo != null) {
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Castclass, type);
// Generate the getter call based on whether it's a Property or Field
if (propInfo != null)
il.EmitCall(OpCodes.Callvirt, getterMethodInfo, null);
else
il.Emit(OpCodes.Ldfld, fieldInfo);
il.Emit(OpCodes.Box, propertyType);
il.Emit(OpCodes.Ret);
// Specify that this method implements GetProperty from the inherited interface.
accessorTypeBuilder.DefineMethodOverride(method, _getPropertyMethod);
}
else {
// Generate IL. The generated IL corresponds to "throw new InvalidOperationException"
ConstructorInfo cons = typeof(InvalidOperationException).GetConstructor(Type.EmptyTypes);
il.Emit(OpCodes.Newobj, cons);
il.Emit(OpCodes.Throw);
}
//
// Define the SetProperty method. It must be virtual to be an interface implementation.
//
method = accessorTypeBuilder.DefineMethod("SetProperty",
MethodAttributes.Public |
MethodAttributes.Virtual,
null,
_setPropertyParameterList);
il = method.GetILGenerator();
// Don't generate any code in the setter if it's a readonly property.
// We still need to have an implementation of SetProperty, but it does nothing.
if (fieldInfo != null || setterMethodInfo != null) {
// Generate IL. The generated IL corresponds to:
// "((TargetType) target).Blah = (PropType) val;"
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Castclass, type);
il.Emit(OpCodes.Ldarg_2);
if (propertyType.IsPrimitive) {
// Primitive type: deal with boxing
il.Emit(OpCodes.Unbox, propertyType);
// Emit the proper instruction for the type
if (propertyType == typeof(sbyte)) {
il.Emit(OpCodes.Ldind_I1);
}
else if (propertyType == typeof(byte)) {
il.Emit(OpCodes.Ldind_U1);
}
else if (propertyType == typeof(short)) {
il.Emit(OpCodes.Ldind_I2);
}
else if (propertyType == typeof(ushort)) {
il.Emit(OpCodes.Ldind_U2);
}
else if (propertyType == typeof(uint)) {
il.Emit(OpCodes.Ldind_U4);
}
else if (propertyType == typeof(int)) {
il.Emit(OpCodes.Ldind_I4);
}
else if (propertyType == typeof(long)) {
il.Emit(OpCodes.Ldind_I8);
}
else if (propertyType == typeof(ulong)) {
il.Emit(OpCodes.Ldind_I8); // Somehow, there is no Ldind_u8
}
else if (propertyType == typeof(bool)) {
il.Emit(OpCodes.Ldind_I1);
}
else if (propertyType == typeof(char)) {
il.Emit(OpCodes.Ldind_U2);
}
else if (propertyType == typeof(decimal)) {
il.Emit(OpCodes.Ldobj, propertyType);
}
else if (propertyType == typeof(float)) {
il.Emit(OpCodes.Ldind_R4);
}
else if (propertyType == typeof(double)) {
il.Emit(OpCodes.Ldind_R8);
}
else {
il.Emit(OpCodes.Ldobj, propertyType);
}
}
else if (propertyType.IsValueType) {
// Value type: deal with boxing
il.Emit(OpCodes.Unbox, propertyType);
il.Emit(OpCodes.Ldobj, propertyType);
}
else {
// No boxing involved: just generate a standard cast
il.Emit(OpCodes.Castclass, propertyType);
}
// Generate the assignment based on whether it's a Property or Field
if (propInfo != null)
il.EmitCall(OpCodes.Callvirt, setterMethodInfo, null);
else
il.Emit(OpCodes.Stfld, fieldInfo);
}
il.Emit(OpCodes.Ret);
// Specify that this method implements SetProperty from the inherited interface.
accessorTypeBuilder.DefineMethodOverride(method, _setPropertyMethod);
// Bake in the type.
accessorType = accessorTypeBuilder.CreateType();
return accessorType;
}
private static void GetPropertyInfo(Type type, string propertyName, out PropertyInfo propInfo, out FieldInfo fieldInfo, out Type declaringType) {
// First, try to find a property with that name. Type.GetProperty() without BindingFlags.Declared
// will throw AmbiguousMatchException if there is a hidden property with the same name and a
// different type (VSWhidbey 237437). This method finds the property with the specified name
// on the most specific type.
propInfo = GetPropertyMostSpecific(type, propertyName);
fieldInfo = null;
if (propInfo != null) {
// Get the most base Type where the property is first declared
MethodInfo baseCheckMethodInfo = propInfo.GetGetMethod();
if (baseCheckMethodInfo == null) {
baseCheckMethodInfo = propInfo.GetSetMethod();
}
declaringType = baseCheckMethodInfo.GetBaseDefinition().DeclaringType;
// DevDiv Bug 27734
// Ignore the declaring type if it's generic
if (declaringType.IsGenericType)
declaringType = type;
// If they're different, get a new PropertyInfo
if (declaringType != type) {
// We want the propertyInfo for the property specifically declared on the declaringType.
// So pass in the correct BindingFlags to avoid an AmbiguousMatchException, which would
// be thrown if the declaringType hides a property with the same name and a different type.
// VSWhidbey 518034
propInfo = declaringType.GetProperty(propertyName, _declaredFlags);
}
}
else {
// We couldn't find a property, so try a field
// Type.GetField can not throw AmbiguousMatchException like Type.GetProperty above.
fieldInfo = type.GetField(propertyName);
// If we couldn't find a field either, give up
if (fieldInfo == null)
throw new ArgumentException();
declaringType = fieldInfo.DeclaringType;
}
}
private static IWebPropertyAccessor GetPropertyAccessor(Type type, string propertyName) {
if (s_accessorGenerator == null || s_accessorCache == null) {
lock (s_lockObject) {
if (s_accessorGenerator == null || s_accessorCache == null) {
s_accessorGenerator = new FastPropertyAccessor();
s_accessorCache = new Hashtable();
}
}
}
// First, check if we have it cached
// Get a hash key based on the Type and the property name
int cacheKey = HashCodeCombiner.CombineHashCodes(
type.GetHashCode(), propertyName.GetHashCode());
IWebPropertyAccessor accessor = (IWebPropertyAccessor)s_accessorCache[cacheKey];
// It was cached, so just return it
if (accessor != null)
return accessor;
FieldInfo fieldInfo = null;
PropertyInfo propInfo = null;
Type declaringType;
GetPropertyInfo(type, propertyName, out propInfo, out fieldInfo, out declaringType);
// If the Type where the property/field is declared is not the same as the current
// Type, check if the declaring Type already has a cached accessor. This limits
// the number of different accessors we need to create. e.g. Every control has
// an ID property, but we'll end up only create one accessor for all of them.
int declaringTypeCacheKey = 0;
if (declaringType != type) {
// Get a hash key based on the declaring Type and the property name
declaringTypeCacheKey = HashCodeCombiner.CombineHashCodes(
declaringType.GetHashCode(), propertyName.GetHashCode());
accessor = (IWebPropertyAccessor) s_accessorCache[declaringTypeCacheKey];
// We have a cached accessor for the declaring type, so use it
if (accessor != null) {
// Cache the declaring type's accessor as ourselves
lock (s_accessorCache.SyncRoot) {
s_accessorCache[cacheKey] = accessor;
}
return accessor;
}
}
if (accessor == null) {
Type propertyAccessorType;
lock (s_accessorGenerator) {
propertyAccessorType = s_accessorGenerator.GetPropertyAccessorTypeWithAssert(
declaringType, propertyName, propInfo, fieldInfo);
}
// Create the type. This is the only place where Activator.CreateInstance is used,
// reducing the calls to it from 1 per instance to 1 per type.
accessor = (IWebPropertyAccessor) HttpRuntime.CreateNonPublicInstance(propertyAccessorType);
}
// Cache the accessor
lock (s_accessorCache.SyncRoot) {
s_accessorCache[cacheKey] = accessor;
if (declaringTypeCacheKey != 0)
s_accessorCache[declaringTypeCacheKey] = accessor;
}
return accessor;
}
internal static object GetProperty(object target, string propName, bool inDesigner) {
if (!inDesigner) {
IWebPropertyAccessor accessor = GetPropertyAccessor(target.GetType(), propName);
return accessor.GetProperty(target);
}
else {
// Dev10 bug 491386 - avoid CLR code path that causes an exception when designer uses two
// assemblies of the same name at different locations
FieldInfo fieldInfo = null;
PropertyInfo propInfo = null;
Type declaringType;
GetPropertyInfo(target.GetType(), propName, out propInfo, out fieldInfo, out declaringType);
if (propInfo != null) {
return propInfo.GetValue(target, null);
}
else if (fieldInfo != null) {
return fieldInfo.GetValue(target);
}
throw new ArgumentException();
}
}
// Finds the property with the specified name on the most specific type.
private static PropertyInfo GetPropertyMostSpecific(Type type, string name) {
PropertyInfo propInfo;
Type currentType = type;
while (currentType != null) {
propInfo = currentType.GetProperty(name, _declaredFlags);
if (propInfo != null) {
return propInfo;
}
else {
currentType = currentType.BaseType;
}
}
return null;
}
internal static void SetProperty(object target, string propName, object val, bool inDesigner) {
if (!inDesigner) {
IWebPropertyAccessor accessor = GetPropertyAccessor(target.GetType(), propName);
accessor.SetProperty(target, val);
}
else {
// Dev10 bug 491386 - avoid CLR code path that causes an exception when designer uses two
// assemblies of the same name at different locations
FieldInfo fieldInfo = null;
PropertyInfo propInfo = null;
Type declaringType = null;
GetPropertyInfo(target.GetType(), propName, out propInfo, out fieldInfo, out declaringType);
if (propInfo != null) {
propInfo.SetValue(target, val, null);
}
else if (fieldInfo != null) {
fieldInfo.SetValue(target, val);
}
else {
throw new ArgumentException();
}
}
}
}
public interface IWebPropertyAccessor {
object GetProperty(object target);
void SetProperty(object target, object value);
}
}
| |
//
// File.cs:
//
// Author:
// Julien Moutte <[email protected]>
//
// Copyright (C) 2011 FLUENDO S.A.
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// 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
//
using System.Collections.Generic;
using System;
namespace TagLib.Matroska
{
/// <summary>
/// Enumeration listing supported Matroska track types.
/// </summary>
public enum TrackType
{
/// <summary>
/// Video track type.
/// </summary>
Video = 0x1,
/// <summary>
/// Audio track type.
/// </summary>
Audio = 0x2,
/// <summary>
/// Complex track type.
/// </summary>
Complex = 0x3,
/// <summary>
/// Logo track type.
/// </summary>
Logo = 0x10,
/// <summary>
/// Subtitle track type.
/// </summary>
Subtitle = 0x11,
/// <summary>
/// Buttons track type.
/// </summary>
Buttons = 0x12,
/// <summary>
/// Control track type.
/// </summary>
Control = 0x20
}
/// <summary>
/// This class extends <see cref="TagLib.File" /> to provide tagging
/// and properties support for Matroska files.
/// </summary>
[SupportedMimeType ("taglib/mkv", "mkv")]
[SupportedMimeType ("taglib/mka", "mka")]
[SupportedMimeType ("taglib/mks", "mks")]
[SupportedMimeType ("video/webm")]
[SupportedMimeType ("video/x-matroska")]
public class File : TagLib.File
{
#region Private Fields
/// <summary>
/// Contains the tags for the file.
/// </summary>
private Matroska.Tag tag = new Matroska.Tag ();
/// <summary>
/// Contains the media properties.
/// </summary>
private Properties properties;
private UInt64 duration_unscaled;
private uint time_scale;
private TimeSpan duration;
#pragma warning disable 414 // Assigned, never used
private string title;
#pragma warning restore 414
private List<Track> tracks = new List<Track> ();
#endregion
#region Constructors
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="File" /> for a specified path in the local file
/// system and specified read style.
/// </summary>
/// <param name="path">
/// A <see cref="string" /> object containing the path of the
/// file to use in the new instance.
/// </param>
/// <param name="propertiesStyle">
/// A <see cref="ReadStyle" /> value specifying at what level
/// of accuracy to read the media properties, or <see
/// cref="ReadStyle.None" /> to ignore the properties.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" />.
/// </exception>
public File (string path, ReadStyle propertiesStyle)
: this (new File.LocalFileAbstraction (path),
propertiesStyle)
{
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="File" /> for a specified path in the local file
/// system with an average read style.
/// </summary>
/// <param name="path">
/// A <see cref="string" /> object containing the path of the
/// file to use in the new instance.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" />.
/// </exception>
public File (string path)
: this (path, ReadStyle.Average)
{
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="File" /> for a specified file abstraction and
/// specified read style.
/// </summary>
/// <param name="abstraction">
/// A <see cref="IFileAbstraction" /> object to use when
/// reading from and writing to the file.
/// </param>
/// <param name="propertiesStyle">
/// A <see cref="ReadStyle" /> value specifying at what level
/// of accuracy to read the media properties, or <see
/// cref="ReadStyle.None" /> to ignore the properties.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="abstraction" /> is <see langword="null"
/// />.
/// </exception>
public File (File.IFileAbstraction abstraction,
ReadStyle propertiesStyle)
: base (abstraction)
{
Mode = AccessMode.Read;
try {
Read (propertiesStyle);
TagTypesOnDisk = TagTypes;
}
finally {
Mode = AccessMode.Closed;
}
List<ICodec> codecs = new List<ICodec> ();
foreach (Track track in tracks) {
codecs.Add (track);
}
properties = new Properties (duration, codecs);
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="File" /> for a specified file abstraction with an
/// average read style.
/// </summary>
/// <param name="abstraction">
/// A <see cref="IFileAbstraction" /> object to use when
/// reading from and writing to the file.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="abstraction" /> is <see langword="null"
/// />.
/// </exception>
public File (File.IFileAbstraction abstraction)
: this (abstraction, ReadStyle.Average)
{
}
#endregion
#region Public Methods
/// <summary>
/// Saves the changes made in the current instance to the
/// file it represents.
/// </summary>
public override void Save ()
{
Mode = AccessMode.Write;
try {
}
finally {
Mode = AccessMode.Closed;
}
}
/// <summary>
/// Removes a set of tag types from the current instance.
/// </summary>
/// <param name="types">
/// A bitwise combined <see cref="TagLib.TagTypes" /> value
/// containing tag types to be removed from the file.
/// </param>
/// <remarks>
/// In order to remove all tags from a file, pass <see
/// cref="TagTypes.AllTags" /> as <paramref name="types" />.
/// </remarks>
public override void RemoveTags (TagLib.TagTypes types)
{
}
/// <summary>
/// Gets a tag of a specified type from the current instance,
/// optionally creating a new tag if possible.
/// </summary>
/// <param name="type">
/// A <see cref="TagLib.TagTypes" /> value indicating the
/// type of tag to read.
/// </param>
/// <param name="create">
/// A <see cref="bool" /> value specifying whether or not to
/// try and create the tag if one is not found.
/// </param>
/// <returns>
/// A <see cref="Tag" /> object containing the tag that was
/// found in or added to the current instance. If no
/// matching tag was found and none was created, <see
/// langword="null" /> is returned.
/// </returns>
public override TagLib.Tag GetTag (TagLib.TagTypes type,
bool create)
{
return null;
}
#endregion
#region Public Properties
/// <summary>
/// Gets a abstract representation of all tags stored in the
/// current instance.
/// </summary>
/// <value>
/// A <see cref="TagLib.Tag" /> object representing all tags
/// stored in the current instance.
/// </value>
public override TagLib.Tag Tag
{
get { return tag; }
}
/// <summary>
/// Gets the media properties of the file represented by the
/// current instance.
/// </summary>
/// <value>
/// A <see cref="TagLib.Properties" /> object containing the
/// media properties of the file represented by the current
/// instance.
/// </value>
public override TagLib.Properties Properties
{
get
{
return properties;
}
}
#endregion
#region Private Methods
/// <summary>
/// Reads the file with a specified read style.
/// </summary>
/// <param name="propertiesStyle">
/// A <see cref="ReadStyle" /> value specifying at what level
/// of accuracy to read the media properties, or <see
/// cref="ReadStyle.None" /> to ignore the properties.
/// </param>
private void Read (ReadStyle propertiesStyle)
{
ulong offset = 0;
while (offset < (ulong) Length) {
EBMLElement element = new EBMLElement (this, offset);
EBMLID ebml_id = (EBMLID) element.ID;
MatroskaID matroska_id = (MatroskaID) element.ID;
switch (ebml_id) {
case EBMLID.EBMLHeader:
ReadHeader (element);
break;
default:
break;
}
switch (matroska_id) {
case MatroskaID.MatroskaSegment:
ReadSegment (element);
break;
default:
break;
}
offset += element.Size;
}
}
private void ReadHeader (EBMLElement element)
{
string doctype = null;
ulong i = 0;
while (i < element.DataSize) {
EBMLElement child = new EBMLElement (this, element.DataOffset + i);
EBMLID ebml_id = (EBMLID) child.ID;
switch (ebml_id) {
case EBMLID.EBMLDocType:
doctype = child.ReadString ();
break;
default:
break;
}
i += child.Size;
}
// Check DocType
if (String.IsNullOrEmpty (doctype) || (doctype != "matroska" && doctype != "webm")) {
throw new UnsupportedFormatException ("DocType is not matroska or webm");
}
}
private void ReadSegment (EBMLElement element)
{
ulong i = 0;
while (i < element.DataSize) {
EBMLElement child = new EBMLElement (this, element.DataOffset + i);
MatroskaID matroska_id = (MatroskaID) child.ID;
switch (matroska_id) {
case MatroskaID.MatroskaTracks:
ReadTracks (child);
break;
case MatroskaID.MatroskaSegmentInfo:
ReadSegmentInfo (child);
break;
case MatroskaID.MatroskaTags:
ReadTags (child);
break;
case MatroskaID.MatroskaCluster:
// Get out of here when we reach the clusters for now.
return;
default:
break;
}
i += child.Size;
}
}
private void ReadTags (EBMLElement element)
{
ulong i = 0;
while (i < element.DataSize) {
EBMLElement child = new EBMLElement (this, element.DataOffset + i);
MatroskaID matroska_id = (MatroskaID) child.ID;
switch (matroska_id) {
case MatroskaID.MatroskaTag:
ReadTag (child);
break;
default:
break;
}
i += child.Size;
}
}
private void ReadTag (EBMLElement element)
{
ulong i = 0;
while (i < element.DataSize) {
EBMLElement child = new EBMLElement (this, element.DataOffset + i);
MatroskaID matroska_id = (MatroskaID) child.ID;
switch (matroska_id) {
case MatroskaID.MatroskaSimpleTag:
ReadSimpleTag (child);
break;
default:
break;
}
i += child.Size;
}
}
private void ReadSimpleTag (EBMLElement element)
{
ulong i = 0;
#pragma warning disable 219 // Assigned, never read
string tag_name = null, tag_language = null, tag_string = null;
#pragma warning restore 219
while (i < element.DataSize) {
EBMLElement child = new EBMLElement (this, element.DataOffset + i);
MatroskaID matroska_id = (MatroskaID) child.ID;
switch (matroska_id) {
case MatroskaID.MatroskaTagName:
tag_name = child.ReadString ();
break;
case MatroskaID.MatroskaTagLanguage:
tag_language = child.ReadString ();
break;
case MatroskaID.MatroskaTagString:
tag_string = child.ReadString ();
break;
default:
break;
}
i += child.Size;
}
if (tag_name == "AUTHOR") {
tag.Performers = new string [] { tag_string };
}
else if (tag_name == "TITLE") {
tag.Title = tag_string;
}
else if (tag_name == "ALBUM") {
tag.Album = tag_string;
}
else if (tag_name == "COMMENTS") {
tag.Comment = tag_string;
}
}
private void ReadSegmentInfo (EBMLElement element)
{
ulong i = 0;
while (i < element.DataSize) {
EBMLElement child = new EBMLElement (this, element.DataOffset + i);
MatroskaID matroska_id = (MatroskaID) child.ID;
switch (matroska_id) {
case MatroskaID.MatroskaDuration:
duration_unscaled = (UInt64) child.ReadDouble ();
if (time_scale > 0) {
duration = TimeSpan.FromSeconds (duration_unscaled * time_scale / 1000000000);
}
break;
case MatroskaID.MatroskaTimeCodeScale:
time_scale = child.ReadUInt ();
if (duration_unscaled > 0) {
duration = TimeSpan.FromSeconds (duration_unscaled * time_scale / 1000000000);
}
break;
case MatroskaID.MatroskaTitle:
title = child.ReadString ();
break;
default:
break;
}
i += child.Size;
}
}
private void ReadTracks (EBMLElement element)
{
ulong i = 0;
while (i < element.DataSize) {
EBMLElement child = new EBMLElement (this, element.DataOffset + i);
MatroskaID matroska_id = (MatroskaID) child.ID;
switch (matroska_id) {
case MatroskaID.MatroskaTrackEntry:
ReadTrackEntry (child);
break;
default:
break;
}
i += child.Size;
}
}
private void ReadTrackEntry (EBMLElement element)
{
ulong i = 0;
while (i < element.DataSize) {
EBMLElement child = new EBMLElement (this, element.DataOffset + i);
MatroskaID matroska_id = (MatroskaID) child.ID;
switch (matroska_id) {
case MatroskaID.MatroskaTrackType: {
TrackType track_type = (TrackType) child.ReadUInt ();
switch (track_type) {
case TrackType.Video: {
VideoTrack track = new VideoTrack (this, element);
tracks.Add (track);
break;
}
case TrackType.Audio: {
AudioTrack track = new AudioTrack (this, element);
tracks.Add (track);
break;
}
case TrackType.Subtitle: {
SubtitleTrack track = new SubtitleTrack (this, element);
tracks.Add (track);
break;
}
default:
break;
}
break;
}
default:
break;
}
i += child.Size;
}
}
#endregion
#region Private Properties
#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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace Microsoft.VisualBasic
{
public enum CallType
{
Get = 2,
Let = 4,
Method = 1,
Set = 8,
}
public sealed partial class Collection : System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList
{
public Collection() { }
public int Count { get { throw null; } }
public object this[int Index] { get { throw null; } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public object this[object Index] { get { throw null; } }
public object this[string Key] { get { throw null; } }
int System.Collections.ICollection.Count { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
bool System.Collections.IList.IsFixedSize { get { throw null; } }
bool System.Collections.IList.IsReadOnly { get { throw null; } }
object System.Collections.IList.this[int index] { get { throw null; } set { } }
public void Add(object Item, string Key = null, object Before = null, object After = null) { }
public void Clear() { }
public bool Contains(string Key) { throw null; }
public System.Collections.IEnumerator GetEnumerator() { throw null; }
public void Remove(int Index) { }
public void Remove(string Key) { }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
int System.Collections.IList.Add(object value) { throw null; }
void System.Collections.IList.Clear() { }
bool System.Collections.IList.Contains(object value) { throw null; }
int System.Collections.IList.IndexOf(object value) { throw null; }
void System.Collections.IList.Insert(int index, object value) { }
void System.Collections.IList.Remove(object value) { }
void System.Collections.IList.RemoveAt(int index) { }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=false, AllowMultiple=false)]
public sealed partial class ComClassAttribute : System.Attribute
{
public ComClassAttribute() { }
public ComClassAttribute(string _ClassID) { }
public ComClassAttribute(string _ClassID, string _InterfaceID) { }
public ComClassAttribute(string _ClassID, string _InterfaceID, string _EventId) { }
public string ClassID { get { throw null; } }
public string EventID { get { throw null; } }
public string InterfaceID { get { throw null; } }
public bool InterfaceShadows { get { throw null; } set { } }
}
public enum CompareMethod
{
Binary = 0,
Text = 1,
}
[Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute]
public sealed partial class Constants
{
internal Constants() { }
public const string vbBack = "\b";
public const Microsoft.VisualBasic.CompareMethod vbBinaryCompare = Microsoft.VisualBasic.CompareMethod.Binary;
public const string vbCr = "\r";
public const string vbCrLf = "\r\n";
public const string vbFormFeed = "\f";
public const string vbLf = "\n";
[System.ObsoleteAttribute("For a carriage return and line feed, use vbCrLf. For the current platform's newline, use System.Environment.NewLine.")]
public const string vbNewLine = "\r\n";
public const string vbNullChar = "\0";
public const string vbNullString = null;
public const string vbTab = "\t";
public const Microsoft.VisualBasic.CompareMethod vbTextCompare = Microsoft.VisualBasic.CompareMethod.Text;
public const string vbVerticalTab = "\v";
}
public sealed partial class ControlChars
{
public const char Back = '\b';
public const char Cr = '\r';
public const string CrLf = "\r\n";
public const char FormFeed = '\f';
public const char Lf = '\n';
public const string NewLine = "\r\n";
public const char NullChar = '\0';
public const char Quote = '"';
public const char Tab = '\t';
public const char VerticalTab = '\v';
public ControlChars() { }
}
[Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute]
public sealed partial class DateAndTime
{
internal DateAndTime() { }
public static System.DateTime Now { get { throw null; } }
public static System.DateTime Today { get { throw null; } }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class HideModuleNameAttribute : System.Attribute
{
public HideModuleNameAttribute() { }
}
[Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute]
public sealed partial class Information
{
internal Information() { }
public static bool IsArray(object VarName) { throw null; }
public static bool IsDate(object Expression) { throw null; }
public static bool IsDBNull(object Expression) { throw null; }
public static bool IsError(object Expression) { throw null; }
public static bool IsNothing(object Expression) { throw null; }
public static bool IsNumeric(object Expression) { throw null; }
public static bool IsReference(object Expression) { throw null; }
public static int LBound(System.Array Array, int Rank = 1) { throw null; }
public static int QBColor(int Color) { throw null; }
public static int RGB(int Red, int Green, int Blue) { throw null; }
public static string SystemTypeName(string VbName) { throw null; }
public static int UBound(System.Array Array, int Rank = 1) { throw null; }
public static Microsoft.VisualBasic.VariantType VarType(object VarName) { throw null; }
public static string VbTypeName(string UrtName) { throw null; }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public sealed partial class MyGroupCollectionAttribute : System.Attribute
{
public MyGroupCollectionAttribute(string typeToCollect, string createInstanceMethodName, string disposeInstanceMethodName, string defaultInstanceAlias) { }
public string CreateMethod { get { throw null; } }
public string DefaultInstanceAlias { get { throw null; } }
public string DisposeMethod { get { throw null; } }
public string MyGroupName { get { throw null; } }
}
[Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute]
public sealed partial class Strings
{
internal Strings() { }
public static int Asc(char String) { throw null; }
public static int Asc(string String) { throw null; }
public static int AscW(char String) { throw null; }
public static int AscW(string String) { throw null; }
public static char Chr(int CharCode) { throw null; }
public static char ChrW(int CharCode) { throw null; }
public static string[] Filter(object[] Source, string Match, bool Include = true, [Microsoft.VisualBasic.CompilerServices.OptionCompareAttribute]Microsoft.VisualBasic.CompareMethod Compare = Microsoft.VisualBasic.CompareMethod.Binary) { throw null; }
public static string[] Filter(string[] Source, string Match, bool Include = true, [Microsoft.VisualBasic.CompilerServices.OptionCompareAttribute]Microsoft.VisualBasic.CompareMethod Compare = Microsoft.VisualBasic.CompareMethod.Binary) { throw null; }
public static int InStr(int StartPos, string String1, string String2, [Microsoft.VisualBasic.CompilerServices.OptionCompareAttribute]Microsoft.VisualBasic.CompareMethod Compare = Microsoft.VisualBasic.CompareMethod.Binary) { throw null; }
public static int InStr(string String1, string String2, [Microsoft.VisualBasic.CompilerServices.OptionCompareAttribute]Microsoft.VisualBasic.CompareMethod Compare = Microsoft.VisualBasic.CompareMethod.Binary) { throw null; }
public static int InStrRev(string StringCheck, string StringMatch, int Start = -1, [Microsoft.VisualBasic.CompilerServices.OptionCompareAttribute]Microsoft.VisualBasic.CompareMethod Compare = Microsoft.VisualBasic.CompareMethod.Binary) { throw null; }
public static string Left(string str, int Length) { throw null; }
public static int Len(bool Expression) { throw null; }
public static int Len(byte Expression) { throw null; }
public static int Len(char Expression) { throw null; }
public static int Len(System.DateTime Expression) { throw null; }
public static int Len(decimal Expression) { throw null; }
public static int Len(double Expression) { throw null; }
public static int Len(short Expression) { throw null; }
public static int Len(int Expression) { throw null; }
public static int Len(long Expression) { throw null; }
public static int Len(object Expression) { throw null; }
[System.CLSCompliantAttribute(false)]
public static int Len(sbyte Expression) { throw null; }
public static int Len(float Expression) { throw null; }
public static int Len(string Expression) { throw null; }
[System.CLSCompliantAttribute(false)]
public static int Len(ushort Expression) { throw null; }
[System.CLSCompliantAttribute(false)]
public static int Len(uint Expression) { throw null; }
[System.CLSCompliantAttribute(false)]
public static int Len(ulong Expression) { throw null; }
public static string LTrim(string str) { throw null; }
public static string Mid(string str, int Start) { throw null; }
public static string Mid(string str, int Start, int Length) { throw null; }
public static string Right(string str, int Length) { throw null; }
public static string RTrim(string str) { throw null; }
public static string Trim(string str) { throw null; }
}
public enum VariantType
{
Array = 8192,
Boolean = 11,
Byte = 17,
Char = 18,
Currency = 6,
DataObject = 13,
Date = 7,
Decimal = 14,
Double = 5,
Empty = 0,
Error = 10,
Integer = 3,
Long = 20,
Null = 1,
Object = 9,
Short = 2,
Single = 4,
String = 8,
UserDefinedType = 36,
Variant = 12,
}
[System.AttributeUsageAttribute(System.AttributeTargets.Field, Inherited=false, AllowMultiple=false)]
public sealed partial class VBFixedArrayAttribute : System.Attribute
{
public VBFixedArrayAttribute(int UpperBound1) { }
public VBFixedArrayAttribute(int UpperBound1, int UpperBound2) { }
public int[] Bounds { get { throw null; } }
public int Length { get { throw null; } }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Field, Inherited=false, AllowMultiple=false)]
public sealed partial class VBFixedStringAttribute : System.Attribute
{
public VBFixedStringAttribute(int Length) { }
public int Length { get { throw null; } }
}
[Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute]
public sealed partial class VBMath
{
internal VBMath() { }
public static void Randomize() { }
public static void Randomize(double Number) { }
public static float Rnd() { throw null; }
public static float Rnd(float Number) { throw null; }
}
}
namespace Microsoft.VisualBasic.ApplicationServices
{
public partial class StartupEventArgs : System.ComponentModel.CancelEventArgs
{
public StartupEventArgs(System.Collections.ObjectModel.ReadOnlyCollection<string> args) { }
public System.Collections.ObjectModel.ReadOnlyCollection<string> CommandLine { get { throw null; } }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public partial class StartupNextInstanceEventArgs : System.EventArgs
{
public StartupNextInstanceEventArgs(System.Collections.ObjectModel.ReadOnlyCollection<string> args, bool bringToForegroundFlag) { }
public bool BringToForeground { get { throw null; } set { } }
public System.Collections.ObjectModel.ReadOnlyCollection<string> CommandLine { get { throw null; } }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public partial class UnhandledExceptionEventArgs : System.Threading.ThreadExceptionEventArgs
{
public UnhandledExceptionEventArgs(bool exitApplication, System.Exception exception) : base (default(System.Exception)) { }
public bool ExitApplication { get { throw null; } set { } }
}
}
namespace Microsoft.VisualBasic.CompilerServices
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class BooleanType
{
internal BooleanType() { }
public static bool FromObject(object Value) { throw null; }
public static bool FromString(string Value) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class Conversions
{
internal Conversions() { }
public static object ChangeType(object Expression, System.Type TargetType) { throw null; }
[System.ObsoleteAttribute("do not use this method", true)]
public static object FallbackUserDefinedConversion(object Expression, System.Type TargetType) { throw null; }
public static string FromCharAndCount(char Value, int Count) { throw null; }
public static string FromCharArray(char[] Value) { throw null; }
public static string FromCharArraySubset(char[] Value, int StartIndex, int Length) { throw null; }
public static bool ToBoolean(object Value) { throw null; }
public static bool ToBoolean(string Value) { throw null; }
public static byte ToByte(object Value) { throw null; }
public static byte ToByte(string Value) { throw null; }
public static char ToChar(object Value) { throw null; }
public static char ToChar(string Value) { throw null; }
public static char[] ToCharArrayRankOne(object Value) { throw null; }
public static char[] ToCharArrayRankOne(string Value) { throw null; }
public static System.DateTime ToDate(object Value) { throw null; }
public static System.DateTime ToDate(string Value) { throw null; }
public static decimal ToDecimal(bool Value) { throw null; }
public static decimal ToDecimal(object Value) { throw null; }
public static decimal ToDecimal(string Value) { throw null; }
public static double ToDouble(object Value) { throw null; }
public static double ToDouble(string Value) { throw null; }
public static T ToGenericParameter<T>(object Value) { throw null; }
public static int ToInteger(object Value) { throw null; }
public static int ToInteger(string Value) { throw null; }
public static long ToLong(object Value) { throw null; }
public static long ToLong(string Value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(object Value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(string Value) { throw null; }
public static short ToShort(object Value) { throw null; }
public static short ToShort(string Value) { throw null; }
public static float ToSingle(object Value) { throw null; }
public static float ToSingle(string Value) { throw null; }
public static string ToString(bool Value) { throw null; }
public static string ToString(byte Value) { throw null; }
public static string ToString(char Value) { throw null; }
public static string ToString(System.DateTime Value) { throw null; }
public static string ToString(decimal Value) { throw null; }
public static string ToString(decimal Value, System.Globalization.NumberFormatInfo NumberFormat) { throw null; }
public static string ToString(double Value) { throw null; }
public static string ToString(double Value, System.Globalization.NumberFormatInfo NumberFormat) { throw null; }
public static string ToString(short Value) { throw null; }
public static string ToString(int Value) { throw null; }
public static string ToString(long Value) { throw null; }
public static string ToString(object Value) { throw null; }
public static string ToString(float Value) { throw null; }
public static string ToString(float Value, System.Globalization.NumberFormatInfo NumberFormat) { throw null; }
[System.CLSCompliantAttribute(false)]
public static string ToString(uint Value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static string ToString(ulong Value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static uint ToUInteger(object Value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static uint ToUInteger(string Value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static ulong ToULong(object Value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static ulong ToULong(string Value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static ushort ToUShort(object Value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static ushort ToUShort(string Value) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class DecimalType
{
internal DecimalType() { }
public static decimal FromBoolean(bool Value) { throw null; }
public static decimal FromObject(object Value) { throw null; }
public static decimal FromObject(object Value, System.Globalization.NumberFormatInfo NumberFormat) { throw null; }
public static decimal FromString(string Value) { throw null; }
public static decimal FromString(string Value, System.Globalization.NumberFormatInfo NumberFormat) { throw null; }
public static decimal Parse(string Value, System.Globalization.NumberFormatInfo NumberFormat) { throw null; }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class DesignerGeneratedAttribute : System.Attribute
{
public DesignerGeneratedAttribute() { }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class DoubleType
{
internal DoubleType() { }
public static double FromObject(object Value) { throw null; }
public static double FromObject(object Value, System.Globalization.NumberFormatInfo NumberFormat) { throw null; }
public static double FromString(string Value) { throw null; }
public static double FromString(string Value, System.Globalization.NumberFormatInfo NumberFormat) { throw null; }
public static double Parse(string Value) { throw null; }
public static double Parse(string Value, System.Globalization.NumberFormatInfo NumberFormat) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class IncompleteInitialization : System.Exception
{
public IncompleteInitialization() { }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class NewLateBinding
{
internal NewLateBinding() { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.ObsoleteAttribute("do not use this method", true)]
public static object FallbackCall(object Instance, string MemberName, object[] Arguments, string[] ArgumentNames, bool IgnoreReturn) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.ObsoleteAttribute("do not use this method", true)]
public static object FallbackGet(object Instance, string MemberName, object[] Arguments, string[] ArgumentNames) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.ObsoleteAttribute("do not use this method", true)]
public static void FallbackIndexSet(object Instance, object[] Arguments, string[] ArgumentNames) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.ObsoleteAttribute("do not use this method", true)]
public static void FallbackIndexSetComplex(object Instance, object[] Arguments, string[] ArgumentNames, bool OptimisticSet, bool RValueBase) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.ObsoleteAttribute("do not use this method", true)]
public static object FallbackInvokeDefault1(object Instance, object[] Arguments, string[] ArgumentNames, bool ReportErrors) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.ObsoleteAttribute("do not use this method", true)]
public static object FallbackInvokeDefault2(object Instance, object[] Arguments, string[] ArgumentNames, bool ReportErrors) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.ObsoleteAttribute("do not use this method", true)]
public static void FallbackSet(object Instance, string MemberName, object[] Arguments) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.ObsoleteAttribute("do not use this method", true)]
public static void FallbackSetComplex(object Instance, string MemberName, object[] Arguments, bool OptimisticSet, bool RValueBase) { }
public static object LateCall(object Instance, System.Type Type, string MemberName, object[] Arguments, string[] ArgumentNames, System.Type[] TypeArguments, bool[] CopyBack, bool IgnoreReturn) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static object LateCallInvokeDefault(object Instance, object[] Arguments, string[] ArgumentNames, bool ReportErrors) { throw null; }
public static object LateGet(object Instance, System.Type Type, string MemberName, object[] Arguments, string[] ArgumentNames, System.Type[] TypeArguments, bool[] CopyBack) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static object LateGetInvokeDefault(object Instance, object[] Arguments, string[] ArgumentNames, bool ReportErrors) { throw null; }
public static object LateIndexGet(object Instance, object[] Arguments, string[] ArgumentNames) { throw null; }
public static void LateIndexSet(object Instance, object[] Arguments, string[] ArgumentNames) { }
public static void LateIndexSetComplex(object Instance, object[] Arguments, string[] ArgumentNames, bool OptimisticSet, bool RValueBase) { }
public static void LateSet(object Instance, System.Type Type, string MemberName, object[] Arguments, string[] ArgumentNames, System.Type[] TypeArguments) { }
public static void LateSet(object Instance, System.Type Type, string MemberName, object[] Arguments, string[] ArgumentNames, System.Type[] TypeArguments, bool OptimisticSet, bool RValueBase, Microsoft.VisualBasic.CallType CallType) { }
public static void LateSetComplex(object Instance, System.Type Type, string MemberName, object[] Arguments, string[] ArgumentNames, System.Type[] TypeArguments, bool OptimisticSet, bool RValueBase) { }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class ObjectFlowControl
{
internal ObjectFlowControl() { }
public static void CheckForSyncLockOnValueType(object Expression) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class ForLoopControl
{
internal ForLoopControl() { }
public static bool ForLoopInitObj(object Counter, object Start, object Limit, object StepValue, ref object LoopForResult, ref object CounterResult) { throw null; }
public static bool ForNextCheckDec(decimal count, decimal limit, decimal StepValue) { throw null; }
public static bool ForNextCheckObj(object Counter, object LoopObj, ref object CounterResult) { throw null; }
public static bool ForNextCheckR4(float count, float limit, float StepValue) { throw null; }
public static bool ForNextCheckR8(double count, double limit, double StepValue) { throw null; }
}
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class Operators
{
internal Operators() { }
public static object AddObject(object Left, object Right) { throw null; }
public static object AndObject(object Left, object Right) { throw null; }
public static object CompareObjectEqual(object Left, object Right, bool TextCompare) { throw null; }
public static object CompareObjectGreater(object Left, object Right, bool TextCompare) { throw null; }
public static object CompareObjectGreaterEqual(object Left, object Right, bool TextCompare) { throw null; }
public static object CompareObjectLess(object Left, object Right, bool TextCompare) { throw null; }
public static object CompareObjectLessEqual(object Left, object Right, bool TextCompare) { throw null; }
public static object CompareObjectNotEqual(object Left, object Right, bool TextCompare) { throw null; }
public static int CompareString(string Left, string Right, bool TextCompare) { throw null; }
public static object ConcatenateObject(object Left, object Right) { throw null; }
public static bool ConditionalCompareObjectEqual(object Left, object Right, bool TextCompare) { throw null; }
public static bool ConditionalCompareObjectGreater(object Left, object Right, bool TextCompare) { throw null; }
public static bool ConditionalCompareObjectGreaterEqual(object Left, object Right, bool TextCompare) { throw null; }
public static bool ConditionalCompareObjectLess(object Left, object Right, bool TextCompare) { throw null; }
public static bool ConditionalCompareObjectLessEqual(object Left, object Right, bool TextCompare) { throw null; }
public static bool ConditionalCompareObjectNotEqual(object Left, object Right, bool TextCompare) { throw null; }
public static object DivideObject(object Left, object Right) { throw null; }
public static object ExponentObject(object Left, object Right) { throw null; }
[System.ObsoleteAttribute("do not use this method", true)]
public static object FallbackInvokeUserDefinedOperator(object vbOp, object[] arguments) { throw null; }
public static object IntDivideObject(object Left, object Right) { throw null; }
public static object LeftShiftObject(object Operand, object Amount) { throw null; }
public static object ModObject(object Left, object Right) { throw null; }
public static object MultiplyObject(object Left, object Right) { throw null; }
public static object NegateObject(object Operand) { throw null; }
public static object NotObject(object Operand) { throw null; }
public static object OrObject(object Left, object Right) { throw null; }
public static object PlusObject(object Operand) { throw null; }
public static object RightShiftObject(object Operand, object Amount) { throw null; }
public static object SubtractObject(object Left, object Right) { throw null; }
public static object XorObject(object Left, object Right) { throw null; }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Parameter, Inherited=false, AllowMultiple=false)]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class OptionCompareAttribute : System.Attribute
{
public OptionCompareAttribute() { }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=false, AllowMultiple=false)]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class OptionTextAttribute : System.Attribute
{
public OptionTextAttribute() { }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class ProjectData
{
internal ProjectData() { }
public static void ClearProjectError() { }
public static void SetProjectError(System.Exception ex) { }
public static void SetProjectError(System.Exception ex, int lErl) { }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=false, AllowMultiple=false)]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class StandardModuleAttribute : System.Attribute
{
public StandardModuleAttribute() { }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class StaticLocalInitFlag
{
public short State;
public StaticLocalInitFlag() { }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class Utils
{
internal Utils() { }
public static System.Array CopyArray(System.Array arySrc, System.Array aryDest) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class Versioned
{
internal Versioned() { }
public static bool IsNumeric(object Expression) { throw null; }
public static string SystemTypeName(string VbName) { throw null; }
public static string VbTypeName(string SystemName) { throw null; }
}
}
namespace Microsoft.VisualBasic.Devices
{
public partial class NetworkAvailableEventArgs : System.EventArgs
{
public NetworkAvailableEventArgs(bool networkAvailable) { }
public bool IsNetworkAvailable { get { throw null; } }
}
}
namespace Microsoft.VisualBasic.FileIO
{
public enum DeleteDirectoryOption
{
DeleteAllContents = 5,
ThrowIfDirectoryNonEmpty = 4,
}
public enum FieldType
{
Delimited = 0,
FixedWidth = 1,
}
public partial class FileSystem
{
public FileSystem() { }
public static string CurrentDirectory { get { throw null; } set { } }
public static System.Collections.ObjectModel.ReadOnlyCollection<System.IO.DriveInfo> Drives { get { throw null; } }
public static string CombinePath(string baseDirectory, string relativePath) { throw null; }
public static void CopyDirectory(string sourceDirectoryName, string destinationDirectoryName) { }
public static void CopyDirectory(string sourceDirectoryName, string destinationDirectoryName, Microsoft.VisualBasic.FileIO.UIOption showUI) { }
public static void CopyDirectory(string sourceDirectoryName, string destinationDirectoryName, Microsoft.VisualBasic.FileIO.UIOption showUI, Microsoft.VisualBasic.FileIO.UICancelOption onUserCancel) { }
public static void CopyDirectory(string sourceDirectoryName, string destinationDirectoryName, bool overwrite) { }
public static void CopyFile(string sourceFileName, string destinationFileName) { }
public static void CopyFile(string sourceFileName, string destinationFileName, Microsoft.VisualBasic.FileIO.UIOption showUI) { }
public static void CopyFile(string sourceFileName, string destinationFileName, Microsoft.VisualBasic.FileIO.UIOption showUI, Microsoft.VisualBasic.FileIO.UICancelOption onUserCancel) { }
public static void CopyFile(string sourceFileName, string destinationFileName, bool overwrite) { }
public static void CreateDirectory(string directory) { }
public static void DeleteDirectory(string directory, Microsoft.VisualBasic.FileIO.DeleteDirectoryOption onDirectoryNotEmpty) { }
public static void DeleteDirectory(string directory, Microsoft.VisualBasic.FileIO.UIOption showUI, Microsoft.VisualBasic.FileIO.RecycleOption recycle) { }
public static void DeleteDirectory(string directory, Microsoft.VisualBasic.FileIO.UIOption showUI, Microsoft.VisualBasic.FileIO.RecycleOption recycle, Microsoft.VisualBasic.FileIO.UICancelOption onUserCancel) { }
public static void DeleteFile(string file) { }
public static void DeleteFile(string file, Microsoft.VisualBasic.FileIO.UIOption showUI, Microsoft.VisualBasic.FileIO.RecycleOption recycle) { }
public static void DeleteFile(string file, Microsoft.VisualBasic.FileIO.UIOption showUI, Microsoft.VisualBasic.FileIO.RecycleOption recycle, Microsoft.VisualBasic.FileIO.UICancelOption onUserCancel) { }
public static bool DirectoryExists(string directory) { throw null; }
public static bool FileExists(string file) { throw null; }
public static System.Collections.ObjectModel.ReadOnlyCollection<string> FindInFiles(string directory, string containsText, bool ignoreCase, Microsoft.VisualBasic.FileIO.SearchOption searchType) { throw null; }
public static System.Collections.ObjectModel.ReadOnlyCollection<string> FindInFiles(string directory, string containsText, bool ignoreCase, Microsoft.VisualBasic.FileIO.SearchOption searchType, params string[] fileWildcards) { throw null; }
public static System.Collections.ObjectModel.ReadOnlyCollection<string> GetDirectories(string directory) { throw null; }
public static System.Collections.ObjectModel.ReadOnlyCollection<string> GetDirectories(string directory, Microsoft.VisualBasic.FileIO.SearchOption searchType, params string[] wildcards) { throw null; }
public static System.IO.DirectoryInfo GetDirectoryInfo(string directory) { throw null; }
public static System.IO.DriveInfo GetDriveInfo(string drive) { throw null; }
public static System.IO.FileInfo GetFileInfo(string file) { throw null; }
public static System.Collections.ObjectModel.ReadOnlyCollection<string> GetFiles(string directory) { throw null; }
public static System.Collections.ObjectModel.ReadOnlyCollection<string> GetFiles(string directory, Microsoft.VisualBasic.FileIO.SearchOption searchType, params string[] wildcards) { throw null; }
public static string GetName(string path) { throw null; }
public static string GetParentPath(string path) { throw null; }
public static string GetTempFileName() { throw null; }
public static void MoveDirectory(string sourceDirectoryName, string destinationDirectoryName) { }
public static void MoveDirectory(string sourceDirectoryName, string destinationDirectoryName, Microsoft.VisualBasic.FileIO.UIOption showUI) { }
public static void MoveDirectory(string sourceDirectoryName, string destinationDirectoryName, Microsoft.VisualBasic.FileIO.UIOption showUI, Microsoft.VisualBasic.FileIO.UICancelOption onUserCancel) { }
public static void MoveDirectory(string sourceDirectoryName, string destinationDirectoryName, bool overwrite) { }
public static void MoveFile(string sourceFileName, string destinationFileName) { }
public static void MoveFile(string sourceFileName, string destinationFileName, Microsoft.VisualBasic.FileIO.UIOption showUI) { }
public static void MoveFile(string sourceFileName, string destinationFileName, Microsoft.VisualBasic.FileIO.UIOption showUI, Microsoft.VisualBasic.FileIO.UICancelOption onUserCancel) { }
public static void MoveFile(string sourceFileName, string destinationFileName, bool overwrite) { }
public static Microsoft.VisualBasic.FileIO.TextFieldParser OpenTextFieldParser(string file) { throw null; }
public static Microsoft.VisualBasic.FileIO.TextFieldParser OpenTextFieldParser(string file, params int[] fieldWidths) { throw null; }
public static Microsoft.VisualBasic.FileIO.TextFieldParser OpenTextFieldParser(string file, params string[] delimiters) { throw null; }
public static System.IO.StreamReader OpenTextFileReader(string file) { throw null; }
public static System.IO.StreamReader OpenTextFileReader(string file, System.Text.Encoding encoding) { throw null; }
public static System.IO.StreamWriter OpenTextFileWriter(string file, bool append) { throw null; }
public static System.IO.StreamWriter OpenTextFileWriter(string file, bool append, System.Text.Encoding encoding) { throw null; }
public static byte[] ReadAllBytes(string file) { throw null; }
public static string ReadAllText(string file) { throw null; }
public static string ReadAllText(string file, System.Text.Encoding encoding) { throw null; }
public static void RenameDirectory(string directory, string newName) { }
public static void RenameFile(string file, string newName) { }
public static void WriteAllBytes(string file, byte[] data, bool append) { }
public static void WriteAllText(string file, string text, bool append) { }
public static void WriteAllText(string file, string text, bool append, System.Text.Encoding encoding) { }
}
public partial class MalformedLineException : System.Exception
{
public MalformedLineException() { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
protected MalformedLineException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public MalformedLineException(string message) { }
public MalformedLineException(string message, System.Exception innerException) { }
public MalformedLineException(string message, long lineNumber) { }
public MalformedLineException(string message, long lineNumber, System.Exception innerException) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public long LineNumber { get { throw null; } set { } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public override string ToString() { throw null; }
}
public enum RecycleOption
{
DeletePermanently = 2,
SendToRecycleBin = 3,
}
public enum SearchOption
{
SearchAllSubDirectories = 3,
SearchTopLevelOnly = 2,
}
public partial class SpecialDirectories
{
public SpecialDirectories() { }
public static string AllUsersApplicationData { get { throw null; } }
public static string CurrentUserApplicationData { get { throw null; } }
public static string Desktop { get { throw null; } }
public static string MyDocuments { get { throw null; } }
public static string MyMusic { get { throw null; } }
public static string MyPictures { get { throw null; } }
public static string ProgramFiles { get { throw null; } }
public static string Programs { get { throw null; } }
public static string Temp { get { throw null; } }
}
public partial class TextFieldParser : System.IDisposable
{
public TextFieldParser(System.IO.Stream stream) { }
public TextFieldParser(System.IO.Stream stream, System.Text.Encoding defaultEncoding) { }
public TextFieldParser(System.IO.Stream stream, System.Text.Encoding defaultEncoding, bool detectEncoding) { }
public TextFieldParser(System.IO.Stream stream, System.Text.Encoding defaultEncoding, bool detectEncoding, bool leaveOpen) { }
public TextFieldParser(System.IO.TextReader reader) { }
public TextFieldParser(string path) { }
public TextFieldParser(string path, System.Text.Encoding defaultEncoding) { }
public TextFieldParser(string path, System.Text.Encoding defaultEncoding, bool detectEncoding) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public string[] CommentTokens { get { throw null; } set { } }
public string[] Delimiters { get { throw null; } set { } }
public bool EndOfData { get { throw null; } }
public string ErrorLine { get { throw null; } }
public long ErrorLineNumber { get { throw null; } }
public int[] FieldWidths { get { throw null; } set { } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public bool HasFieldsEnclosedInQuotes { get { throw null; } set { } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public long LineNumber { get { throw null; } }
public Microsoft.VisualBasic.FileIO.FieldType TextFieldType { get { throw null; } set { } }
public bool TrimWhiteSpace { get { throw null; } set { } }
public void Close() { }
protected virtual void Dispose(bool disposing) { }
~TextFieldParser() { }
public string PeekChars(int numberOfChars) { throw null; }
public string[] ReadFields() { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public string ReadLine() { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public string ReadToEnd() { throw null; }
public void SetDelimiters(params string[] delimiters) { }
public void SetFieldWidths(params int[] fieldWidths) { }
void System.IDisposable.Dispose() { }
}
public enum UICancelOption
{
DoNothing = 2,
ThrowException = 3,
}
public enum UIOption
{
AllDialogs = 3,
OnlyErrorDialogs = 2,
}
}
| |
using UnityEngine;
using UnityEngine.Rendering;
using System.Collections.Generic;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
#if ENABLE_RAYTRACING
public class HDRaytracingShadowManager
{
HDRenderPipelineAsset m_PipelineAsset = null;
RenderPipelineResources m_PipelineResources = null;
HDRaytracingManager m_RaytracingManager = null;
SharedRTManager m_SharedRTManager = null;
LightLoop m_LightLoop = null;
GBufferManager m_GbufferManager = null;
// Buffers that hold the intermediate data of the shadow algorithm
RTHandleSystem.RTHandle m_AnalyticProbBuffer = null;
RTHandleSystem.RTHandle m_DenoiseBuffer0 = null;
RTHandleSystem.RTHandle m_DenoiseBuffer1 = null;
RTHandleSystem.RTHandle m_RaytracingDirectionBuffer = null;
RTHandleSystem.RTHandle m_RaytracingDistanceBuffer = null;
// Array that holds the shadow textures for the area lights
RTHandleSystem.RTHandle m_AreaShadowTextureArray = null;
// String values
const string m_RayGenShaderName = "RayGenShadows";
const string m_RayGenShadowSingleName = "RayGenShadowSingle";
const string m_MissShaderName = "MissShaderShadows";
// Temporary variable that allows us to store the world to local matrix
Matrix4x4 worldToLocalArea = new Matrix4x4();
public HDRaytracingShadowManager()
{
}
public void Init(HDRenderPipelineAsset asset, HDRaytracingManager raytracingManager, SharedRTManager sharedRTManager, LightLoop lightLoop, GBufferManager gbufferManager)
{
// Keep track of the pipeline asset
m_PipelineAsset = asset;
m_PipelineResources = asset.renderPipelineResources;
// keep track of the ray tracing manager
m_RaytracingManager = raytracingManager;
// Keep track of the shared rt manager
m_SharedRTManager = sharedRTManager;
// The lightloop that holds all the lights of the scene
m_LightLoop = lightLoop;
// GBuffer manager that holds all the data for shading the samples
m_GbufferManager = gbufferManager;
// Allocate the intermediate buffers
m_AnalyticProbBuffer = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: GraphicsFormat.R16G16_SFloat, enableRandomWrite: true, useDynamicScale: true, xrInstancing: true, useMipMap: false, name: "AnalyticProbBuffer");
m_DenoiseBuffer0 = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite: true, useDynamicScale: true, xrInstancing: true, useMipMap: false, name: "DenoiseBuffer0");
m_DenoiseBuffer1 = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite: true, useDynamicScale: true, xrInstancing: true, useMipMap: false, name: "DenoiseBuffer1");
m_RaytracingDirectionBuffer = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite: true, useDynamicScale: true, xrInstancing: true,useMipMap: false, name: "RaytracingDirectionBuffer");
m_RaytracingDistanceBuffer = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: GraphicsFormat.R32_SFloat, enableRandomWrite: true, useDynamicScale: true, xrInstancing: true, useMipMap: false, name: "RaytracingDistanceBuffer");
// Allocate the final result texture
m_AreaShadowTextureArray = RTHandles.Alloc(Vector2.one, slices:4, dimension:TextureDimension.Tex2DArray, filterMode: FilterMode.Point, colorFormat: GraphicsFormat.R16_SFloat, enableRandomWrite: true, useDynamicScale: true, xrInstancing: true, useMipMap: false, name: "AreaShadowArrayBuffer");
}
public RTHandleSystem.RTHandle GetIntegrationTexture()
{
return m_DenoiseBuffer0;
}
public void Release()
{
RTHandles.Release(m_AreaShadowTextureArray);
RTHandles.Release(m_RaytracingDistanceBuffer);
RTHandles.Release(m_RaytracingDirectionBuffer);
RTHandles.Release(m_DenoiseBuffer1);
RTHandles.Release(m_DenoiseBuffer0);
RTHandles.Release(m_AnalyticProbBuffer);
}
void BindShadowTexture(CommandBuffer cmd)
{
cmd.SetGlobalTexture(HDShaderIDs._AreaShadowTexture, m_AreaShadowTextureArray);
}
static RTHandleSystem.RTHandle AreaShadowHistoryBufferAllocatorFunction(string viewName, int frameIndex, RTHandleSystem rtHandleSystem)
{
return rtHandleSystem.Alloc(Vector2.one, slices:4, dimension:TextureDimension.Tex2DArray, filterMode: FilterMode.Point, colorFormat: GraphicsFormat.R16G16_SFloat,
enableRandomWrite: true, useDynamicScale: true, xrInstancing: true, useMipMap: false, name: string.Format("AreaShadowHistoryBuffer{0}", frameIndex));
}
static RTHandleSystem.RTHandle AreaAnalyticHistoryBufferAllocatorFunction(string viewName, int frameIndex, RTHandleSystem rtHandleSystem)
{
return rtHandleSystem.Alloc(Vector2.one, slices:4, dimension:TextureDimension.Tex2DArray, filterMode: FilterMode.Point, colorFormat: GraphicsFormat.R16_SFloat,
enableRandomWrite: true, useDynamicScale: true, xrInstancing: true, useMipMap: false, name: "AnalyticHistoryBuffer");
}
public bool RenderAreaShadows(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext renderContext, uint frameCount)
{
// NOTE: Here we cannot clear the area shadow texture because it is a texture array. So we need to bind it and make sure no material will try to read it in the shaders
BindShadowTexture(cmd);
// Let's check all the resources and states to see if we should render the effect
HDRaytracingEnvironment rtEnvironement = m_RaytracingManager.CurrentEnvironment();
RaytracingShader shadowRaytrace = m_PipelineAsset.renderPipelineResources.shaders.areaShadowsRaytracingRT;
ComputeShader shadowsCompute = m_PipelineAsset.renderPipelineResources.shaders.areaShadowRaytracingCS;
ComputeShader shadowFilter = m_PipelineAsset.renderPipelineResources.shaders.areaShadowFilterCS;
// Make sure everything is valid
bool invalidState = rtEnvironement == null || rtEnvironement.raytracedShadows == false ||
hdCamera.frameSettings.litShaderMode != LitShaderMode.Deferred ||
shadowRaytrace == null || shadowsCompute == null || shadowFilter == null ||
m_PipelineResources.textures.owenScrambledTex == null || m_PipelineResources.textures.scramblingTex == null;
// If invalid state or ray-tracing acceleration structure, we stop right away
if (invalidState)
return false;
// Grab the TAA history buffers (SN/UN and Analytic value)
RTHandleSystem.RTHandle areaShadowHistoryArray = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.RaytracedAreaShadow)
?? hdCamera.AllocHistoryFrameRT((int)HDCameraFrameHistoryType.RaytracedAreaShadow, AreaShadowHistoryBufferAllocatorFunction, 1);
RTHandleSystem.RTHandle areaAnalyticHistoryArray = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.RaytracedAreaAnalytic)
?? hdCamera.AllocHistoryFrameRT((int)HDCameraFrameHistoryType.RaytracedAreaAnalytic, AreaAnalyticHistoryBufferAllocatorFunction, 1);
// Grab the acceleration structure for the target camera
RaytracingAccelerationStructure accelerationStructure = m_RaytracingManager.RequestAccelerationStructure(rtEnvironement.shadowLayerMask);
// Define the shader pass to use for the reflection pass
cmd.SetRaytracingShaderPass(shadowRaytrace, "VisibilityDXR");
// Set the acceleration structure for the pass
cmd.SetRaytracingAccelerationStructure(shadowRaytrace, HDShaderIDs._RaytracingAccelerationStructureName, accelerationStructure);
// Inject the ray-tracing sampling data
cmd.SetGlobalTexture(HDShaderIDs._OwenScrambledTexture, m_PipelineResources.textures.owenScrambledTex);
cmd.SetGlobalTexture(HDShaderIDs._ScramblingTexture, m_PipelineResources.textures.scramblingTex);
int frameIndex = hdCamera.IsTAAEnabled() ? hdCamera.taaFrameIndex : (int)frameCount % 8;
cmd.SetGlobalInt(HDShaderIDs._RaytracingFrameIndex, frameIndex);
// Grab the Filtering Kernels
int copyTAAHistoryKernel = shadowFilter.FindKernel("AreaShadowCopyTAAHistory");
int applyTAAKernel = shadowFilter.FindKernel("AreaShadowApplyTAA");
int updateAnalyticHistory= shadowFilter.FindKernel("AreaAnalyticHistoryUpdate");
int estimateNoiseKernel = shadowFilter.FindKernel("AreaShadowEstimateNoise");
int firstDenoiseKernel = shadowFilter.FindKernel("AreaShadowDenoiseFirstPass");
int secondDenoiseKernel = shadowFilter.FindKernel("AreaShadowDenoiseSecondPass");
// Texture dimensions
int texWidth = hdCamera.actualWidth;
int texHeight = hdCamera.actualHeight;
// Evaluate the dispatch parameters
int areaTileSize = 8;
int numTilesX = (texWidth + (areaTileSize - 1)) / areaTileSize;
int numTilesY = (texHeight + (areaTileSize - 1)) / areaTileSize;
// Inject the ray generation data
cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayBias, rtEnvironement.rayBias);
int numLights = m_LightLoop.m_lightList.lights.Count;
for(int lightIdx = 0; lightIdx < numLights; ++lightIdx)
{
// If this is not a rectangular area light or it won't have shadows, skip it
if(m_LightLoop.m_lightList.lights[lightIdx].lightType != GPULightType.Rectangle || m_LightLoop.m_lightList.lights[lightIdx].rayTracedAreaShadowIndex == -1) continue;
using (new ProfilingSample(cmd, "Raytrace Area Shadow", CustomSamplerId.RaytracingShadowIntegration.GetSampler()))
{
LightData currentLight = m_LightLoop.m_lightList.lights[lightIdx];
// We need to build the world to area light matrix
worldToLocalArea.SetColumn(0, currentLight.right);
worldToLocalArea.SetColumn(1, currentLight.up);
worldToLocalArea.SetColumn(2, currentLight.forward);
// Compensate the relative rendering if active
Vector3 lightPositionWS = currentLight.positionRWS;
if (ShaderConfig.s_CameraRelativeRendering != 0)
{
lightPositionWS += hdCamera.camera.transform.position;
}
worldToLocalArea.SetColumn(3, lightPositionWS);
worldToLocalArea.m33 = 1.0f;
worldToLocalArea = worldToLocalArea.inverse;
// We have noticed from extensive profiling that ray-trace shaders are not as effective for running per-pixel computation. In order to reduce that,
// we do a first prepass that compute the analytic term and probability and generates the first integration sample
if(rtEnvironement.splitIntegration)
{
int shadowComputeKernel = shadowsCompute.FindKernel("RaytracingAreaShadowPrepass");
// This pass evaluates the analytic value and the generates and outputs the first sample
cmd.SetComputeBufferParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._LightDatas, m_LightLoop.lightDatas);
cmd.SetComputeIntParam(shadowsCompute, HDShaderIDs._RaytracingTargetAreaLight, lightIdx);
cmd.SetComputeIntParam(shadowsCompute, HDShaderIDs._RaytracingNumSamples, rtEnvironement.shadowNumSamples);
cmd.SetComputeMatrixParam(shadowsCompute, HDShaderIDs._RaytracingAreaWorldToLocal, worldToLocalArea);
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer());
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer());
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._GBufferTexture[0], m_GbufferManager.GetBuffer(0));
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._GBufferTexture[1], m_GbufferManager.GetBuffer(1));
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._GBufferTexture[2], m_GbufferManager.GetBuffer(2));
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._GBufferTexture[3], m_GbufferManager.GetBuffer(3));
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._AreaCookieTextures, m_LightLoop.areaLightCookieManager.GetTexCache());
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._RaytracedAreaShadowIntegration, m_DenoiseBuffer0);
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._RaytracedAreaShadowSample, m_DenoiseBuffer1);
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._RaytracingDirectionBuffer, m_RaytracingDirectionBuffer);
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._RaytracingDistanceBuffer, m_RaytracingDistanceBuffer);
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._AnalyticProbBuffer, m_AnalyticProbBuffer);
cmd.DispatchCompute(shadowsCompute, shadowComputeKernel, numTilesX, numTilesY, 1);
// This pass will use the previously generated sample and add it to the integration buffer
cmd.SetRaytracingBufferParam(shadowRaytrace, m_RayGenShadowSingleName, HDShaderIDs._LightDatas, m_LightLoop.lightDatas);
cmd.SetRaytracingTextureParam(shadowRaytrace, m_RayGenShadowSingleName, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer());
cmd.SetRaytracingTextureParam(shadowRaytrace, m_RayGenShadowSingleName, HDShaderIDs._RaytracedAreaShadowSample, m_DenoiseBuffer1);
cmd.SetRaytracingTextureParam(shadowRaytrace, m_RayGenShadowSingleName, HDShaderIDs._RaytracedAreaShadowIntegration, m_DenoiseBuffer0);
cmd.SetRaytracingTextureParam(shadowRaytrace, m_RayGenShadowSingleName, HDShaderIDs._RaytracingDirectionBuffer, m_RaytracingDirectionBuffer);
cmd.SetRaytracingTextureParam(shadowRaytrace, m_RayGenShadowSingleName, HDShaderIDs._RaytracingDistanceBuffer, m_RaytracingDistanceBuffer);
cmd.SetRaytracingTextureParam(shadowRaytrace, m_RayGenShadowSingleName, HDShaderIDs._AnalyticProbBuffer, m_AnalyticProbBuffer);
cmd.DispatchRays(shadowRaytrace, m_RayGenShadowSingleName, (uint)hdCamera.actualWidth, (uint)hdCamera.actualHeight, 1);
// Let's do the following samples (if any)
for(int sampleIndex = 1; sampleIndex < rtEnvironement.shadowNumSamples; ++sampleIndex)
{
shadowComputeKernel = shadowsCompute.FindKernel("RaytracingAreaShadowNewSample");
// This pass generates a new sample based on the initial pre-pass
cmd.SetComputeBufferParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._LightDatas, m_LightLoop.lightDatas);
cmd.SetComputeIntParam(shadowsCompute, HDShaderIDs._RaytracingTargetAreaLight, lightIdx);
cmd.SetComputeIntParam(shadowsCompute, HDShaderIDs._RaytracingNumSamples, rtEnvironement.shadowNumSamples);
cmd.SetComputeIntParam(shadowsCompute, HDShaderIDs._RaytracingSampleIndex, sampleIndex);
cmd.SetComputeMatrixParam(shadowsCompute, HDShaderIDs._RaytracingAreaWorldToLocal, worldToLocalArea);
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer());
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer());
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._GBufferTexture[0], m_GbufferManager.GetBuffer(0));
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._GBufferTexture[1], m_GbufferManager.GetBuffer(1));
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._GBufferTexture[2], m_GbufferManager.GetBuffer(2));
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._GBufferTexture[3], m_GbufferManager.GetBuffer(3));
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._AreaCookieTextures, m_LightLoop.areaLightCookieManager.GetTexCache());
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._RaytracedAreaShadowIntegration, m_DenoiseBuffer0);
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._RaytracedAreaShadowSample, m_DenoiseBuffer1);
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._RaytracingDirectionBuffer, m_RaytracingDirectionBuffer);
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._RaytracingDistanceBuffer, m_RaytracingDistanceBuffer);
cmd.SetComputeTextureParam(shadowsCompute, shadowComputeKernel, HDShaderIDs._AnalyticProbBuffer, m_AnalyticProbBuffer);
cmd.DispatchCompute(shadowsCompute, shadowComputeKernel, numTilesX, numTilesY, 1);
// This pass will use the previously generated sample and add it to the integration buffer
cmd.SetRaytracingBufferParam(shadowRaytrace, m_RayGenShadowSingleName, HDShaderIDs._LightDatas, m_LightLoop.lightDatas);
cmd.SetRaytracingTextureParam(shadowRaytrace, m_RayGenShadowSingleName, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer());
cmd.SetRaytracingTextureParam(shadowRaytrace, m_RayGenShadowSingleName, HDShaderIDs._RaytracedAreaShadowSample, m_DenoiseBuffer1);
cmd.SetRaytracingTextureParam(shadowRaytrace, m_RayGenShadowSingleName, HDShaderIDs._RaytracedAreaShadowIntegration, m_DenoiseBuffer0);
cmd.SetRaytracingTextureParam(shadowRaytrace, m_RayGenShadowSingleName, HDShaderIDs._RaytracingDirectionBuffer, m_RaytracingDirectionBuffer);
cmd.SetRaytracingTextureParam(shadowRaytrace, m_RayGenShadowSingleName, HDShaderIDs._RaytracingDistanceBuffer, m_RaytracingDistanceBuffer);
cmd.SetRaytracingTextureParam(shadowRaytrace, m_RayGenShadowSingleName, HDShaderIDs._AnalyticProbBuffer, m_AnalyticProbBuffer);
cmd.DispatchRays(shadowRaytrace, m_RayGenShadowSingleName, (uint)hdCamera.actualWidth, (uint)hdCamera.actualHeight, 1);
}
}
else
{
// This pass generates the analytic value and will do the full integration
cmd.SetRaytracingBufferParam(shadowRaytrace, m_RayGenShaderName, HDShaderIDs._LightDatas, m_LightLoop.lightDatas);
cmd.SetRaytracingIntParam(shadowRaytrace, HDShaderIDs._RaytracingTargetAreaLight, lightIdx);
cmd.SetRaytracingIntParam(shadowRaytrace, HDShaderIDs._RaytracingNumSamples, rtEnvironement.shadowNumSamples);
cmd.SetRaytracingMatrixParam(shadowRaytrace, HDShaderIDs._RaytracingAreaWorldToLocal, worldToLocalArea);
cmd.SetRaytracingTextureParam(shadowRaytrace, m_RayGenShaderName, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer());
cmd.SetRaytracingTextureParam(shadowRaytrace, m_RayGenShaderName, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer());
cmd.SetRaytracingTextureParam(shadowRaytrace, m_RayGenShaderName, HDShaderIDs._GBufferTexture[0], m_GbufferManager.GetBuffer(0));
cmd.SetRaytracingTextureParam(shadowRaytrace, m_RayGenShaderName, HDShaderIDs._GBufferTexture[1], m_GbufferManager.GetBuffer(1));
cmd.SetRaytracingTextureParam(shadowRaytrace, m_RayGenShaderName, HDShaderIDs._GBufferTexture[2], m_GbufferManager.GetBuffer(2));
cmd.SetRaytracingTextureParam(shadowRaytrace, m_RayGenShaderName, HDShaderIDs._GBufferTexture[3], m_GbufferManager.GetBuffer(3));
cmd.SetRaytracingIntParam(shadowRaytrace, HDShaderIDs._RayCountEnabled, m_RaytracingManager.rayCountManager.RayCountIsEnabled());
cmd.SetRaytracingTextureParam(shadowRaytrace, m_RayGenShaderName, HDShaderIDs._RayCountTexture, m_RaytracingManager.rayCountManager.rayCountTexture);
cmd.SetRaytracingTextureParam(shadowRaytrace, m_RayGenShaderName, HDShaderIDs._AreaCookieTextures, m_LightLoop.areaLightCookieManager.GetTexCache());
cmd.SetRaytracingTextureParam(shadowRaytrace, m_RayGenShaderName, HDShaderIDs._AnalyticProbBuffer, m_AnalyticProbBuffer);
cmd.SetRaytracingTextureParam(shadowRaytrace, m_RayGenShaderName, HDShaderIDs._RaytracedAreaShadowIntegration, m_DenoiseBuffer0);
cmd.DispatchRays(shadowRaytrace, m_RayGenShaderName, (uint)hdCamera.actualWidth, (uint)hdCamera.actualHeight, 1);
}
}
using (new ProfilingSample(cmd, "Combine Area Shadow", CustomSamplerId.RaytracingShadowCombination.GetSampler()))
{
// Global parameters
cmd.SetComputeIntParam(shadowFilter, HDShaderIDs._RaytracingDenoiseRadius, rtEnvironement.shadowFilterRadius);
cmd.SetComputeIntParam(shadowFilter, HDShaderIDs._RaytracingShadowSlot, m_LightLoop.m_lightList.lights[lightIdx].rayTracedAreaShadowIndex);
// Given that we can't read and write into the same buffer, we store the current frame value and the history in the denoisebuffer1
cmd.SetComputeTextureParam(shadowFilter, copyTAAHistoryKernel, HDShaderIDs._AreaShadowHistoryRW, areaShadowHistoryArray);
cmd.SetComputeTextureParam(shadowFilter, copyTAAHistoryKernel, HDShaderIDs._DenoiseInputTexture, m_DenoiseBuffer0);
cmd.SetComputeTextureParam(shadowFilter, copyTAAHistoryKernel, HDShaderIDs._DenoiseOutputTextureRW, m_DenoiseBuffer1);
cmd.DispatchCompute(shadowFilter, copyTAAHistoryKernel, numTilesX, numTilesY, 1);
// Apply a vectorized temporal filtering pass and store it back in the denoisebuffer0 with the analytic value in the third channel
var historyScale = new Vector2(hdCamera.actualWidth / (float)areaShadowHistoryArray.rt.width, hdCamera.actualHeight / (float)areaShadowHistoryArray.rt.height);
cmd.SetComputeVectorParam(shadowFilter, HDShaderIDs._RTHandleScaleHistory, historyScale);
cmd.SetComputeTextureParam(shadowFilter, applyTAAKernel, HDShaderIDs._AnalyticProbBuffer, m_AnalyticProbBuffer);
cmd.SetComputeTextureParam(shadowFilter, applyTAAKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer());
cmd.SetComputeTextureParam(shadowFilter, applyTAAKernel, HDShaderIDs._AnalyticHistoryBuffer, areaAnalyticHistoryArray);
cmd.SetComputeTextureParam(shadowFilter, applyTAAKernel, HDShaderIDs._DenoiseInputTexture, m_DenoiseBuffer1);
cmd.SetComputeTextureParam(shadowFilter, applyTAAKernel, HDShaderIDs._DenoiseOutputTextureRW, m_DenoiseBuffer0);
cmd.SetComputeTextureParam(shadowFilter, applyTAAKernel, HDShaderIDs._AreaShadowHistoryRW, areaShadowHistoryArray);
cmd.DispatchCompute(shadowFilter, applyTAAKernel, numTilesX, numTilesY, 1);
// Now that we do not need it anymore, update the anyltic history
cmd.SetComputeTextureParam(shadowFilter, updateAnalyticHistory, HDShaderIDs._AnalyticHistoryBuffer, areaAnalyticHistoryArray);
cmd.SetComputeTextureParam(shadowFilter, updateAnalyticHistory, HDShaderIDs._AnalyticProbBuffer, m_AnalyticProbBuffer);
cmd.DispatchCompute(shadowFilter, updateAnalyticHistory, numTilesX, numTilesY, 1);
if (rtEnvironement.shadowFilterRadius > 0)
{
// Inject parameters for noise estimation
cmd.SetComputeTextureParam(shadowFilter, estimateNoiseKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer());
cmd.SetComputeTextureParam(shadowFilter, estimateNoiseKernel, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer());
cmd.SetComputeTextureParam(shadowFilter, estimateNoiseKernel, HDShaderIDs._ScramblingTexture, m_PipelineResources.textures.scramblingTex);
// Noise estimation pre-pass
cmd.SetComputeTextureParam(shadowFilter, estimateNoiseKernel, HDShaderIDs._DenoiseInputTexture, m_DenoiseBuffer0);
cmd.SetComputeTextureParam(shadowFilter, estimateNoiseKernel, HDShaderIDs._DenoiseOutputTextureRW, m_DenoiseBuffer1);
cmd.DispatchCompute(shadowFilter, estimateNoiseKernel, numTilesX, numTilesY, 1);
// Reinject parameters for denoising
cmd.SetComputeTextureParam(shadowFilter, firstDenoiseKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer());
cmd.SetComputeTextureParam(shadowFilter, firstDenoiseKernel, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer());
cmd.SetComputeTextureParam(shadowFilter, firstDenoiseKernel, HDShaderIDs._AreaShadowTextureRW, m_AreaShadowTextureArray);
// First denoising pass
cmd.SetComputeTextureParam(shadowFilter, firstDenoiseKernel, HDShaderIDs._DenoiseInputTexture, m_DenoiseBuffer1);
cmd.SetComputeTextureParam(shadowFilter, firstDenoiseKernel, HDShaderIDs._DenoiseOutputTextureRW, m_DenoiseBuffer0);
cmd.DispatchCompute(shadowFilter, firstDenoiseKernel, numTilesX, numTilesY, 1);
}
// Reinject parameters for denoising
cmd.SetComputeTextureParam(shadowFilter, secondDenoiseKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer());
cmd.SetComputeTextureParam(shadowFilter, secondDenoiseKernel, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer());
cmd.SetComputeTextureParam(shadowFilter, secondDenoiseKernel, HDShaderIDs._AreaShadowTextureRW, m_AreaShadowTextureArray);
// Second (and final) denoising pass
cmd.SetComputeTextureParam(shadowFilter, secondDenoiseKernel, HDShaderIDs._DenoiseInputTexture, m_DenoiseBuffer0);
cmd.DispatchCompute(shadowFilter, secondDenoiseKernel, numTilesX, numTilesY, 1);
}
}
// If this is the right debug mode and we have at least one light, write the first shadow to the denoise texture
HDRenderPipeline hdrp = (RenderPipelineManager.currentPipeline as HDRenderPipeline);
if (FullScreenDebugMode.RaytracedAreaShadow == hdrp.m_CurrentDebugDisplaySettings.data.fullScreenDebugMode && numLights > 0)
{
int targetKernel = shadowFilter.FindKernel("WriteShadowTextureDebug");
cmd.SetComputeIntParam(shadowFilter, HDShaderIDs._RaytracingShadowSlot, 0);
cmd.SetComputeTextureParam(shadowFilter, targetKernel, HDShaderIDs._AreaShadowTextureRW, m_AreaShadowTextureArray);
cmd.SetComputeTextureParam(shadowFilter, targetKernel, HDShaderIDs._DenoiseOutputTextureRW, m_DenoiseBuffer0);
cmd.DispatchCompute(shadowFilter, targetKernel, numTilesX, numTilesY, 1);
hdrp.PushFullScreenDebugTexture(hdCamera, cmd, m_DenoiseBuffer0, FullScreenDebugMode.RaytracedAreaShadow);
}
return true;
}
}
#endif
}
| |
// ***********************************************************************
// Copyright (c) 2008-2015 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Reflection;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Builders;
namespace NUnit.Framework
{
/// <summary>
/// Marks a method as a parameterized test suite and provides arguments for each test case.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited=false)]
public class TestCaseAttribute : NUnitAttribute, ITestBuilder, ITestCaseData, IImplyFixture
{
#region Constructors
/// <summary>
/// Construct a TestCaseAttribute with a list of arguments.
/// This constructor is not CLS-Compliant
/// </summary>
/// <param name="arguments"></param>
public TestCaseAttribute(params object[] arguments)
{
RunState = RunState.Runnable;
if (arguments == null)
Arguments = new object[] { null };
else
Arguments = arguments;
Properties = new PropertyBag();
}
/// <summary>
/// Construct a TestCaseAttribute with a single argument
/// </summary>
/// <param name="arg"></param>
public TestCaseAttribute(object arg)
{
RunState = RunState.Runnable;
Arguments = new object[] { arg };
Properties = new PropertyBag();
}
/// <summary>
/// Construct a TestCaseAttribute with a two arguments
/// </summary>
/// <param name="arg1"></param>
/// <param name="arg2"></param>
public TestCaseAttribute(object arg1, object arg2)
{
RunState = RunState.Runnable;
Arguments = new object[] { arg1, arg2 };
Properties = new PropertyBag();
}
/// <summary>
/// Construct a TestCaseAttribute with a three arguments
/// </summary>
/// <param name="arg1"></param>
/// <param name="arg2"></param>
/// <param name="arg3"></param>
public TestCaseAttribute(object arg1, object arg2, object arg3)
{
RunState = RunState.Runnable;
Arguments = new object[] { arg1, arg2, arg3 };
Properties = new PropertyBag();
}
#endregion
#region ITestData Members
/// <summary>
/// Gets or sets the name of the test.
/// </summary>
/// <value>The name of the test.</value>
public string TestName { get; set; }
/// <summary>
/// Gets or sets the RunState of this test case.
/// </summary>
public RunState RunState { get; private set; }
/// <summary>
/// Gets the list of arguments to a test case
/// </summary>
public object[] Arguments { get; }
/// <summary>
/// Gets the properties of the test case
/// </summary>
public IPropertyBag Properties { get; }
#endregion
#region ITestCaseData Members
/// <summary>
/// Gets or sets the expected result.
/// </summary>
/// <value>The result.</value>
public object ExpectedResult
{
get { return _expectedResult; }
set
{
_expectedResult = value;
HasExpectedResult = true;
}
}
private object _expectedResult;
/// <summary>
/// Returns true if the expected result has been set
/// </summary>
public bool HasExpectedResult { get; private set; }
#endregion
#region Other Properties
/// <summary>
/// Gets or sets the description.
/// </summary>
/// <value>The description.</value>
public string Description
{
get { return Properties.Get(PropertyNames.Description) as string; }
set { Properties.Set(PropertyNames.Description, value); }
}
/// <summary>
/// The author of this test
/// </summary>
public string Author
{
get { return Properties.Get(PropertyNames.Author) as string; }
set { Properties.Set(PropertyNames.Author, value); }
}
/// <summary>
/// The type that this test is testing
/// </summary>
public Type TestOf
{
get { return _testOf; }
set
{
_testOf = value;
Properties.Set(PropertyNames.TestOf, value.FullName);
}
}
private Type _testOf;
/// <summary>
/// Gets or sets the reason for ignoring the test
/// </summary>
public string Ignore
{
get { return IgnoreReason; }
set { IgnoreReason = value; }
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="NUnit.Framework.TestCaseAttribute"/> is explicit.
/// </summary>
/// <value>
/// <c>true</c> if explicit; otherwise, <c>false</c>.
/// </value>
public bool Explicit
{
get { return RunState == RunState.Explicit; }
set { RunState = value ? RunState.Explicit : RunState.Runnable; }
}
/// <summary>
/// Gets or sets the reason for not running the test.
/// </summary>
/// <value>The reason.</value>
public string Reason
{
get { return Properties.Get(PropertyNames.SkipReason) as string; }
set { Properties.Set(PropertyNames.SkipReason, value); }
}
/// <summary>
/// Gets or sets the ignore reason. When set to a non-null
/// non-empty value, the test is marked as ignored.
/// </summary>
/// <value>The ignore reason.</value>
public string IgnoreReason
{
get { return Reason; }
set
{
RunState = RunState.Ignored;
Reason = value;
}
}
#if PLATFORM_DETECTION
/// <summary>
/// Comma-delimited list of platforms to run the test for
/// </summary>
public string IncludePlatform { get; set; }
/// <summary>
/// Comma-delimited list of platforms to not run the test for
/// </summary>
public string ExcludePlatform { get; set; }
#endif
/// <summary>
/// Gets and sets the category for this test case.
/// May be a comma-separated list of categories.
/// </summary>
public string Category
{
get { return Properties.Get(PropertyNames.Category) as string; }
set
{
foreach (string cat in value.Split(new char[] { ',' }) )
Properties.Add(PropertyNames.Category, cat);
}
}
#endregion
#region Helper Methods
private TestCaseParameters GetParametersForTestCase(IMethodInfo method)
{
TestCaseParameters parms;
try
{
IParameterInfo[] parameters = method.GetParameters();
int argsNeeded = parameters.Length;
int argsProvided = Arguments.Length;
parms = new TestCaseParameters(this);
// Special handling for ExpectedResult (see if it needs to be converted into method return type)
object expectedResultInTargetType;
if (parms.HasExpectedResult
&& PerformSpecialConversion(parms.ExpectedResult, method.ReturnType.Type, out expectedResultInTargetType))
{
parms.ExpectedResult = expectedResultInTargetType;
}
// Special handling for params arguments
if (argsNeeded > 0 && argsProvided >= argsNeeded - 1)
{
IParameterInfo lastParameter = parameters[argsNeeded - 1];
Type lastParameterType = lastParameter.ParameterType;
Type elementType = lastParameterType.GetElementType();
if (lastParameterType.IsArray && lastParameter.IsDefined<ParamArrayAttribute>(false))
{
if (argsProvided == argsNeeded)
{
if (!lastParameterType.IsInstanceOfType(parms.Arguments[argsProvided - 1]))
{
Array array = Array.CreateInstance(elementType, 1);
array.SetValue(parms.Arguments[argsProvided - 1], 0);
parms.Arguments[argsProvided - 1] = array;
}
}
else
{
object[] newArglist = new object[argsNeeded];
for (int i = 0; i < argsNeeded && i < argsProvided; i++)
newArglist[i] = parms.Arguments[i];
int length = argsProvided - argsNeeded + 1;
Array array = Array.CreateInstance(elementType, length);
for (int i = 0; i < length; i++)
array.SetValue(parms.Arguments[argsNeeded + i - 1], i);
newArglist[argsNeeded - 1] = array;
parms.Arguments = newArglist;
argsProvided = argsNeeded;
}
}
}
//Special handling for optional parameters
if (parms.Arguments.Length < argsNeeded)
{
object[] newArgList = new object[parameters.Length];
Array.Copy(parms.Arguments, newArgList, parms.Arguments.Length);
//Fill with Type.Missing for remaining required parameters where optional
for (var i = parms.Arguments.Length; i < parameters.Length; i++)
{
if (parameters[i].IsOptional)
newArgList[i] = Type.Missing;
else
{
if (i < parms.Arguments.Length)
newArgList[i] = parms.Arguments[i];
else
throw new TargetParameterCountException(string.Format(
"Method requires {0} arguments but TestCaseAttribute only supplied {1}",
argsNeeded,
argsProvided));
}
}
parms.Arguments = newArgList;
}
//if (method.GetParameters().Length == 1 && method.GetParameters()[0].ParameterType == typeof(object[]))
// parms.Arguments = new object[]{parms.Arguments};
// Special handling when sole argument is an object[]
if (argsNeeded == 1 && method.GetParameters()[0].ParameterType == typeof(object[]))
{
if (argsProvided > 1 ||
argsProvided == 1 && parms.Arguments[0].GetType() != typeof(object[]))
{
parms.Arguments = new object[] { parms.Arguments };
}
}
if (argsProvided == argsNeeded)
PerformSpecialConversions(parms.Arguments, parameters);
}
catch (Exception ex)
{
parms = new TestCaseParameters(ex);
}
return parms;
}
/// <summary>
/// Performs several special conversions allowed by NUnit in order to
/// permit arguments with types that cannot be used in the constructor
/// of an Attribute such as TestCaseAttribute or to simplify their use.
/// </summary>
/// <param name="arglist">The arguments to be converted</param>
/// <param name="parameters">The ParameterInfo array for the method</param>
private static void PerformSpecialConversions(object[] arglist, IParameterInfo[] parameters)
{
for (int i = 0; i < arglist.Length; i++)
{
object arg = arglist[i];
Type targetType = parameters[i].ParameterType;
object argAsTargetType;
if (PerformSpecialConversion(arg, targetType, out argAsTargetType))
{
arglist[i] = argAsTargetType;
}
}
}
/// <summary>
/// Performs several special conversions allowed by NUnit in order to
/// permit arguments with types that cannot be used in the constructor
/// of an Attribute such as TestCaseAttribute or to simplify their use.
/// </summary>
/// <param name="arg">The argument to be converted</param>
/// <param name="targetType">The target <see cref="Type"/> in which the <paramref name="arg"/> should be converted</param>
/// <param name="argAsTargetType">If conversion was successfully applied, the <paramref name="arg"/> converted into <paramref name="targetType"/></param>
/// <returns>
/// <c>true</c> if <paramref name="arg"/> was converted and <paramref name="argAsTargetType"/> should be used;
/// <c>false</c> is no conversion was applied and <paramref name="argAsTargetType"/> should be ignored
/// </returns>
private static bool PerformSpecialConversion(object arg, Type targetType, out object argAsTargetType)
{
argAsTargetType = null;
if (arg == null)
return false;
if (targetType.IsInstanceOfType(arg))
return false;
if (arg.GetType().FullName == "System.DBNull")
{
argAsTargetType = null;
return true;
}
bool convert = false;
if (targetType == typeof(short) || targetType == typeof(byte) || targetType == typeof(sbyte) || targetType == typeof(long?) ||
targetType == typeof(short?) || targetType == typeof(byte?) || targetType == typeof(sbyte?) || targetType == typeof(double?))
{
convert = arg is int;
}
else if (targetType == typeof(decimal) || targetType == typeof(decimal?))
{
convert = arg is double || arg is string || arg is int;
}
else if (targetType == typeof(DateTime) || targetType == typeof(DateTime?))
{
convert = arg is string;
}
if (convert)
{
Type convertTo = targetType.GetTypeInfo().IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>) ?
targetType.GetGenericArguments()[0] : targetType;
argAsTargetType = Convert.ChangeType(arg, convertTo, System.Globalization.CultureInfo.InvariantCulture);
return true;
}
// Convert.ChangeType doesn't work for TimeSpan from string
if ((targetType == typeof(TimeSpan) || targetType == typeof(TimeSpan?)) && arg is string)
{
argAsTargetType = TimeSpan.Parse((string)arg);
return true;
}
return false;
}
#endregion
#region ITestBuilder Members
/// <summary>
/// Builds a single test from the specified method and context.
/// </summary>
/// <param name="method">The MethodInfo for which tests are to be constructed.</param>
/// <param name="suite">The suite to which the tests will be added.</param>
public IEnumerable<TestMethod> BuildFrom(IMethodInfo method, Test suite)
{
TestMethod test = new NUnitTestCaseBuilder().BuildTestMethod(method, suite, GetParametersForTestCase(method));
#if PLATFORM_DETECTION
if (IncludePlatform != null || ExcludePlatform != null)
{
if (test.RunState == RunState.NotRunnable || test.RunState == RunState.Ignored)
{
yield return test;
yield break;
}
var platformHelper = new PlatformHelper();
if (!platformHelper.IsPlatformSupported(this))
{
test.RunState = RunState.Skipped;
test.Properties.Add(PropertyNames.SkipReason, platformHelper.Reason);
}
}
#endif
yield return test;
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.